hexsha
stringlengths
40
40
size
int64
22
2.4M
ext
stringclasses
5 values
lang
stringclasses
1 value
max_stars_repo_path
stringlengths
3
260
max_stars_repo_name
stringlengths
5
109
max_stars_repo_head_hexsha
stringlengths
40
78
max_stars_repo_licenses
listlengths
1
9
max_stars_count
float64
1
191k
max_stars_repo_stars_event_min_datetime
stringlengths
24
24
max_stars_repo_stars_event_max_datetime
stringlengths
24
24
max_issues_repo_path
stringlengths
3
260
max_issues_repo_name
stringlengths
5
109
max_issues_repo_head_hexsha
stringlengths
40
78
max_issues_repo_licenses
listlengths
1
9
max_issues_count
float64
1
67k
max_issues_repo_issues_event_min_datetime
stringlengths
24
24
max_issues_repo_issues_event_max_datetime
stringlengths
24
24
max_forks_repo_path
stringlengths
3
260
max_forks_repo_name
stringlengths
5
109
max_forks_repo_head_hexsha
stringlengths
40
78
max_forks_repo_licenses
listlengths
1
9
max_forks_count
float64
1
105k
max_forks_repo_forks_event_min_datetime
stringlengths
24
24
max_forks_repo_forks_event_max_datetime
stringlengths
24
24
content
stringlengths
22
2.4M
avg_line_length
float64
5
169k
max_line_length
int64
5
786k
alphanum_fraction
float64
0.06
0.95
matches
listlengths
1
11
d14f350117550cbba4a98f6175ee6e12efb90e17
16,395
h
C
src/project_cpp.h
wuyakuma/cmftStudio
8a953802548379db3917cf7c368dc211a54f4841
[ "BSD-2-Clause" ]
null
null
null
src/project_cpp.h
wuyakuma/cmftStudio
8a953802548379db3917cf7c368dc211a54f4841
[ "BSD-2-Clause" ]
null
null
null
src/project_cpp.h
wuyakuma/cmftStudio
8a953802548379db3917cf7c368dc211a54f4841
[ "BSD-2-Clause" ]
null
null
null
/* * Copyright 2014-2015 Dario Manesku. All rights reserved. * License: http://www.opensource.org/licenses/BSD-2-Clause */ #include "common/common.h" #include "project.h" #include "guimanager.h" // imguiEnqueueStatusMessage(), outputWindow*() #include "settings.h" // Settings #include "inflatedeflate.h" // DeflateFileReader/Writer #include <bx/string.h> // bx::snprintf #define CMFTSTUDIO_CHUNK_MAGIC_PROJECT BX_MAKEFOURCC('c', 's', 0x6, 0x9) #define CMFTSTUDIO_CHUNK_MAGIC_MAT_BEGIN BX_MAKEFOURCC('M', 'A', 'T', 0x0) #define CMFTSTUDIO_CHUNK_MAGIC_MAT_END BX_MAKEFOURCC('M', 'A', 'T', 0x1) #define CMFTSTUDIO_CHUNK_MAGIC_MIN_BEGIN BX_MAKEFOURCC('M', 'I', 'N', 0x0) #define CMFTSTUDIO_CHUNK_MAGIC_MIN_END BX_MAKEFOURCC('M', 'I', 'N', 0x1) #define CMFTSTUDIO_CHUNK_MAGIC_MSH_BEGIN BX_MAKEFOURCC('M', 'S', 'H', 0x0) #define CMFTSTUDIO_CHUNK_MAGIC_MSH_END BX_MAKEFOURCC('M', 'S', 'H', 0x1) #define CMFTSTUDIO_CHUNK_MAGIC_MSH_MISC BX_MAKEFOURCC('M', 'S', 'H', 0x2) #define CMFTSTUDIO_CHUNK_MAGIC_MSH_DONE BX_MAKEFOURCC('M', 'S', 'H', 0x3) #define CMFTSTUDIO_CHUNK_MAGIC_ENV_BEGIN BX_MAKEFOURCC('E', 'N', 'V', 0x0) #define CMFTSTUDIO_CHUNK_MAGIC_ENV_END BX_MAKEFOURCC('E', 'N', 'V', 0x1) #define CMFTSTUDIO_CHUNK_MAGIC_TEX_BEGIN BX_MAKEFOURCC('T', 'E', 'X', 0x0) #define CMFTSTUDIO_CHUNK_MAGIC_TEX_END BX_MAKEFOURCC('T', 'E', 'X', 0x1) #define CMFTSTUDIO_CHUNK_MAGIC_SET_BEGIN BX_MAKEFOURCC('S', 'E', 'T', 0x0) #define CMFTSTUDIO_CHUNK_MAGIC_SET_END BX_MAKEFOURCC('S', 'E', 'T', 0x1) #define CMFTSTUDIO_CHUNK_MAGIC_PROJECT_END BX_MAKEFOURCC(0x9, 0x6, 'c', 's') bool projectSave(const char* _path , const cs::MaterialList& _materialList , const cs::EnvList& _envList , const cs::MeshInstanceList& _meshInstList , const Settings& _settings , int32_t _compressionLevel , OnValidFile _validFileCallback , OnInvalidFile _invalidFileCallback ) { // Open file for writing. FILE* file = fopen(_path, "wb"); if (NULL == file) { if (NULL != _invalidFileCallback) { char msg[128] = "Error: Invalid output file specified!"; if (NULL != _path && '\0' != _path[0]) { bx::snprintf(msg, sizeof(msg), "Error: Unable to open output file \'%s\'!", _path); } _invalidFileCallback(CmftStudioProject::FileIOError, msg); } return false; } // File is valid. if (NULL != _validFileCallback) { _validFileCallback(0, NULL); } outputWindowPrint("Saving '%s'...", bx::baseName(_path)); outputWindowPrint("Path: '%s'", _path); outputWindowPrint("--------------------------------------------------------------------------------------------------------"); outputWindowPrint(" Resource | Name | Size "); outputWindowPrint("--------------------------------------------------------------------------------------------------------"); enum { BiggestId = 128 }; dm::SetT<BiggestId> texturesToWrite; dm::SetT<BiggestId> meshesToWrite; // Write magic. const uint32_t magic = CMFTSTUDIO_CHUNK_MAGIC_PROJECT; fwrite(&magic, 1, sizeof(magic), file); // Write major version. const uint16_t versionMajor = g_versionMajor; fwrite(&versionMajor, 1, sizeof(versionMajor), file); // Write minor version. const uint16_t versionMinor = g_versionMinor; fwrite(&versionMinor, 1, sizeof(versionMinor), file); // Write compressed data from now on using DeflateFileWriter. cs::DeflateFileWriter writer(file, cs::g_stackAlloc, DM_MEGABYTES(100), DM_MEGABYTES(100), _compressionLevel); const uint64_t totalBefore = writer.getTotal(); const uint64_t compressedBefore = writer.getTotalCompressed(); // Write materials. for (uint16_t ii = 0, end = _materialList.count(); ii < end; ++ii) { const cs::MaterialHandle material = _materialList[ii]; const cs::Material& materialObj = cs::getObj(material); for (uint8_t jj = 0; jj < cs::Material::TextureCount; ++jj) { const cs::Material::Texture tex = (cs::Material::Texture)jj; const cs::TextureHandle texture = materialObj.get(tex); if (isValid(texture)) { texturesToWrite.safeInsert(texture.m_idx); } } const uint64_t before = writer.getTotal(); bx::write(&writer, CMFTSTUDIO_CHUNK_MAGIC_MAT_BEGIN); cs::write(&writer, material); bx::write(&writer, CMFTSTUDIO_CHUNK_MAGIC_MAT_END); const uint64_t after = writer.getTotal(); const uint64_t size = after-before; outputWindowPrint("[Material] %79s - %4u.%03u MB", cs::getName(material), dm::U_UMB(size), size); } // Write used textures. for (uint16_t ii = 0, end = texturesToWrite.count(); ii < end; ++ii) { const cs::TextureHandle texture = { texturesToWrite.getValueAt(ii) }; const uint64_t before = writer.getTotal(); bx::write(&writer, CMFTSTUDIO_CHUNK_MAGIC_TEX_BEGIN); cs::write(&writer, texture); bx::write(&writer, CMFTSTUDIO_CHUNK_MAGIC_TEX_END); const uint64_t after = writer.getTotal(); const uint64_t size = after-before; outputWindowPrint("[Texture] %79s - %4u.%03u MB", cs::getName(texture), dm::U_UMB(size), size); } // Write mesh instances. for (uint16_t ii = 0, end = _meshInstList.count(); ii < end; ++ii) { meshesToWrite.safeInsert(_meshInstList[ii].m_mesh.m_idx); bx::write(&writer, CMFTSTUDIO_CHUNK_MAGIC_MIN_BEGIN); cs::write(&writer, _meshInstList[ii]); bx::write(&writer, CMFTSTUDIO_CHUNK_MAGIC_MIN_END); } // Write meshes. for (uint16_t ii = 0, end = meshesToWrite.count(); ii < end; ++ii) { const cs::MeshHandle mesh = { meshesToWrite.getValueAt(ii) }; const uint64_t before = writer.getTotal(); bx::write(&writer, CMFTSTUDIO_CHUNK_MAGIC_MSH_BEGIN); cs::write(&writer, mesh); bx::write(&writer, CMFTSTUDIO_CHUNK_MAGIC_MSH_END); const uint64_t after = writer.getTotal(); const uint64_t size = after-before; outputWindowPrint("[Mesh] %79s - %4u.%03u MB", cs::getName(mesh), dm::U_UMB(size), size); } // Write environments. for (uint16_t ii = 0, end = _envList.count(); ii < end; ++ii) { const cs::EnvHandle env = _envList[ii]; const uint64_t before = writer.getTotal(); bx::write(&writer, CMFTSTUDIO_CHUNK_MAGIC_ENV_BEGIN); cs::write(&writer, env); bx::write(&writer, CMFTSTUDIO_CHUNK_MAGIC_ENV_END); const uint64_t after = writer.getTotal(); const uint64_t size = after-before; outputWindowPrint("[Env] %79s - %4u.%03u MB", cs::getName(env), dm::U_UMB(size), size); } // Write settings. bx::write(&writer, CMFTSTUDIO_CHUNK_MAGIC_SET_BEGIN); ::write(&writer, _settings); bx::write(&writer, CMFTSTUDIO_CHUNK_MAGIC_SET_END); // Write project end magic. bx::write(&writer, CMFTSTUDIO_CHUNK_MAGIC_PROJECT_END); // All done. writer.flush(); fclose(file); const uint64_t totalAfter = writer.getTotal(); const uint64_t totalSize = totalAfter-totalBefore; const uint64_t compressedAfter = writer.getTotalCompressed(); const uint64_t compressedSize = compressedAfter-compressedBefore; outputWindowPrint("--------------------------------------------------------------------------------------------------------"); outputWindowPrint("<Total> %83u.%03u MB", dm::U_UMB(totalSize)); outputWindowPrint("<Compressed> %83u.%03u MB", dm::U_UMB(compressedSize)); outputWindowPrint("--------------------------------------------------------------------------------------------------------"); return true; } bool projectLoad(const char* _path , cs::TextureList& _textureList , cs::MaterialList& _materialList , cs::EnvList& _envList , cs::MeshInstanceList& _meshInstList , Settings& _settings , OnValidFile _validFileCallback , OnInvalidFile _invalidFileCallback , cs::StackAllocatorI* _stackAlloc ) { // Open file. bx::CrtFileReader fileReader; if (fileReader.open(_path)) { if (NULL != _invalidFileCallback) { char msg[128] = "Error: Invalid input file specified!"; if (NULL != _path && '\0' != _path[0]) { bx::snprintf(msg, sizeof(msg), "Error: Unable to open input file \'%s\'!", _path); } _invalidFileCallback(CmftStudioProject::FileIOError, msg); } return false; } // Check magic. uint32_t magic = 0; fileReader.read(&magic, 4); if (magic != CMFTSTUDIO_CHUNK_MAGIC_PROJECT) { fileReader.close(); if (NULL != _invalidFileCallback) { const char* msg = "Error: Selected file is not a valid cmftStudio project."; _invalidFileCallback(CmftStudioProject::InvalidMagic, msg); } return false; } // Check version. uint16_t versionMajor = 0; fileReader.read(&versionMajor, sizeof(versionMajor)); uint16_t versionMinor = 0; fileReader.read(&versionMinor, sizeof(versionMinor)); if (versionMajor != g_versionMajor || versionMinor != g_versionMinor) { fileReader.close(); if (NULL != _invalidFileCallback) { char msg[128]; bx::snprintf(msg, sizeof(msg) , "Project file (v%d.%d) is not compatibile with the current version of cmftStudio (v%d.%d)!" , versionMajor, versionMinor , g_versionMajor, g_versionMinor ); _invalidFileCallback(CmftStudioProject::InvalidVersion, msg); } return false; } // File is valid. if (NULL != _validFileCallback) { _validFileCallback(0, NULL); } outputWindowPrint("Loading '%s'...", bx::baseName(_path)); // Get remaining file size. const uint32_t curr = (uint32_t)fileReader.seek(0, bx::Whence::Current); const uint32_t end = (uint32_t)fileReader.seek(0, bx::Whence::End); const uint32_t compressedSize = end-curr; fileReader.seek(curr, bx::Whence::Begin); // Read and decompress project data. cs::StackAllocScope scope(_stackAlloc); DynamicMemoryBlockWriter memory(_stackAlloc, DM_MEGABYTES(512)); const bool result = cs::readInflate(&memory, &fileReader, compressedSize, _stackAlloc); CS_CHECK(result == true, "cs::readInflate() failed!"); BX_UNUSED(result); fileReader.close(); void* data = memory.getDataTrim(); uint32_t dataSize = memory.getDataSize(); outputWindowPrint("--------------------------------------------------------------------------------------------------------"); outputWindowPrint(" Resource | Name | Size "); outputWindowPrint("--------------------------------------------------------------------------------------------------------"); bx::MemoryReader reader(data, dataSize); const uint64_t totalBefore = reader.seek(0, bx::Whence::Current); // Keep track of loaded meshes. HandleArrayT<cs::MeshHandle, CS_MAX_MESHES> meshList; bool done = false; uint32_t chunk; while (!done && 4 == bx::read(&reader, chunk) ) { switch (chunk) { case CMFTSTUDIO_CHUNK_MAGIC_MSH_BEGIN: { const uint64_t before = reader.seek(0, bx::Whence::Current); const cs::MeshHandle mesh = cs::readMesh(&reader); meshList.add(mesh); const uint64_t after = reader.seek(0, bx::Whence::Current); uint32_t end; bx::read(&reader, end); BX_CHECK(CMFTSTUDIO_CHUNK_MAGIC_MSH_END == end, "Error reading file!"); const uint64_t size = after-before; outputWindowPrint("[Mesh] %79s - %4u.%03u MB", cs::getName(mesh), dm::U_UMB(size), size); } break; case CMFTSTUDIO_CHUNK_MAGIC_MIN_BEGIN: { cs::MeshInstance* obj = _meshInstList.addNew(); cs::readMeshInstance(&reader, obj); uint32_t end; bx::read(&reader, end); BX_CHECK(CMFTSTUDIO_CHUNK_MAGIC_MIN_END == end, "Error reading file!"); } break; case CMFTSTUDIO_CHUNK_MAGIC_ENV_BEGIN: { const uint64_t before = reader.seek(0, bx::Whence::Current); const cs::EnvHandle env = cs::readEnv(&reader); _envList.add(env); const uint64_t after = reader.seek(0, bx::Whence::Current); uint32_t end; bx::read(&reader, end); BX_CHECK(CMFTSTUDIO_CHUNK_MAGIC_ENV_END == end, "Error reading file!"); const uint64_t size = after-before; outputWindowPrint("[Env] %79s - %4u.%03u MB", cs::getName(env), dm::U_UMB(size), size); } break; case CMFTSTUDIO_CHUNK_MAGIC_MAT_BEGIN: { const uint64_t before = reader.seek(0, bx::Whence::Current); const cs::MaterialHandle material = cs::readMaterial(&reader); _materialList.add(material); const uint64_t after = reader.seek(0, bx::Whence::Current); uint32_t end; bx::read(&reader, end); BX_CHECK(CMFTSTUDIO_CHUNK_MAGIC_MAT_END == end, "Error reading file!"); const uint64_t size = after-before; outputWindowPrint("[Material] %79s - %4u.%03u MB", cs::getName(material), dm::U_UMB(size), size); } break; case CMFTSTUDIO_CHUNK_MAGIC_TEX_BEGIN: { const uint64_t before = reader.seek(0, bx::Whence::Current); const cs::TextureHandle texture = cs::readTexture(&reader); _textureList.add(texture); const uint64_t after = reader.seek(0, bx::Whence::Current); uint32_t end; bx::read(&reader, end); BX_CHECK(CMFTSTUDIO_CHUNK_MAGIC_TEX_END == end, "Error reading file!"); const uint64_t size = after-before; outputWindowPrint("[Texture] %79s - %4u.%03u MB", cs::getName(texture), dm::U_UMB(size), size); } break; case CMFTSTUDIO_CHUNK_MAGIC_SET_BEGIN: { ::read(&reader, _settings); uint32_t end; bx::read(&reader, end); BX_CHECK(CMFTSTUDIO_CHUNK_MAGIC_SET_END == end, "Error reading file!"); } break; case CMFTSTUDIO_CHUNK_MAGIC_PROJECT_END: { done = true; } break; default: { CS_CHECK(0, "Error reading project file! %08x at %ld", chunk, reader.seek(0, bx::Whence::Current)); done = true; } break; } } const uint64_t totalAfter = reader.seek(0, bx::Whence::Current); const uint64_t totalSize = totalAfter-totalBefore; outputWindowPrint("--------------------------------------------------------------------------------------------------------"); outputWindowPrint("<File size> %76u.%03u MB", dm::U_UMB(compressedSize)); outputWindowPrint("<Decompressed> %76u.%03u MB", dm::U_UMB(totalSize)); outputWindowPrint("--------------------------------------------------------------------------------------------------------"); // Resolve loaded resources. cs::resourceResolveAll(); cs::resourceClearMappings(); // Cleanup. for (uint32_t ii = meshList.count(); ii--; ) { cs::release(meshList[ii]); } BX_FREE(_stackAlloc, data); return true; } /* vim: set sw=4 ts=4 expandtab: */
37.951389
130
0.565111
[ "mesh" ]
d1532557c489d2a3bcf2ff55d062e181cf225399
2,114
h
C
lib/c_glib/src/protocol/thrift_protocol_factory.h
dreiss/old-thrift
b9621e9b63f6a40124e48c8a905e4b50a4c1c999
[ "Apache-2.0" ]
3
2015-11-05T08:18:15.000Z
2019-06-03T17:05:16.000Z
lib/c_glib/src/protocol/thrift_protocol_factory.h
dreiss/old-thrift
b9621e9b63f6a40124e48c8a905e4b50a4c1c999
[ "Apache-2.0" ]
null
null
null
lib/c_glib/src/protocol/thrift_protocol_factory.h
dreiss/old-thrift
b9621e9b63f6a40124e48c8a905e4b50a4c1c999
[ "Apache-2.0" ]
4
2021-02-10T06:08:22.000Z
2022-02-17T11:55:35.000Z
#ifndef _THRIFT_PROTOCOL_FACTORY_H #define _THRIFT_PROTOCOL_FACTORY_H #include <glib-object.h> #include "transport/thrift_transport.h" #include "protocol/thrift_protocol.h" /*! \file thrift_protocol_factory.h * \brief Abstract class for Thrift protocol factory implementations. */ /* type macros */ #define THRIFT_TYPE_PROTOCOL_FACTORY (thrift_protocol_factory_get_type ()) #define THRIFT_PROTOCOL_FACTORY(obj) (G_TYPE_CHECK_INSTANCE_CAST ((obj), \ THRIFT_TYPE_PROTOCOL_FACTORY, \ ThriftProtocolFactory)) #define THRIFT_IS_PROTOCOL_FACTORY(obj) (G_TYPE_CHECK_INSTANCE_TYPE ((obj), \ THRIFT_TYPE_PROTOCOL_FACTORY)) #define THRIFT_PROTOCOL_FACTORY_CLASS(c) (G_TYPE_CHECK_CLASS_CAST ((c), \ THRIFT_TYPE_PROTOCOL_FACTORY, \ ThriftProtocolFactoryClass)) #define THRIFT_IS_PROTOCOL_FACTORY_CLASS(c) (G_TYPE_CHECK_CLASS_TYPE ((c), \ THRIFT_TYPE_PROTOCOL_FACTORY)) #define THRIFT_PROTOCOL_FACTORY_GET_CLASS(obj) \ (G_TYPE_INSTANCE_GET_CLASS ((obj), \ THRIFT_TYPE_PROTOCOL_FACTORY, \ ThriftProtocolFactoryClass)) /*! * Thrift Protocol Factory object */ struct _ThriftProtocolFactory { GObject parent; }; typedef struct _ThriftProtocolFactory ThriftProtocolFactory; /*! * Thrift Protocol Factory class */ struct _ThriftProtocolFactoryClass { GObjectClass parent; ThriftProtocol *(*get_protocol) (ThriftProtocolFactory *factory, ThriftTransport *transport); }; typedef struct _ThriftProtocolFactoryClass ThriftProtocolFactoryClass; /* used by THRIFT_TYPE_PROTOCOL_FACTORY */ GType thrift_protocol_factory_get_type (void); /* virtual public methods */ ThriftProtocol *thrift_protocol_factory_get_protocol(ThriftProtocolFactory *factory, ThriftTransport *transport); #endif /* _THRIFT_PROTOCOL_FACTORY_H */
36.448276
113
0.667455
[ "object" ]
d15e86f8601a344a7ee0b3c60f2f87ad718e2d26
2,162
h
C
qbLSQ.h
QuantitativeBytes/qbLinAlg
019007071dcbb12af157dab8452409c02f0628ba
[ "MIT" ]
13
2021-02-16T11:59:12.000Z
2022-03-19T07:25:59.000Z
qbLSQ.h
QuantitativeBytes/qbLinAlg
019007071dcbb12af157dab8452409c02f0628ba
[ "MIT" ]
null
null
null
qbLSQ.h
QuantitativeBytes/qbLinAlg
019007071dcbb12af157dab8452409c02f0628ba
[ "MIT" ]
4
2021-02-16T11:59:14.000Z
2021-12-20T15:52:28.000Z
// This file is part of the qbLinAlg linear algebra library. // Copyright (c) 2021 Michael Bennett // MIT license #ifndef QBLSQ_H #define QBLSQ_H /* ************************************************************************************************* qbLSQ Function to solve a system of linear equations using a least squares approach to handle systems where there are more equations (observations) than unknowns. Assumes that the system is in the form of y = X*beta. *** INPUTS *** Xin qbMatrix2<T> The matrix of independent variables (X in the above equation). yin qbVector<T> The vector of dependent variables (y in the above equation). result qbVector<T> The vector of unknown parameters (beta in the above equation). The final solution is returned in this vector. *** OUTPUTS *** INT Flag indicating success or failure of the process. 1 Indicates success. -1 indicates failure due to there being no computable inverse. Created as part of the qbLinAlg linear algebra library, which is intended to be primarily for educational purposes. For more details, see the corresponding videos on the QuantitativeBytes YouTube channel at: www.youtube.com/c/QuantitativeBytes ************************************************************************************************* */ #include <stdexcept> #include <iostream> #include <iomanip> #include <math.h> #include <vector> #include "qbVector.h" #include "qbMatrix.h" // Define error codes. constexpr int QBLSQ_NOINVERSE = -1; // The qbLSQ function. template <typename T> int qbLSQ(const qbMatrix2<T> &Xin, const qbVector<T> &yin, qbVector<T> &result) { // Firstly, make a copy of X and y. qbMatrix2<T> X = Xin; qbVector<T> y = yin; // Compute the tranpose of X. qbMatrix2<T> XT = X.Transpose(); // Compute XTX. qbMatrix2<T> XTX = XT * X; // Compute the inverse of this. if (!XTX.Inverse()) { // We were unable to compute the inverse. return QBLSQ_NOINVERSE; } // Multiply the inverse by XT. qbMatrix2<T> XTXXT = XTX * XT; // And multiply by y to get the final result. result = XTXXT * y; return 1; } #endif
27.367089
101
0.639685
[ "vector" ]
d16e8c6b616e4f0787e7800ecbf296a46179701b
2,672
h
C
thirdparty/physx/PhysXSDK/Source/GeomUtils/src/convex/GuConvexHelper.h
johndpope/echo
e9ce2f4037e8a5d49b74cc7a9d9ee09f296e7fa7
[ "MIT" ]
null
null
null
thirdparty/physx/PhysXSDK/Source/GeomUtils/src/convex/GuConvexHelper.h
johndpope/echo
e9ce2f4037e8a5d49b74cc7a9d9ee09f296e7fa7
[ "MIT" ]
2
2015-06-21T17:38:11.000Z
2015-06-22T20:54:42.000Z
thirdparty/physx/PhysXSDK/Source/GeomUtils/src/convex/GuConvexHelper.h
johndpope/echo
e9ce2f4037e8a5d49b74cc7a9d9ee09f296e7fa7
[ "MIT" ]
null
null
null
/* * Copyright (c) 2008-2015, NVIDIA CORPORATION. All rights reserved. * * NVIDIA CORPORATION and its licensors retain all intellectual property * and proprietary rights in and to this software, related documentation * and any modifications thereto. Any use, reproduction, disclosure or * distribution of this software and related documentation without an express * license agreement from NVIDIA CORPORATION is strictly prohibited. */ // Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved. // Copyright (c) 2001-2004 NovodeX AG. All rights reserved. #ifndef GU_CONVEXHELPER_H #define GU_CONVEXHELPER_H #include "PsFPU.h" #include "PxVec3.h" #include "GuShapeConvex.h" namespace physx { namespace Gu { class GeometryUnion; PX_FORCE_INLINE void copyPlane(PxPlane* PX_RESTRICT dst, const Gu::HullPolygonData* PX_RESTRICT src) { // PT: "as usual" now, the direct copy creates LHS that are avoided by the IR macro... #ifdef PX_PS3 // AP: IR macro causes compiler warnings (dereferencing type-punned pointer will break strict-aliasing rules) dst->n = src->mPlane.n; dst->d = src->mPlane.d; #else PX_IR(dst->n.x) = PX_IR(src->mPlane.n.x); PX_IR(dst->n.y) = PX_IR(src->mPlane.n.y); PX_IR(dst->n.z) = PX_IR(src->mPlane.n.z); PX_IR(dst->d) = PX_IR(src->mPlane.d); #endif } /////////////////////////////////////////////////////////////////////////// PX_PHYSX_COMMON_API void getScaledConvex( PxVec3*& scaledVertices, PxU8*& scaledIndices, PxVec3* dstVertices, PxU8* dstIndices, bool idtConvexScale, const PxVec3* srcVerts, const PxU8* srcIndices, PxU32 nbVerts, const Cm::FastVertex2ShapeScaling& convexScaling); // PT: calling this correctly isn't trivial so let's macroize it. At least we limit the damage since it immediately calls a real function. #define GET_SCALEX_CONVEX(scaledVertices, stackIndices, idtScaling, nbVerts, scaling, srcVerts, srcIndices) \ getScaledConvex(scaledVertices, stackIndices, \ idtScaling ? NULL : (PxVec3*)PxAlloca(nbVerts * sizeof(PxVec3)), \ idtScaling ? NULL : (PxU8*)PxAlloca(nbVerts * sizeof(PxU8)), \ idtScaling, srcVerts, srcIndices, nbVerts, scaling); PX_PHYSX_COMMON_API bool getConvexData(const Gu::GeometryUnion& shape, Cm::FastVertex2ShapeScaling& scaling, PxBounds3& bounds, PolygonalData& polyData); struct ConvexEdge { PxU8 vref0; PxU8 vref1; PxVec3 normal; // warning: non-unit vector! }; PX_PHYSX_COMMON_API PxU32 findUniqueConvexEdges(PxU32 maxNbEdges, ConvexEdge* PX_RESTRICT edges, PxU32 numPolygons, const Gu::HullPolygonData* PX_RESTRICT polygons, const PxU8* PX_RESTRICT vertexData); } } #endif
39.880597
202
0.723428
[ "shape", "vector" ]
2f6357aec061022a3b5328a11168b4bac79ee93b
2,223
h
C
core/src/main/cpp/webrtc/modules/rtp_rtcp/source/ssrc_database.h
sclwork/core
65904846fcaa86dd67937a263dc6ae5882dd1f30
[ "Apache-2.0" ]
78
2016-06-23T03:01:49.000Z
2022-03-03T03:15:49.000Z
core/src/main/cpp/webrtc/modules/rtp_rtcp/source/ssrc_database.h
sclwork/core
65904846fcaa86dd67937a263dc6ae5882dd1f30
[ "Apache-2.0" ]
8
2016-12-17T03:16:01.000Z
2020-05-21T09:55:58.000Z
core/src/main/cpp/webrtc/modules/rtp_rtcp/source/ssrc_database.h
sclwork/core
65904846fcaa86dd67937a263dc6ae5882dd1f30
[ "Apache-2.0" ]
53
2016-06-05T13:34:42.000Z
2021-12-22T10:44:03.000Z
/* * Copyright (c) 2011 The WebRTC project authors. All Rights Reserved. * * Use of this source code is governed by a BSD-style license * that can be found in the LICENSE file in the root of the source * tree. An additional intellectual property rights grant can be found * in the file PATENTS. All contributing project authors may * be found in the AUTHORS file in the root of the source tree. */ #ifndef WEBRTC_MODULES_RTP_RTCP_SOURCE_SSRC_DATABASE_H_ #define WEBRTC_MODULES_RTP_RTCP_SOURCE_SSRC_DATABASE_H_ #include <set> #include "webrtc/base/criticalsection.h" #include "webrtc/base/random.h" #include "webrtc/base/thread_annotations.h" #include "webrtc/system_wrappers/include/static_instance.h" #include "webrtc/typedefs.h" namespace webrtc { // TODO(tommi, holmer): Look into whether we can eliminate locking in this // class or the class itself completely once voice engine doesn't rely on it. // At the moment voe_auto_test requires locking, but it's not clear if that's // an issue with the test code or if it reflects real world usage or if that's // the best design performance wise. // If we do decide to keep the class, we should at least get rid of using // StaticInstance. class SSRCDatabase { public: static SSRCDatabase* GetSSRCDatabase(); static void ReturnSSRCDatabase(); uint32_t CreateSSRC(); void RegisterSSRC(uint32_t ssrc); void ReturnSSRC(uint32_t ssrc); protected: SSRCDatabase(); ~SSRCDatabase(); static SSRCDatabase* CreateInstance() { return new SSRCDatabase(); } // Friend function to allow the SSRC destructor to be accessed from the // template class. friend SSRCDatabase* GetStaticInstance<SSRCDatabase>( CountOperation count_operation); private: rtc::CriticalSection crit_; Random random_ GUARDED_BY(crit_); std::set<uint32_t> ssrcs_ GUARDED_BY(crit_); // TODO(tommi): Use a thread checker to ensure the object is created and // deleted on the same thread. At the moment this isn't possible due to // voe::ChannelOwner in voice engine. To reproduce, run: // voe_auto_test --automated --gtest_filter=*MixManyChannelsForStressOpus }; } // namespace webrtc #endif // WEBRTC_MODULES_RTP_RTCP_SOURCE_SSRC_DATABASE_H_
35.285714
78
0.761583
[ "object" ]
2f7174eabafbcc01af126104337602580309b96a
232
h
C
Ray_Tracing/Mesh.h
jaxfrank/Ray-Tracer
d700352197ca19039b45c7b4b9eeef0ec158ba25
[ "MIT" ]
null
null
null
Ray_Tracing/Mesh.h
jaxfrank/Ray-Tracer
d700352197ca19039b45c7b4b9eeef0ec158ba25
[ "MIT" ]
null
null
null
Ray_Tracing/Mesh.h
jaxfrank/Ray-Tracer
d700352197ca19039b45c7b4b9eeef0ec158ba25
[ "MIT" ]
null
null
null
#pragma once #include <Vector> #include "Vertex.h" class Mesh { public: Mesh(std::vector<Vertex> vertices, std::vector<int> indices); ~Mesh(); private: std::vector<Vertex> vertices; std::vector<int> indices; };
13.647059
65
0.650862
[ "mesh", "vector" ]
2f729b6dc318d49b837cc59e13631487a1539fd1
791
h
C
common/control.h
carloshd86/PracticaArquitecturaVideojuego
c6bb0816cb6ad0e75233ab5753d3fcf4e11c53d9
[ "BSD-2-Clause" ]
null
null
null
common/control.h
carloshd86/PracticaArquitecturaVideojuego
c6bb0816cb6ad0e75233ab5753d3fcf4e11c53d9
[ "BSD-2-Clause" ]
null
null
null
common/control.h
carloshd86/PracticaArquitecturaVideojuego
c6bb0816cb6ad0e75233ab5753d3fcf4e11c53d9
[ "BSD-2-Clause" ]
null
null
null
#ifndef __CONTROL_H__ #define __CONTROL_H__ #include "eventmanager.h" #include "container.h" class Control : public IEventManager::IListener { public: Control(float x, float y, float width, float height, Container * parent); virtual ~Control(); virtual bool ProcessEvent (IEventManager::EM_Event event) = 0; virtual void Update (float deltaTime) = 0; virtual void Render () = 0; virtual const Container * GetParent () const; virtual void SetFocused (bool focused); virtual bool GetVisible () const; virtual void SetVisible (bool visible); protected: float mX; float mY; float mWidth; float mHeight; bool mFocused; bool mVisible; Container *mParent; }; #endif
19.775
74
0.639697
[ "render" ]
2f78b0c5dbcd752b8cf769fcf48d4905ceac113f
543
h
C
src/essence.game/qpang/room/session/skill/RoomSessionSkillManager.h
hinnie123/qpang-essence-emulator-1
2b99f21bcbcbdcd5ff8104d4845ebc10ec0e6e1b
[ "MIT" ]
1
2021-11-23T00:31:46.000Z
2021-11-23T00:31:46.000Z
src/essence.game/qpang/room/session/skill/RoomSessionSkillManager.h
hinnie123/qpang-essence-emulator-1
2b99f21bcbcbdcd5ff8104d4845ebc10ec0e6e1b
[ "MIT" ]
null
null
null
src/essence.game/qpang/room/session/skill/RoomSessionSkillManager.h
hinnie123/qpang-essence-emulator-1
2b99f21bcbcbdcd5ff8104d4845ebc10ec0e6e1b
[ "MIT" ]
1
2021-12-18T12:50:46.000Z
2021-12-18T12:50:46.000Z
#pragma once #include <functional> #include <memory> #include <unordered_map> #include "Skill.h" class RoomSession; class RoomSessionPlayer; class RoomSessionSkillManager { public: void initialize(const std::shared_ptr<RoomSession>& roomSession); std::shared_ptr<Skill> getSkillByItemId(const uint32_t itemId); std::shared_ptr<Skill> generateRandomSkill(); bool isValidSkillForGameMode(uint32_t itemId); private: std::weak_ptr<RoomSession> m_roomSession; std::vector<std::function<std::unique_ptr<Skill>()>> m_skillsForGameMode; };
22.625
74
0.790055
[ "vector" ]
2f80932ce7e8b40819f5ccb090d33302223446b5
2,172
h
C
EVE/EveDet/AliEveTOFSectorEditor.h
AllaMaevskaya/AliRoot
c53712645bf1c7d5f565b0d3228e3a6b9b09011a
[ "BSD-3-Clause" ]
52
2016-12-11T13:04:01.000Z
2022-03-11T11:49:35.000Z
EVE/EveDet/AliEveTOFSectorEditor.h
AllaMaevskaya/AliRoot
c53712645bf1c7d5f565b0d3228e3a6b9b09011a
[ "BSD-3-Clause" ]
1,388
2016-11-01T10:27:36.000Z
2022-03-30T15:26:09.000Z
EVE/EveDet/AliEveTOFSectorEditor.h
AllaMaevskaya/AliRoot
c53712645bf1c7d5f565b0d3228e3a6b9b09011a
[ "BSD-3-Clause" ]
275
2016-06-21T20:24:05.000Z
2022-03-31T13:06:19.000Z
#ifndef ALIEVETOFSECTOREDITOR_H #define ALIEVETOFSECTOREDITOR_H /************************************************************************** * Copyright(c) 1998-2008, ALICE Experiment at CERN, all rights reserved. * * See http://aliceinfo.cern.ch/Offline/AliRoot/License.html for * * full copyright notice. * **************************************************************************/ // $Id$ // Main authors: Matevz Tadel & Alja Mrak-Tadel: 2006, 2007 // // // #include <TGedFrame.h> class TGCheckButton; class TGNumberEntry; class TGColorSelect; class TGDoubleHSlider; class TGHSlider; class TEveGValuator; class TEveGDoubleValuator; class AliEveTOFSector; class AliEveTOFSectorEditor : public TGedFrame { public: AliEveTOFSectorEditor(const TGWindow* p=0, Int_t width=170, Int_t height=30, UInt_t options=kChildFrame, Pixel_t back=GetDefaultFrameBackground()); virtual ~AliEveTOFSectorEditor(); virtual void SetModel(TObject* obj); void DoSectorID(); void DoAutoTrans(); void DoPlate0(); void DoPlate1(); void DoPlate2(); void DoPlate3(); void DoPlate4(); void DoPlate(Int_t nPlate); void DoThreshold(); void DoMaxVal(); protected: AliEveTOFSector* fM; // Model object. TEveGValuator* fSectorID; // Valuator for sector id. TGCheckButton* fAutoTrans; // Check-button for automatic translation. TGCheckButton** fPlate; // Check-buttons for plates. TGCheckButton* fPlate0; // Check-button for plate 0. TGCheckButton* fPlate1; // Check-button for plate 1. TGCheckButton* fPlate2; // Check-button for plate 2. TGCheckButton* fPlate3; // Check-button for plate 3. TGCheckButton* fPlate4; // Check-button for plate 4. TEveGValuator* fThreshold; // Valuator for threshold. TEveGValuator* fMaxVal; // Valuator for maximum value. private: AliEveTOFSectorEditor(const AliEveTOFSectorEditor&); // Not implemented AliEveTOFSectorEditor& operator=(const AliEveTOFSectorEditor&); // Not implemented ClassDef(AliEveTOFSectorEditor, 0); // Editor for AliEveTOFSector }; #endif
28.207792
84
0.651934
[ "object", "model" ]
2f8c763391fa6c36ba64f7d1e6e78dc8b7ab78ab
970
h
C
include/Player.h
vikrambombhi/Checkers
99c2464a37057f72a40d4ff962d52b82686d461b
[ "MIT" ]
6
2020-02-07T22:58:14.000Z
2022-03-14T06:26:10.000Z
include/Player.h
VikramBombhi/Checkers
99c2464a37057f72a40d4ff962d52b82686d461b
[ "MIT" ]
1
2016-11-23T02:59:38.000Z
2016-11-23T04:35:28.000Z
include/Player.h
vikrambombhi/Checkers
99c2464a37057f72a40d4ff962d52b82686d461b
[ "MIT" ]
3
2019-06-12T18:30:28.000Z
2021-06-06T10:34:23.000Z
// // Player.h // CheckersProject // // Created by Benjamin Emdon on 2016-02-13. // Copyright © 2016 Ben Emdon. // #ifndef Player_h #define Player_h #include "CheckersBoard.h" #include "Piece.h" using namespace std; class Button; class Player{ public: Player(bool,CheckersBoard*, Button*); ~Player(); virtual bool makeMove(SDL_Event *); vector<Piece> team; bool turn; void updateTeam(); void updateKings(); // for multi turn loop bool killWasMade = false; protected: void movePiece(vector<vector<int>> &, vector<Piece> & ,int, int, int); void killPiece(vector<vector<int>> &, int, int); void initTeam(); bool sameTeam(int,int); int pieceTeamIndexByXY(int,int); int currentIndex; bool topSide; int ONE; int TEAM_NUMBER; int ENEMY_TEAM_NUMBER; CheckersBoard *Board; Button *boardButtons; // for multi turn loop int killerPeiceIndex; }; #endif /* Player_h */
19.019608
74
0.650515
[ "vector" ]
2fa0bc10c579b9ec055d42cf1474adb79cbecd27
1,452
h
C
src/SubInspector.h
TypesettingCartel/SubInspector
872fec2caa26b416eae1c118cb778d714348299a
[ "MIT" ]
5
2016-03-27T09:16:01.000Z
2020-12-20T19:43:54.000Z
src/SubInspector.h
TypesettingCartel/SubInspector
872fec2caa26b416eae1c118cb778d714348299a
[ "MIT" ]
2
2019-02-09T17:23:34.000Z
2019-02-12T19:55:51.000Z
src/SubInspector.h
TypesettingCartel/SubInspector
872fec2caa26b416eae1c118cb778d714348299a
[ "MIT" ]
3
2015-12-09T18:24:59.000Z
2016-03-27T15:47:19.000Z
/* SubInspector is free software. You can redistribute it and/or modify * it under the terms of the MIT License. See COPYING or do a google * search for details. */ #pragma once #include <stdint.h> #include <string.h> // size_t #ifdef _WIN32 #ifdef SUB_INSPECTOR_STATIC #define SI_EXPORT #else #ifdef BUILD_DLL #define SI_EXPORT __declspec(dllexport) #else #define SI_EXPORT __declspec(dllimport) #endif // BUILD_DLL #endif // SUB_INSPECTOR_STATIC #else // Non-windows #define SI_EXPORT #endif // _WIN32 #define SI_VERSION 0x000502 typedef struct SI_State_priv SI_State; typedef struct { int x, y; unsigned int w, h; uint32_t hash; uint8_t solid; } SI_Rect; SI_EXPORT uint32_t si_getVersion( void ); SI_EXPORT const char* si_getErrorString( SI_State *state ); SI_EXPORT SI_State* si_init( int width, int height, const char* fontConfigConfig, const char *fontDir ); SI_EXPORT void si_changeResolution( SI_State *state, int width, int height ); SI_EXPORT void si_reloadFonts( SI_State *state, const char *fontConfigConfig, const char *fontDir ); SI_EXPORT int si_setHeader( SI_State *state, const char *header, size_t length ); SI_EXPORT int si_setScript( SI_State *state, const char *body, size_t length ); SI_EXPORT int si_calculateBounds( SI_State *state, SI_Rect *rects, const int32_t *times, const uint32_t renderCount ); SI_EXPORT void si_cleanup( SI_State *state );
33
126
0.738981
[ "solid" ]
2faa3cac690b5af699eb4d26932ce8593f73b2aa
787
h
C
simple-paint-sdl2/simple-paint-sdl2/simple-paint-sdl2/modules/layers_viewer/layers_viewer.h
i582/simple-paint-sdl2
3fc4eac68b6cfac949d42d6ea25a38e8fd206b7c
[ "MIT" ]
null
null
null
simple-paint-sdl2/simple-paint-sdl2/simple-paint-sdl2/modules/layers_viewer/layers_viewer.h
i582/simple-paint-sdl2
3fc4eac68b6cfac949d42d6ea25a38e8fd206b7c
[ "MIT" ]
null
null
null
simple-paint-sdl2/simple-paint-sdl2/simple-paint-sdl2/modules/layers_viewer/layers_viewer.h
i582/simple-paint-sdl2
3fc4eac68b6cfac949d42d6ea25a38e8fd206b7c
[ "MIT" ]
null
null
null
#pragma once #include "../viewport/canvas/layers/layers.h" #include "layer_view/layer_view.h" #include "../colors/color.h" class Viewport; class LayersViewer { private: SDL_Renderer* renderer; SDL_Texture* texture; SDL_Rect size; Layers* layers; vector <LayerView*> layer_views; SDL_Point pos_mouse; TTF_Font* font; Viewport* parent; public: LayersViewer(SDL_Renderer* renderer, Viewport* parent, SDL_Rect size, Layers* layers); public: friend LayerView; private: void setup(); void render_one_layer(int num); public: void update(); void update_layer(); bool on_hover(int x, int y); void mouseButtonDown(SDL_Event* e); void mouseButtonUp(SDL_Event* e); void mouseMotion(SDL_Event* e); void mouseWheel(SDL_Event* e); void update_coord(int* x, int* y); };
16.744681
87
0.736976
[ "vector" ]
2fbc1be121b11550655f8293a9c4d5215bf8fb75
8,769
h
C
RuleFunctions.h
flocklang/flock-compiler-cpp
b43fc774587668abe4885d67aa481408adb45704
[ "Apache-2.0" ]
1
2020-09-06T23:08:30.000Z
2020-09-06T23:08:30.000Z
RuleFunctions.h
flocklang/flock-compiler-cpp
b43fc774587668abe4885d67aa481408adb45704
[ "Apache-2.0" ]
null
null
null
RuleFunctions.h
flocklang/flock-compiler-cpp
b43fc774587668abe4885d67aa481408adb45704
[ "Apache-2.0" ]
null
null
null
///* // * Copyright 2020 John Orlando Keleshian Moxley, 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. // */ //#ifndef FLOCK_EBNF_RULE_FUNCTIONS_H //#define FLOCK_EBNF_RULE_FUNCTIONS_H // //#include "RuleTypes.h" //#include "LocationSupplier.h" //#include "ConsoleFormat.h" //#include <vector> //#include <map> //#include <string> //#include <numeric> //#include <cstdarg> // /// // /// Basic Grammar, that allows to employ basic BNF style grammars in language detection. // /// //namespace flock { // namespace ebnf { // namespace rule { // using namespace flock::ebnf::types; // // static _sp<SequentialRule> SEQ(initializer_list<_sp<Rule>> rules); // static _sp<AnyRule> ANY(); // static _sp<AnyButRule> ANYBUT(_sp<Rule> rule); // static _sp<AnyButRule> ANYBUT(initializer_list<_sp<Rule>> rules); // static _sp<SymbolRule> SYM(string type, _sp<Rule> rule, bool highlightCollect = true); // static _sp<EqualStringRule> EQ(initializer_list<string > values); // static _sp<EqualStringRule> EQ(string value); // static _sp<EqualCharRule> EQ(initializer_list<int> values); // static _sp<EqualCharRule> EQ(vector<int> values); // static _sp<EqualCharRule> EQ(int value); // static _sp<EqualCharRule> equalRange(int start, int end); // static _sp<EOFRule> eof(); // static _sp<RepeatRule> REP(_sp<Rule> rule, const int min = 0, const int max = 0); // static _sp<NotRule> NOT(_sp<Rule> rule); // static _sp<NotRule> NOT(initializer_list<_sp<Rule>> rules); // static _sp<OrRule> OR(initializer_list<_sp<Rule>> rules); // static _sp<OrRule> OR(_sp<Rule> left, _sp<Rule> right); // static _sp<OrRule> OR(_sp<Rule> left, _sp<Rule> middle, _sp<Rule> right); // static _sp<AndRule> AND(initializer_list<_sp<Rule>> rules); // static _sp<AndRule> AND(_sp<Rule> left, _sp<Rule> right); // static _sp<AndRule> AND(_sp<Rule> left, _sp<Rule> middle, _sp<Rule> right); // static _sp<XorRule> XOR(initializer_list<_sp<Rule>> rules); // static _sp<XorRule> XOR(_sp<Rule> left, _sp<Rule> right); // static _sp<SequentialRule> SEQ(_sp<Rule> left, _sp<Rule> right); // static _sp<SequentialRule> SEQ(_sp<Rule> left, _sp<Rule> middle, _sp<Rule> right); // static _sp<OptionalRule> OPT(_sp<Rule> rule); // static _sp<OptionalRule> OPT(initializer_list<_sp<Rule>> rules); // static _sp<RepeatRule> UNTIL(_sp<Rule> rule); // static _sp<SequentialRule> UNTIL_INC(_sp<Rule> rule); // static _sp<SymbolRule> keyword(string keyword); // static _sp<SymbolRule> keyword(initializer_list<string> keywords); // static _sp<Rule> RULE(string grammerName); // static _sp<EqualCharRule> new_line(); // static _sp<EqualCharRule> blank(); // static _sp<OrRule> whitespace(); // static _sp<EqualCharRule> uppercase_alpha(); // static _sp<EqualCharRule> lowercase_alpha(); // static _sp<OrRule> alpha(); // static _sp<EqualCharRule> digit(); // // // static _sp<SequentialRule> SEQ(initializer_list<_sp<Rule>> rules) { // return make_shared<SequentialRule>(rules); // } // static _sp<AnyRule> ANY() { // return make_shared<AnyRule>(); // } // static _sp<AnyButRule> ANYBUT(_sp<Rule> rule) { // return make_shared<AnyButRule>(rule); // } // static _sp<AnyButRule> ANYBUT(initializer_list<_sp<Rule>> rules) { // return ANYBUT(SEQ(rules)); // } // static _sp<SymbolRule> SYM(string type, _sp<Rule> rule, bool highlightCollect) { // return make_shared<SymbolRule>(rule, type, highlightCollect); // } // // static _sp<EqualStringRule> EQ(initializer_list<string > values) { // return make_shared<EqualStringRule>(values); // } // static _sp<EqualStringRule> EQ(string value) { // return EQ({ value }); // } // static _sp<EqualCharRule> EQ(vector<int> values) { // return make_shared<EqualCharRule>(values); // } // static _sp<EqualCharRule> EQ(initializer_list<int> values) { // return make_shared<EqualCharRule>(values); // } // static _sp<EqualCharRule> EQ(int value) { // return EQ({ value }); // } // static _sp<EqualCharRule> equalRange(int start, int end) { // vector<int> list((end - start) + 1); // iota(std::begin(list), std::end(list), start); // return EQ(list); // } // static _sp<EOFRule> eof() { // return make_shared<EOFRule>(); // } // // // static _sp<NotRule> NOT(_sp<Rule> rule) { // return make_shared<NotRule>(rule); // } // static _sp<NotRule> NOT(initializer_list<_sp<Rule>> rules) { // return make_shared<NotRule>(SEQ(rules)); // } // static _sp<RepeatRule> REP(_sp<Rule> rule, int min, int max) { // return make_shared<RepeatRule>(rule, min, max); // } // static _sp<OrRule> OR(initializer_list<_sp<Rule>> rules) { // return make_shared<OrRule>(rules); // } // static _sp<OrRule> OR(_sp<Rule> left, _sp<Rule> right) { // return OR({ left, right }); // } // static _sp<OrRule> OR(_sp<Rule> left, _sp<Rule> middle, _sp<Rule> right) { // return OR({ left, middle, right }); // } // static _sp<AndRule> AND(initializer_list<_sp<Rule>> rules) { // return make_shared<AndRule>(rules); // } // static _sp<AndRule> AND(_sp<Rule> left, _sp<Rule> right) { // return AND({ left, right }); // } // static _sp<AndRule> AND(_sp<Rule> left, _sp<Rule> middle, _sp<Rule> right) { // return AND({ left, middle, right }); // } // static _sp<XorRule> XOR(initializer_list<_sp<Rule>> rules) { // return make_shared<XorRule>(rules); // } // static _sp<XorRule> XOR(_sp<Rule> left, _sp<Rule> right) { // return XOR({ left, right }); // } // static _sp<SequentialRule> SEQ(_sp<Rule> left, _sp<Rule> right) { // return SEQ({ left, right }); // } // static _sp<SequentialRule> SEQ(_sp<Rule> left, _sp<Rule> middle, _sp<Rule> right) { // return SEQ({ left, middle, right }); // } // // static _sp<OptionalRule> OPT(_sp<Rule> rule) { // return make_shared<OptionalRule>(rule); // } // static _sp<OptionalRule> OPT(initializer_list<_sp<Rule>> rules) { // return OPT(SEQ(rules)); // } // static _sp<RepeatRule> UNTIL(_sp<Rule> rule) { // return REP(ANYBUT(rule)); // } // static _sp<SequentialRule> UNTIL_INC(_sp<Rule> rule) { // return SEQ(REP(ANYBUT(rule)), rule); // } // static _sp<SymbolRule> keyword(string keyword) { // return SYM("keyword", EQ(keyword)); // } // static _sp<SymbolRule> keyword(initializer_list<string> keywords) { // return SYM("keyword", EQ(keywords)); // } // // /// <summary> // /// </summary> // /// <param name="grammer"></param> // /// <returns></returns> // static _sp<Rule> RULE(string grammerName) { // switch (grammerName.back()) { // case '*': { // string name = grammerName.substr(0, grammerName.length() - 1); // _sp<GrammarRule> grammarRule = make_shared<GrammarRule>(name); // return REP(grammarRule); // } // case '+': { // string name = grammerName.substr(0, grammerName.length() - 1); // _sp<GrammarRule> grammarRule = make_shared<GrammarRule>(name); // return SEQ(grammarRule, REP(grammarRule)); // } // case '?': { // string name = grammerName.substr(0, grammerName.length() - 1); // _sp<GrammarRule> grammarRule = make_shared<GrammarRule>(name); // return OPT(grammarRule); // // } // case '-': { // string name = grammerName.substr(0, grammerName.length() - 1); // _sp<GrammarRule> grammarRule = make_shared<GrammarRule>(name); // return ANYBUT(grammarRule); // } // // default: { // return make_shared<GrammarRule>(grammerName); // } // // } // } // static _sp<EqualCharRule> new_line() { // return EQ({ '\n', '\r' }); // } // static _sp<EqualCharRule> blank() { // return EQ({ ' ', '\t', '\v', '\f' }); // } // static _sp<OrRule> whitespace() { // return OR(blank(), new_line()); // } // static _sp<EqualCharRule> uppercase_alpha() { // return equalRange('A', 'Z'); // } // static _sp<EqualCharRule> lowercase_alpha() { // return equalRange('a', 'z'); // } // static _sp<OrRule> alpha() { // return OR(uppercase_alpha(), lowercase_alpha()); // } // static _sp<EqualCharRule> digit() { // return equalRange('0', '9'); // } // // // // } // } //} //#endif
37
91
0.642719
[ "vector" ]
2fbe1fcc3866f8aef09334947be3cf413d0caa15
17,918
h
C
src/join/tang/tang_join_ti_impl.h
nkkarpov/syncsignature
1379ffcc0911f5a54ade93d2ab936c1fb37b8a00
[ "MIT" ]
null
null
null
src/join/tang/tang_join_ti_impl.h
nkkarpov/syncsignature
1379ffcc0911f5a54ade93d2ab936c1fb37b8a00
[ "MIT" ]
null
null
null
src/join/tang/tang_join_ti_impl.h
nkkarpov/syncsignature
1379ffcc0911f5a54ade93d2ab936c1fb37b8a00
[ "MIT" ]
null
null
null
// The MIT License (MIT) // Copyright (c) 2017 Thomas Huetter // // 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. /// \file join/tang/tang_join_impl.h /// /// \details /// Implements the tree similarity join algorithm proposed by Tang et. al in /// "Scaling Similarity Joins over Tree-Structured Data". #pragma once template <typename Label, typename VerificationAlgorithm> TangJoinTI<Label, VerificationAlgorithm>::TangJoinTI() { pre_candidates_ = 0; sum_subproblem_counter_ = 0; il_lookups_ = 0; } template <typename Label, typename VerificationAlgorithm> void TangJoinTI<Label, VerificationAlgorithm>::execute_join( std::vector<node::Node<Label>>& trees_collection, std::vector<node::BinaryNode<Label>>& binary_trees_collection, std::unordered_set<std::pair<int, int>, hashintegerpair>& candidates, std::vector<join::JoinResultElement>& join_result, const double distance_threshold) { auto a = current_time(); // Convert trees to sets and get the result. convert_trees_to_binary_trees(trees_collection, binary_trees_collection); // Compute candidates for the join using a partition_binary_tree-based // algorithm retrieve_candidates(binary_trees_collection, candidates, distance_threshold); // Verify all computed join candidates and return the join result verify_candidates(trees_collection, candidates, join_result, distance_threshold); auto b = current_time(); printf("TANG,0,0.4,%d,0,0,%lf,%d\n", (int)distance_threshold, get_time(a, b), (int)join_result.size()); fflush(stdout); } template <typename Label, typename VerificationAlgorithm> void TangJoinTI<Label, VerificationAlgorithm>::convert_trees_to_binary_trees( std::vector<node::Node<Label>>& trees_collection, std::vector<node::BinaryNode<Label>>& binary_trees_collection) { // Convert trees to sets and get the result. binary_tree_converter::Converter<Label> btsc; btsc.convert(trees_collection, binary_trees_collection); } template <typename Label, typename VerificationAlgorithm> void TangJoinTI<Label, VerificationAlgorithm>::retrieve_candidates( std::vector<node::BinaryNode<Label>>& binary_trees_collection, std::unordered_set<std::pair<int, int>, hashintegerpair>& candidates, const double distance_threshold) { // initialize inverted list index I of subgraphs // -> pointer to root of subtree? std::unordered_map<int, std::vector<int>> small_trees; // number of subgraphs, we want to achieve int delta = 2 * distance_threshold + 1; // for all trees in binary_trees_collection for (std::size_t curr_binary_tree_id = 0; curr_binary_tree_id < binary_trees_collection.size(); ++curr_binary_tree_id) { int curr_tree_size = binary_trees_collection[curr_binary_tree_id].get_tree_size(); // get all nodes of the actual std::vector<node::BinaryNode<Label>*> nodes_in_postorder; binary_trees_collection[curr_binary_tree_id].get_node_postorder_vector( nodes_in_postorder); // only look at trees with size in the threshold range -> for n in // max(|T_i| - tau, 1), |T_i|) for (int n = std::max(1, curr_tree_size - (int)distance_threshold); n <= curr_tree_size; ++n) { // traverse actual tree in postorder for (std::size_t curr_node_postorder_id = 0; curr_node_postorder_id < nodes_in_postorder.size(); ++curr_node_postorder_id) { // S contains trees T_j that contain the relevant subgraphs s_j // -> S = getSubgraphs(T_i, N) std::vector<int> S; get_subgraphs(nodes_in_postorder[curr_node_postorder_id], n, curr_node_postorder_id, S); // for each T_j (T_j .. tree that owns s) in S for (int T_j : S) // add(T_i, T_j) to candidates, join candidates is an // unordered set, therefore, no worries about duplicates candidates.emplace(curr_binary_tree_id, T_j); } // FIX: add all pairs with small trees for (int T_j : small_trees[n]) candidates.emplace(curr_binary_tree_id, T_j); } // FIX: keep track of small trees, which cannot be partitioned with the // given threshold if (curr_tree_size < delta) small_trees[curr_tree_size].push_back(curr_binary_tree_id); else { // g = MAXMINSIZE(T_i, 2*tau + 1) // maximal number of nodes within a subgraph int gamma = max_min_size(&binary_trees_collection[curr_binary_tree_id], curr_tree_size, delta); // S' = PARTITION(T_i, 2*tau + 1, g) // for each s in S' // insert s into inverted list index I_T_i int postorder_id = 0; int subgraph_id = 0; update_inverted_list(&binary_trees_collection[curr_binary_tree_id], delta, gamma, curr_tree_size, curr_binary_tree_id, postorder_id, subgraph_id, distance_threshold); } } } template <typename Label, typename VerificationAlgorithm> void TangJoinTI<Label, VerificationAlgorithm>::get_subgraphs( node::BinaryNode<Label>* curr_node, int tree_size, int curr_node_postorder_id, std::vector<int>& S) { // get string that concatenates the labels of the current node and its // children take a look at all combinations of empty children (Paper // Section 3.4 label indexing) if (curr_node->get_left_child() != nullptr && curr_node->get_right_child() != nullptr) { std::string l_ll_lr = curr_node->get_top_twig_labels(); for (auto& set_in_il : inverted_list_[tree_size][curr_node_postorder_id][l_ll_lr]) { ++il_lookups_; if (check_subgraphs(curr_node, set_in_il.second)) // are the // subgraphs // equivalent S.push_back(set_in_il.first); } } if (curr_node->get_left_child() != nullptr) { std::string l_ll_e = curr_node->label().to_string() + curr_node->get_left_child()->label().to_string() + empty_string_; for (auto& set_in_il : inverted_list_[tree_size][curr_node_postorder_id][l_ll_e]) { ++il_lookups_; if (check_subgraphs(curr_node, set_in_il.second)) // are the // subgraphs // equivalent S.push_back(set_in_il.first); } } if (curr_node->get_right_child() != nullptr) { std::string l_e_lr = curr_node->label().to_string() + empty_string_ + curr_node->get_right_child()->label().to_string(); for (auto& set_in_il : inverted_list_[tree_size][curr_node_postorder_id][l_e_lr]) { ++il_lookups_; if (check_subgraphs(curr_node, set_in_il.second)) // are the // subgraphs // equivalent S.push_back(set_in_il.first); } } std::string l_e_e = curr_node->label().to_string() + empty_string_ + empty_string_; for (auto& set_in_il : inverted_list_[tree_size][curr_node_postorder_id][l_e_e]) { ++il_lookups_; if (check_subgraphs(curr_node, set_in_il.second)) // are the subgraphs // equivalent S.push_back(set_in_il.first); } } template <typename Label, typename VerificationAlgorithm> bool TangJoinTI<Label, VerificationAlgorithm>::check_subgraphs( node::BinaryNode<Label>* left_tree_node, node::BinaryNode<Label>* right_tree_node) { // nodes have the same label if (left_tree_node->label() == right_tree_node->label()) { bool subgraph_identical = true; // check recursively for all descendants if (right_tree_node->has_left_child() && right_tree_node->get_left_child()->get_subgraph_size() != right_tree_node->get_left_child()->get_detached()) { if (left_tree_node->has_left_child()) subgraph_identical &= check_subgraphs(left_tree_node->get_left_child(), right_tree_node->get_left_child()); else return false; } if (subgraph_identical && right_tree_node->has_right_child() && right_tree_node->get_right_child()->get_subgraph_size() != right_tree_node->get_right_child()->get_detached()) { if (left_tree_node->has_right_child()) subgraph_identical &= check_subgraphs(left_tree_node->get_right_child(), right_tree_node->get_right_child()); else return false; } return subgraph_identical; } // labels don't match -> subgraphs aren't identical return false; } template <typename Label, typename VerificationAlgorithm> int TangJoinTI<Label, VerificationAlgorithm>::max_min_size( node::BinaryNode<Label>* curr_node, int tree_size, int delta) { int gamma_max = std::floor(tree_size / delta); int gamma_min = std::floor((tree_size + delta - 1) / (2 * delta - 1)); int c = gamma_max - gamma_min + 1; while (c > 1) { int gamma_mid = gamma_min + std::floor(c / 2); if (partitionable(curr_node, delta, gamma_mid)) { gamma_min = gamma_mid; c = c - std::floor(c / 2); } else { c = std::floor(c / 2); } } return gamma_min; } template <typename Label, typename VerificationAlgorithm> bool TangJoinTI<Label, VerificationAlgorithm>::partitionable( node::BinaryNode<Label>* curr_node, int delta, int gamma) { int nr_of_subgraphs_found = 0; return recursive_partitionable(curr_node, delta, gamma, nr_of_subgraphs_found); } template <typename Label, typename VerificationAlgorithm> bool TangJoinTI<Label, VerificationAlgorithm>::recursive_partitionable( node::BinaryNode<Label>* curr_node, int delta, int gamma, int& nr_of_subgraphs_found) { curr_node->set_subgraph_size(1); curr_node->set_detached(0); node::BinaryNode<Label>* left_child = curr_node->get_left_child(); node::BinaryNode<Label>* right_child = curr_node->get_right_child(); if (left_child != nullptr) { if (recursive_partitionable(left_child, delta, gamma, nr_of_subgraphs_found)) return true; curr_node->set_subgraph_size(curr_node->get_subgraph_size() + left_child->get_subgraph_size()); curr_node->set_detached(curr_node->get_detached() + left_child->get_detached()); } if (right_child != nullptr) { if (recursive_partitionable(right_child, delta, gamma, nr_of_subgraphs_found)) return true; curr_node->set_subgraph_size(curr_node->get_subgraph_size() + right_child->get_subgraph_size()); curr_node->set_detached(curr_node->get_detached() + right_child->get_detached()); } if (curr_node->get_subgraph_size() - curr_node->get_detached() >= gamma) { ++nr_of_subgraphs_found; // identified gamma subtree curr_node->set_detached(curr_node->get_subgraph_size()); if (nr_of_subgraphs_found >= delta) return true; // found (delta, gamma)-partitioning } return false; } template <typename Label, typename VerificationAlgorithm> bool TangJoinTI<Label, VerificationAlgorithm>::update_inverted_list( node::BinaryNode<Label>* curr_node, int delta, int gamma, int tree_size, int curr_tree_id, int& postorder_id, int& subgraph_id, const double distance_threshold) { curr_node->set_subgraph_size(1); curr_node->set_detached(0); node::BinaryNode<Label>* left_child = curr_node->get_left_child(); node::BinaryNode<Label>* right_child = curr_node->get_right_child(); if (left_child != nullptr) { if (update_inverted_list(left_child, delta, gamma, tree_size, curr_tree_id, postorder_id, subgraph_id, distance_threshold)) return true; curr_node->set_subgraph_size(curr_node->get_subgraph_size() + left_child->get_subgraph_size()); curr_node->set_detached(curr_node->get_detached() + left_child->get_detached()); } if (right_child != nullptr) { if (update_inverted_list(right_child, delta, gamma, tree_size, curr_tree_id, postorder_id, subgraph_id, distance_threshold)) return true; curr_node->set_subgraph_size(curr_node->get_subgraph_size() + right_child->get_subgraph_size()); curr_node->set_detached(curr_node->get_detached() + right_child->get_detached()); } curr_node->set_postorder_id(postorder_id++); if (curr_node->get_subgraph_size() - curr_node->get_detached() >= gamma) { ++subgraph_id; curr_node->set_detached(curr_node->get_subgraph_size()); // get top twig label of the current subgraph std::string twig_labels = curr_node->label().to_string(); if (left_child != nullptr) twig_labels += left_child->label().to_string(); else twig_labels += empty_string_; if (right_child != nullptr) twig_labels += right_child->label().to_string(); else twig_labels += empty_string_; int lambda_prim = std::max( 0, (int)(distance_threshold - std::floor(subgraph_id / 2))); int min_index = std::max(0, (int)(curr_node->get_postorder_id() - lambda_prim)); int max_index = curr_node->get_postorder_id() + lambda_prim; // insert the subgraph at all relevant postorder positions with its top // twig labels for (int current_postorder_idx = min_index; current_postorder_idx <= max_index; ++current_postorder_idx) inverted_list_[tree_size][current_postorder_idx][twig_labels] .emplace_back(curr_tree_id, curr_node); if (subgraph_id >= delta) return true; // found (delta, gamma)-partitioning } return false; } template <typename Label, typename VerificationAlgorithm> void TangJoinTI<Label, VerificationAlgorithm>::verify_candidates( std::vector<node::Node<Label>>& trees_collection, std::unordered_set<std::pair<int, int>, hashintegerpair>& candidates, std::vector<join::JoinResultElement>& join_result, const double distance_threshold) { label::LabelDictionary<Label> ld; typename VerificationAlgorithm::AlgsCostModel cm(ld); VerificationAlgorithm ted_algorithm(cm); typename VerificationAlgorithm::AlgsTreeIndex ti_1; typename VerificationAlgorithm::AlgsTreeIndex ti_2; // Verify each pair in the candidate set for (const auto& pair : candidates) { node::index_tree(ti_1, trees_collection[pair.first], ld, cm); node::index_tree(ti_2, trees_collection[pair.second], ld, cm); double ted_value = ted_algorithm.ted_k(ti_1, ti_2, distance_threshold); if (ted_value <= distance_threshold) join_result.emplace_back(pair.first, pair.second, ted_value); // Sum up all number of subproblems sum_subproblem_counter_ += ted_algorithm.get_subproblem_count(); } } template <typename Label, typename VerificationAlgorithm> long long int TangJoinTI<Label, VerificationAlgorithm>::get_number_of_pre_candidates() const { return pre_candidates_; } template <typename Label, typename VerificationAlgorithm> long long int TangJoinTI<Label, VerificationAlgorithm>::get_subproblem_count() const { return sum_subproblem_counter_; } template <typename Label, typename VerificationAlgorithm> long long int TangJoinTI<Label, VerificationAlgorithm>::get_number_of_il_lookups() const { return il_lookups_; }
42.459716
80
0.630762
[ "vector" ]
4a8c2e1bd6342b151151877fd73136192bd588c5
1,640
h
C
src/Generic/events/stat/specific_pm_event_models.h
BBN-E/serif
1e2662d82fb1c377ec3c79355a5a9b0644606cb4
[ "Apache-2.0" ]
1
2022-03-24T19:57:00.000Z
2022-03-24T19:57:00.000Z
src/Generic/events/stat/specific_pm_event_models.h
BBN-E/serif
1e2662d82fb1c377ec3c79355a5a9b0644606cb4
[ "Apache-2.0" ]
null
null
null
src/Generic/events/stat/specific_pm_event_models.h
BBN-E/serif
1e2662d82fb1c377ec3c79355a5a9b0644606cb4
[ "Apache-2.0" ]
null
null
null
// Copyright 2008 by BBN Technologies Corp. // All Rights Reserved. #ifndef SPECIFIC_EVENT_MODELS_H #define SPECIFIC_EVENT_MODELS_H // unifier #include "Generic/events/stat/EventPMStats.h" #include "Generic/events/stat/ETWordVectorFilter.h" #include "Generic/events/stat/ETObjectArgVectorFilter.h" #include "Generic/events/stat/ETSubjectArgVectorFilter.h" #include "Generic/events/stat/ETWordNetVectorFilter.h" #include "Generic/events/stat/ETCluster16VectorFilter.h" #include "Generic/events/stat/ETCluster1216VectorFilter.h" #include "Generic/events/stat/ETCluster81216VectorFilter.h" // probability models #include "Generic/relations/BackoffProbModel.h" #include "Generic/relations/BackoffToPriorProbModel.h" // This file exists as a central repository for typedef'd // models created out of Stats by the combination of a Filter // and a probability model typedef EventPMStats<BackoffProbModel<2>,ETWordVectorFilter> type_et_word_model_t; typedef EventPMStats<BackoffToPriorProbModel<2>,ETWordVectorFilter> type_et_word_prior_model_t; typedef EventPMStats<BackoffProbModel<2>,ETObjectArgVectorFilter> type_et_obj_model_t; typedef EventPMStats<BackoffProbModel<2>,ETSubjectArgVectorFilter> type_et_sub_model_t; typedef EventPMStats<BackoffProbModel<3>,ETWordNetVectorFilter> type_et_wordnet_model_t; typedef EventPMStats<BackoffProbModel<4>,ETCluster81216VectorFilter> type_et_cluster81216_model_t; typedef EventPMStats<BackoffProbModel<3>,ETCluster1216VectorFilter> type_et_cluster1216_model_t; typedef EventPMStats<BackoffProbModel<2>,ETCluster16VectorFilter> type_et_cluster16_model_t; #endif
45.555556
99
0.835366
[ "model" ]
4a9d7ebba153c7f96118dfdb09bdfd88afb14eeb
7,089
c
C
dev/Gems/CryLegacy/Code/Source/CryScriptSystem/vectorlib.c
jeikabu/lumberyard
07228c605ce16cbf5aaa209a94a3cb9d6c1a4115
[ "AML" ]
1,738
2017-09-21T10:59:12.000Z
2022-03-31T21:05:46.000Z
dev/Gems/CryLegacy/Code/Source/CryScriptSystem/vectorlib.c
jeikabu/lumberyard
07228c605ce16cbf5aaa209a94a3cb9d6c1a4115
[ "AML" ]
427
2017-09-29T22:54:36.000Z
2022-02-15T19:26:50.000Z
dev/Gems/CryLegacy/Code/Source/CryScriptSystem/vectorlib.c
jeikabu/lumberyard
07228c605ce16cbf5aaa209a94a3cb9d6c1a4115
[ "AML" ]
671
2017-09-21T08:04:01.000Z
2022-03-29T14:30:07.000Z
/* * All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or * its licensors. * * For complete copyright and license terms please see the LICENSE at the root of this * distribution (the "License"). All use of this software is governed by the License, * or, if provided, by the license below or the license accompanying this file. Do not * remove or modify any license notices. This file is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * */ // Original file Copyright Crytek GMBH or its affiliates, used under license. #include <Lua/lua.h> #include <Lua/lauxlib.h> int g_vectortag = 0; int g_vectorMetatable = 0; const void* g_metatablePointer = 0; int vl_isvector(lua_State* L, int index); float* newvector(lua_State* L) { float* v = (float*)lua_newuserdata(L, sizeof(float) * 3); int nparams = lua_gettop(L); if (nparams > 0) { v[0] = (float)(lua_tonumber(L, 1)); v[1] = (float)(lua_tonumber(L, 2)); v[2] = (float)(lua_tonumber(L, 3)); } else { v[0] = v[1] = v[2] = 0.0f; } lua_getref(L, g_vectorMetatable); lua_setmetatable(L, -2); return v; } lua_Number luaL_check_number(lua_State* L, int index) { return lua_tonumber(L, index); } const char* luaL_check_string(lua_State* L, int index) { return lua_tostring(L, index); } int vector_set(lua_State* L) { float* v = (float*)lua_touserdata(L, 1); if (v) { const char* idx = luaL_check_string(L, 2); if (idx) { switch (idx[0]) { case 'x': case 'r': v[0] = (float)(luaL_check_number(L, 3)); return 0; case 'y': case 'g': v[1] = (float)(luaL_check_number(L, 3)); return 0; case 'z': case 'b': v[2] = (float)(luaL_check_number(L, 3)); return 0; default: break; } } } return 0; } int vector_get(lua_State* L) { float* v = (float*)lua_touserdata(L, 1); if (v) { const char* idx = luaL_check_string(L, 2); if (idx) { switch (idx[0]) { case 'x': case 'r': lua_pushnumber(L, v[0]); return 1; case 'y': case 'g': lua_pushnumber(L, v[1]); return 1; case 'z': case 'b': lua_pushnumber(L, v[2]); return 1; default: return 0; break; } } } return 0; } int vector_mul(lua_State* L) { float* v = (float*)lua_touserdata(L, 1); if (v) { if (vl_isvector(L, 2)) { float* v2 = (float*)lua_touserdata(L, 2); float res = v[0] * v2[0] + v[1] * v2[1] + v[2] * v2[2]; lua_pushnumber(L, res); return 1; } else if (lua_isnumber(L, 2)) { float f = (float)lua_tonumber(L, 2); float* newv = newvector(L); newv[0] = v[0] * f; newv[1] = v[1] * f; newv[2] = v[2] * f; return 1; } //else lua_error(L,"mutiplying a vector with an invalid type"); } return 0; } int vector_add(lua_State* L) { float* v = (float*)lua_touserdata(L, 1); if (v) { if (vl_isvector(L, 2)) { float* v2 = (float*)lua_touserdata(L, 2); float* newv = newvector(L); newv[0] = v[0] + v2[0]; newv[1] = v[1] + v2[1]; newv[2] = v[2] + v2[2]; return 1; } //else lua_error(L,"adding a vector with an invalid type"); } return 0; } int vector_div(lua_State* L) { float* v = (float*)lua_touserdata(L, 1); if (v) { if (lua_isnumber(L, 2)) { float f = (float)lua_tonumber(L, 2); float* newv = newvector(L); newv[0] = v[0] / f; newv[1] = v[1] / f; newv[2] = v[2] / f; return 1; } //else lua_error(L,"dividing a vector with an invalid type"); } return 0; } int vector_sub(lua_State* L) { float* v = (float*)lua_touserdata(L, 1); if (v) { if (vl_isvector(L, 2)) { float* v2 = (float*)lua_touserdata(L, 2); float* newv = newvector(L); newv[0] = v[0] - v2[0]; newv[1] = v[1] - v2[1]; newv[2] = v[2] - v2[2]; return 1; } else if (lua_isnumber(L, 2)) { float f = (float)lua_tonumber(L, 2); float* newv = newvector(L); newv[0] = v[0] - f; newv[1] = v[1] - f; newv[2] = v[2] - f; return 1; } //else lua_error(L,"subtracting a vector with an invalid type"); } return 0; } int vector_unm(lua_State* L) { float* v = (float*)lua_touserdata(L, 1); if (v) { float* newv = newvector(L); newv[0] = -v[0]; newv[1] = -v[1]; newv[2] = -v[2]; return 1; } return 0; } int vector_pow(lua_State* L) { float* v = (float*)lua_touserdata(L, 1); if (v) { if (vl_isvector(L, 2)) { float* v2 = (float*)lua_touserdata(L, 2); float* newv = newvector(L); newv[0] = v[1] * v2[2] - v[2] * v2[1]; newv[1] = v[2] * v2[0] - v[0] * v2[2]; newv[2] = v[0] * v2[1] - v[1] * v2[0]; return 1; } //else lua_error(L,"cross product between vector and an invalid type"); } return 0; } int vl_newvector(lua_State* L) { newvector(L); return 1; } int vl_isvector(lua_State* L, int index) { const void* ptr; if (lua_type(L, index) != LUA_TUSERDATA) { return 0; } lua_getmetatable(L, index); ptr = lua_topointer(L, -1); lua_pop(L, 1); return (ptr == g_metatablePointer); } void vl_SetEventFunction(lua_State* L, const char* sEvent, lua_CFunction fn, int nTable) { lua_pushstring(L, sEvent); lua_pushcclosure(L, fn, 0); lua_rawset(L, nTable); } LUALIB_API int vl_initvectorlib(lua_State* L) { int nTable; // Create a new vector metatable. lua_newtable(L); nTable = lua_gettop(L); g_metatablePointer = lua_topointer(L, nTable); vl_SetEventFunction(L, "__newindex", vector_set, nTable); vl_SetEventFunction(L, "__index", vector_get, nTable); vl_SetEventFunction(L, "__mul", vector_mul, nTable); vl_SetEventFunction(L, "__div", vector_div, nTable); vl_SetEventFunction(L, "__add", vector_add, nTable); vl_SetEventFunction(L, "__sub", vector_sub, nTable); vl_SetEventFunction(L, "__pow", vector_pow, nTable); vl_SetEventFunction(L, "__unm", vector_unm, nTable); g_vectorMetatable = lua_ref(L, nTable); // pop table return 1; }
24.614583
88
0.508534
[ "vector" ]
4aa4091d1f7d3573a3f4485a0c8a3f74113046ea
13,150
h
C
usr/src/lib/libproc/common/Pcontrol.h
AsahiOS/gate
283d47da4e17a5871d9d575e7ffb81e8f6c52e51
[ "MIT" ]
null
null
null
usr/src/lib/libproc/common/Pcontrol.h
AsahiOS/gate
283d47da4e17a5871d9d575e7ffb81e8f6c52e51
[ "MIT" ]
null
null
null
usr/src/lib/libproc/common/Pcontrol.h
AsahiOS/gate
283d47da4e17a5871d9d575e7ffb81e8f6c52e51
[ "MIT" ]
1
2020-12-30T00:04:16.000Z
2020-12-30T00:04:16.000Z
/* * CDDL HEADER START * * The contents of this file are subject to the terms of the * Common Development and Distribution License (the "License"). * You may not use this file except in compliance with the License. * * You can obtain a copy of the license at usr/src/OPENSOLARIS.LICENSE * or http://www.opensolaris.org/os/licensing. * See the License for the specific language governing permissions * and limitations under the License. * * When distributing Covered Code, include this CDDL HEADER in each * file and include the License file at usr/src/OPENSOLARIS.LICENSE. * If applicable, add the following below this CDDL HEADER, with the * fields enclosed by brackets "[]" replaced with your own identifying * information: Portions Copyright [yyyy] [name of copyright owner] * * CDDL HEADER END */ /* * Copyright 2008 Sun Microsystems, Inc. All rights reserved. * Use is subject to license terms. */ /* * Copyright 2012 DEY Storage Systems, Inc. All rights reserved. * Copyright (c) 2013 by Delphix. All rights reserved. * Copyright 2018 Joyent, Inc. * Copyright 2020 OmniOS Community Edition (OmniOSce) Association. */ #ifndef _PCONTROL_H #define _PCONTROL_H /* * Implemention-specific include file for libproc process management. * This is not to be seen by the clients of libproc. */ #include <stdio.h> #include <gelf.h> #include <synch.h> #include <procfs.h> #include <rtld_db.h> #include <libproc.h> #include <libctf.h> #include <limits.h> #include <libproc.h> #include <thread.h> #include <sys/secflags.h> #ifdef __cplusplus extern "C" { #endif #include "Putil.h" /* * Definitions of the process control structures, internal to libproc. * These may change without affecting clients of libproc. */ /* * sym_tbl_t contains a primary and an (optional) auxiliary symbol table, which * we wish to treat as a single logical symbol table. In this logical table, * the data from the auxiliary table preceeds that from the primary. Symbol * indices start at [0], which is the first item in the auxiliary table * if there is one. The sole purpose for this is so that we can treat the * combination of .SUNW_ldynsym and .dynsym sections as a logically single * entity without having to violate the public interface to libelf. * * Both tables must share the same string table section. * * The symtab_getsym() function serves as a gelf_getsym() replacement * that is aware of the two tables and makes them look like a single table * to the caller. * */ typedef struct sym_tbl { /* symbol table */ Elf_Data *sym_data_pri; /* primary table */ Elf_Data *sym_data_aux; /* auxiliary table */ size_t sym_symn_aux; /* number of entries in auxiliary table */ size_t sym_symn; /* total number of entries in both tables */ char *sym_strs; /* ptr to strings */ size_t sym_strsz; /* size of string table */ GElf_Shdr sym_hdr_pri; /* primary symbol table section header */ GElf_Shdr sym_hdr_aux; /* auxiliary symbol table section header */ GElf_Shdr sym_strhdr; /* string table section header */ Elf *sym_elf; /* faked-up ELF handle from core file */ void *sym_elfmem; /* data for faked-up ELF handle */ uint_t *sym_byname; /* symbols sorted by name */ uint_t *sym_byaddr; /* symbols sorted by addr */ size_t sym_count; /* number of symbols in each sorted list */ } sym_tbl_t; typedef struct file_info { /* symbol information for a mapped file */ plist_t file_list; /* linked list */ char file_pname[PATH_MAX]; /* name from prmap_t */ struct map_info *file_map; /* primary (text) mapping */ int file_ref; /* references from map_info_t structures */ int file_fd; /* file descriptor for the mapped file */ int file_dbgfile; /* file descriptor for the debug file */ int file_init; /* 0: initialization yet to be performed */ GElf_Half file_etype; /* ELF e_type from ehdr */ GElf_Half file_class; /* ELF e_ident[EI_CLASS] from ehdr */ rd_loadobj_t *file_lo; /* load object structure from rtld_db */ char *file_lname; /* load object name from rtld_db */ char *file_lbase; /* pointer to basename of file_lname */ char *file_rname; /* resolved on-disk object pathname */ char *file_rbase; /* pointer to basename of file_rname */ Elf *file_elf; /* ELF handle so we can close */ Elf *file_dbgelf; /* Debug ELF handle so we can close */ void *file_elfmem; /* data for faked-up ELF handle */ sym_tbl_t file_symtab; /* symbol table */ sym_tbl_t file_dynsym; /* dynamic symbol table */ uintptr_t file_dyn_base; /* load address for ET_DYN files */ uintptr_t file_plt_base; /* base address for PLT */ size_t file_plt_size; /* size of PLT region */ uintptr_t file_jmp_rel; /* base address of PLT relocations */ uintptr_t file_ctf_off; /* offset of CTF data in object file */ size_t file_ctf_size; /* size of CTF data in object file */ int file_ctf_dyn; /* does the CTF data reference the dynsym */ void *file_ctf_buf; /* CTF data for this file */ ctf_file_t *file_ctfp; /* CTF container for this file */ char *file_shstrs; /* section header string table */ size_t file_shstrsz; /* section header string table size */ uintptr_t *file_saddrs; /* section header addresses */ uint_t file_nsaddrs; /* number of section header addresses */ } file_info_t; typedef struct map_info { /* description of an address space mapping */ prmap_t map_pmap; /* /proc description of this mapping */ file_info_t *map_file; /* pointer into list of mapped files */ off64_t map_offset; /* offset into core file (if core) */ int map_relocate; /* associated file_map needs to be relocated */ } map_info_t; typedef struct lwp_info { /* per-lwp information from core file */ plist_t lwp_list; /* linked list */ lwpid_t lwp_id; /* lwp identifier */ lwpsinfo_t lwp_psinfo; /* /proc/<pid>/lwp/<lwpid>/lwpsinfo data */ lwpstatus_t lwp_status; /* /proc/<pid>/lwp/<lwpid>/lwpstatus data */ char lwp_name[THREAD_NAME_MAX]; #if defined(sparc) || defined(__sparc) gwindows_t *lwp_gwins; /* /proc/<pid>/lwp/<lwpid>/gwindows data */ prxregset_t *lwp_xregs; /* /proc/<pid>/lwp/<lwpid>/xregs data */ int64_t *lwp_asrs; /* /proc/<pid>/lwp/<lwpid>/asrs data */ #endif } lwp_info_t; typedef struct fd_info { plist_t fd_list; /* linked list */ prfdinfo_t *fd_info; /* fd info */ } fd_info_t; typedef struct core_info { /* information specific to core files */ char core_dmodel; /* data model for core file */ char core_osabi; /* ELF OS ABI */ int core_errno; /* error during initialization if != 0 */ plist_t core_lwp_head; /* head of list of lwp info */ lwp_info_t *core_lwp; /* current lwp information */ uint_t core_nlwp; /* number of lwp's in list */ off64_t core_size; /* size of core file in bytes */ char *core_platform; /* platform string from core file */ struct utsname *core_uts; /* uname(2) data from core file */ prcred_t *core_cred; /* process credential from core file */ core_content_t core_content; /* content dumped to core file */ prpriv_t *core_priv; /* process privileges from core file */ size_t core_priv_size; /* size of the privileges */ void *core_privinfo; /* system privileges info from core file */ priv_impl_info_t *core_ppii; /* NOTE entry for core_privinfo */ char *core_zonename; /* zone name from core file */ prsecflags_t *core_secflags; /* secflags from core file */ prupanic_t *core_upanic; /* upanic from core file */ #if defined(__i386) || defined(__amd64) struct ssd *core_ldt; /* LDT entries from core file */ uint_t core_nldt; /* number of LDT entries in core file */ #endif } core_info_t; typedef struct elf_file_header { /* extended ELF header */ unsigned char e_ident[EI_NIDENT]; Elf64_Half e_type; Elf64_Half e_machine; Elf64_Word e_version; Elf64_Addr e_entry; Elf64_Off e_phoff; Elf64_Off e_shoff; Elf64_Word e_flags; Elf64_Half e_ehsize; Elf64_Half e_phentsize; Elf64_Half e_shentsize; Elf64_Word e_phnum; /* phdr count extended to 32 bits */ Elf64_Word e_shnum; /* shdr count extended to 32 bits */ Elf64_Word e_shstrndx; /* shdr string index extended to 32 bits */ } elf_file_header_t; typedef struct elf_file { /* convenience for managing ELF files */ elf_file_header_t e_hdr; /* Extended ELF header */ Elf *e_elf; /* ELF library handle */ int e_fd; /* file descriptor */ } elf_file_t; #define HASHSIZE 1024 /* hash table size, power of 2 */ struct ps_prochandle { struct ps_lwphandle **hashtab; /* hash table for LWPs (Lgrab()) */ mutex_t proc_lock; /* protects hash table; serializes Lgrab() */ pstatus_t orig_status; /* remembered status on Pgrab() */ pstatus_t status; /* status when stopped */ psinfo_t psinfo; /* psinfo_t from last Ppsinfo() request */ uintptr_t sysaddr; /* address of most recent syscall instruction */ pid_t pid; /* process-ID */ int state; /* state of the process, see "libproc.h" */ uint_t flags; /* see defines below */ uint_t agentcnt; /* Pcreate_agent()/Pdestroy_agent() ref count */ int asfd; /* /proc/<pid>/as filedescriptor */ int ctlfd; /* /proc/<pid>/ctl filedescriptor */ int statfd; /* /proc/<pid>/status filedescriptor */ int agentctlfd; /* /proc/<pid>/lwp/agent/ctl */ int agentstatfd; /* /proc/<pid>/lwp/agent/status */ int info_valid; /* if zero, map and file info need updating */ map_info_t *mappings; /* cached process mappings */ size_t map_count; /* number of mappings */ size_t map_alloc; /* number of mappings allocated */ uint_t num_files; /* number of file elements in file_info */ plist_t file_head; /* head of mapped files w/ symbol table info */ char *execname; /* name of the executable file */ auxv_t *auxv; /* the process's aux vector */ int nauxv; /* number of aux vector entries */ rd_agent_t *rap; /* cookie for rtld_db */ map_info_t *map_exec; /* the mapping for the executable file */ map_info_t *map_ldso; /* the mapping for ld.so.1 */ ps_ops_t ops; /* ops-vector */ uintptr_t *ucaddrs; /* ucontext-list addresses */ uint_t ucnelems; /* number of elements in the ucaddrs list */ char *zoneroot; /* cached path to zone root */ plist_t fd_head; /* head of file desc info list */ int num_fd; /* number of file descs in list */ uintptr_t map_missing; /* first missing mapping in core due to sig */ siginfo_t killinfo; /* signal that interrupted core dump */ psinfo_t spymaster; /* agent LWP's spymaster, if any */ void *data; /* private data */ }; /* flags */ #define CREATED 0x01 /* process was created by Pcreate() */ #define SETSIG 0x02 /* set signal trace mask before continuing */ #define SETFAULT 0x04 /* set fault trace mask before continuing */ #define SETENTRY 0x08 /* set sysentry trace mask before continuing */ #define SETEXIT 0x10 /* set sysexit trace mask before continuing */ #define SETHOLD 0x20 /* set signal hold mask before continuing */ #define SETREGS 0x40 /* set registers before continuing */ #define INCORE 0x80 /* use in-core data to build symbol tables */ struct ps_lwphandle { struct ps_prochandle *lwp_proc; /* process to which this lwp belongs */ struct ps_lwphandle *lwp_hash; /* hash table linked list */ lwpstatus_t lwp_status; /* status when stopped */ lwpsinfo_t lwp_psinfo; /* lwpsinfo_t from last Lpsinfo() */ lwpid_t lwp_id; /* lwp identifier */ int lwp_state; /* state of the lwp, see "libproc.h" */ uint_t lwp_flags; /* SETHOLD and/or SETREGS */ int lwp_ctlfd; /* /proc/<pid>/lwp/<lwpid>/lwpctl */ int lwp_statfd; /* /proc/<pid>/lwp/<lwpid>/lwpstatus */ }; /* * Implementation functions in the process control library. * These are not exported to clients of the library. */ extern void prldump(const char *, lwpstatus_t *); extern int dupfd(int, int); extern int set_minfd(void); extern int Pscantext(struct ps_prochandle *); extern void Pinitsym(struct ps_prochandle *); extern void Preadauxvec(struct ps_prochandle *); extern void optimize_symtab(sym_tbl_t *); extern void Pbuild_file_symtab(struct ps_prochandle *, file_info_t *); extern ctf_file_t *Pbuild_file_ctf(struct ps_prochandle *, file_info_t *); extern map_info_t *Paddr2mptr(struct ps_prochandle *, uintptr_t); extern char *Pfindexec(struct ps_prochandle *, const char *, int (*)(const char *, void *), void *); extern int getlwpstatus(struct ps_prochandle *, lwpid_t, lwpstatus_t *); int Pstopstatus(struct ps_prochandle *, long, uint32_t); extern file_info_t *file_info_new(struct ps_prochandle *, map_info_t *); extern char *Plofspath(const char *, char *, size_t); extern char *Pzoneroot(struct ps_prochandle *, char *, size_t); extern char *Pzonepath(struct ps_prochandle *, const char *, char *, size_t); extern fd_info_t *Pfd2info(struct ps_prochandle *, int); extern char *Pfindmap(struct ps_prochandle *, map_info_t *, char *, size_t); extern int Padd_mapping(struct ps_prochandle *, off64_t, file_info_t *, prmap_t *); extern void Psort_mappings(struct ps_prochandle *); extern char procfs_path[PATH_MAX]; /* * Architecture-dependent definition of the breakpoint instruction. */ #if defined(sparc) || defined(__sparc) #define BPT ((instr_t)0x91d02001) #elif defined(__i386) || defined(__amd64) #define BPT ((instr_t)0xcc) #endif /* * Simple convenience. */ #define TRUE 1 #define FALSE 0 #ifdef __cplusplus } #endif #endif /* _PCONTROL_H */
40.838509
79
0.72616
[ "object", "vector", "model" ]
4ab60301df2c737f6100ebcf9eec724ba43df424
932
h
C
ext/conv2d/kfft_cpx_conv.h
SkyMaverick/kfft
aed50c4d73bf581ff046df6832f93b75692a70fa
[ "BSD-3-Clause" ]
null
null
null
ext/conv2d/kfft_cpx_conv.h
SkyMaverick/kfft
aed50c4d73bf581ff046df6832f93b75692a70fa
[ "BSD-3-Clause" ]
null
null
null
ext/conv2d/kfft_cpx_conv.h
SkyMaverick/kfft
aed50c4d73bf581ff046df6832f93b75692a70fa
[ "BSD-3-Clause" ]
null
null
null
#pragma once #include "kfft.h" typedef struct { kfft_object_t object; uint32_t nfft; uint32_t x; uint32_t y; uint32_t flags; kfft_plan_c2d* plan_fwd; kfft_plan_c2d* plan_inv; } kfft_plan_c2cnv; KFFT_API kfft_plan_c2cnv* kfft_config2_conv_cpx(const uint32_t x, const uint32_t y, const uint32_t flags, kfft_pool_t* A, size_t* lenmem); KFFT_API kfft_return_t kfft_eval2_conv_cpx(kfft_plan_c2cnv* plan, const kfft_cpx* fin_A, const kfft_cpx* fin_B, kfft_cpx* fout); #if defined(KFFT_DYNAPI_ENABLE) // clang-format off typedef kfft_plan_c2cnv* (*kfft_callback_config_conv2_cpx)(const uint32_t x, const uint32_t y, const uint32_t flags, kfft_pool_t* A, size_t* lenmem); typedef kfft_return_t (*kfft_callback_eval_conv2_cpx)(kfft_plan_c2cnv* plan, const kfft_cpx* fin_A, const kfft_cpx* fin_B, kfft_cpx* fout); // clang-format on #endif /* KFFT_DYNAPI_ENABLE */
28.242424
124
0.73927
[ "object" ]
4ac2fc1f0bfd411027cb8a24ca142dc78c948f15
3,477
h
C
src/RecordCommand.h
zaporter/rr
513d8ee7a365077c505133b6efb294e3232656c8
[ "BSD-1-Clause" ]
null
null
null
src/RecordCommand.h
zaporter/rr
513d8ee7a365077c505133b6efb294e3232656c8
[ "BSD-1-Clause" ]
null
null
null
src/RecordCommand.h
zaporter/rr
513d8ee7a365077c505133b6efb294e3232656c8
[ "BSD-1-Clause" ]
null
null
null
/* -*- Mode: C++; tab-width: 8; c-basic-offset: 2; indent-tabs-mode: nil; -*- */ #ifndef RR_RECORD_COMMAND_H_ #define RR_RECORD_COMMAND_H_ #include "Command.h" #include "main.h" #include "util.h" #include "core.h" #include "RecordSession.h" using namespace std; namespace rr { struct RecordFlags { vector<string> extra_env; /* Max counter value before the scheduler interrupts a tracee. */ Ticks max_ticks; /* Whenever |ignore_sig| is pending for a tracee, decline to * deliver it. */ int ignore_sig; /* Whenever |continue_through_sig| is delivered to a tracee, if there is no * user handler and the signal would terminate the program, just ignore it. */ int continue_through_sig; /* Whether to use syscall buffering optimization during recording. */ RecordSession::SyscallBuffering use_syscall_buffer; /* If nonzero, the desired syscall buffer size. Must be a multiple of the page * size. */ size_t syscall_buffer_size; /* CPUID features to disable */ DisableCPUIDFeatures disable_cpuid_features; int print_trace_dir; string output_trace_dir; /* Whether to use file-cloning optimization during recording. */ bool use_file_cloning; /* Whether to use read-cloning optimization during recording. */ bool use_read_cloning; /* Whether tracee processes in record and replay are allowed * to run on any logical CPU. */ BindCPU bind_cpu; /* True if we should context switch after every rr event */ bool always_switch; /* Whether to enable chaos mode in the scheduler */ bool chaos; /* Controls number of cores reported to recorded process. */ int num_cores; /* True if we should wait for all processes to exit before finishing * recording. */ bool wait_for_all; /* Start child process directly if run under nested rr recording */ NestedBehavior nested; bool scarce_fds; bool setuid_sudo; unique_ptr<TraceUuid> trace_id; /* Copy preload sources to trace dir */ bool copy_preload_src; /* The signal to use for syscallbuf desched events */ int syscallbuf_desched_sig; /* True if we should load the audit library for SystemTap SDT support. */ bool stap_sdt; /* True if we should unmap the vdso */ bool unmap_vdso; /* True if we should always enable ASAN compatibility. */ bool asan; RecordFlags() : max_ticks(Scheduler::DEFAULT_MAX_TICKS), ignore_sig(0), continue_through_sig(0), use_syscall_buffer(RecordSession::ENABLE_SYSCALL_BUF), syscall_buffer_size(0), print_trace_dir(-1), output_trace_dir(""), use_file_cloning(true), use_read_cloning(true), bind_cpu(BIND_CPU), always_switch(false), chaos(false), num_cores(0), wait_for_all(false), nested(NESTED_ERROR), scarce_fds(false), setuid_sudo(false), copy_preload_src(false), syscallbuf_desched_sig(SYSCALLBUF_DEFAULT_DESCHED_SIGNAL), stap_sdt(false), unmap_vdso(false), asan(false) {} }; void force_close_record_session(); int start_recording(vector<string>& args, RecordFlags& flags); class RecordCommand : public Command { public: virtual int run(std::vector<std::string>& args) override; static RecordCommand* get() { return &singleton; } protected: RecordCommand(const char* name, const char* help) : Command(name, help) {} static RecordCommand singleton; }; } // namespace rr #endif // RR_RECORD_COMMAND_H_
26.340909
80
0.70348
[ "vector" ]
4ac3986d522aa63ed8dd4460c9258418cf4a3375
615
h
C
src/fitnessbasedduplicateremoval.h
j0r1/EATk
4ce34a030e21925532d2725cbb9460b19442424c
[ "MIT" ]
null
null
null
src/fitnessbasedduplicateremoval.h
j0r1/EATk
4ce34a030e21925532d2725cbb9460b19442424c
[ "MIT" ]
null
null
null
src/fitnessbasedduplicateremoval.h
j0r1/EATk
4ce34a030e21925532d2725cbb9460b19442424c
[ "MIT" ]
null
null
null
#pragma once #include "eatkconfig.h" #include "duplicateindividualremoval.h" #include "genomefitness.h" namespace eatk { class FitnessBasedDuplicateRemoval : public DuplicateIndividualRemoval { public: FitnessBasedDuplicateRemoval(const std::shared_ptr<FitnessComparison> &fitComp, size_t numObjectives); ~FitnessBasedDuplicateRemoval(); errut::bool_t check(const std::vector<std::shared_ptr<Individual>> &individuals) override; errut::bool_t removeDuplicates(std::vector<std::shared_ptr<Individual>> &individuals) override; private: std::shared_ptr<FitnessComparison> m_cmp; size_t m_numObjectives; }; }
26.73913
103
0.80813
[ "vector" ]
4ad05c530c31f0f7269b72dcd0f2dceb02458461
49,478
c
C
source/AccessorySDK/Support/HIDUtilsLinux.c
olli991/WirelessCarPlay
a6b51348a7df83c348d7467b2b1ccaa4e71bdc04
[ "MIT" ]
1
2020-03-10T15:53:34.000Z
2020-03-10T15:53:34.000Z
source/AccessorySDK/Support/HIDUtilsLinux.c
Vulpecula-nl/WirelessCarPlay
a6b51348a7df83c348d7467b2b1ccaa4e71bdc04
[ "MIT" ]
null
null
null
source/AccessorySDK/Support/HIDUtilsLinux.c
Vulpecula-nl/WirelessCarPlay
a6b51348a7df83c348d7467b2b1ccaa4e71bdc04
[ "MIT" ]
1
2021-08-30T14:20:33.000Z
2021-08-30T14:20:33.000Z
/* File: HIDUtilsLinux.c Package: Apple CarPlay Communication Plug-in. Abstract: n/a Version: 410.8 Disclaimer: IMPORTANT: This Apple software is supplied to you, by Apple Inc. ("Apple"), in your capacity as a current, and in good standing, Licensee in the MFi Licensing Program. Use of this Apple software is governed by and subject to the terms and conditions of your MFi License, including, but not limited to, the restrictions specified in the provision entitled ”Public Software”, and is further subject to your agreement to the following additional terms, and your agreement that the use, installation, modification or redistribution of this Apple software constitutes acceptance of these additional terms. If you do not agree with these additional terms, please do not use, install, modify or redistribute this Apple software. Subject to all of these terms and in consideration of your agreement to abide by them, Apple grants you, for as long as you are a current and in good-standing MFi Licensee, a personal, non-exclusive license, under Apple's copyrights in this original Apple software (the "Apple Software"), to use, reproduce, and modify the Apple Software in source form, and to use, reproduce, modify, and redistribute the Apple Software, with or without modifications, in binary form. While you may not redistribute the Apple Software in source form, should you redistribute the Apple Software in binary form, you must retain this notice and the following text and disclaimers in all such redistributions of the Apple Software. Neither the name, trademarks, service marks, or logos of Apple Inc. may be used to endorse or promote products derived from the Apple Software without specific prior written permission from Apple. Except as expressly stated in this notice, no other rights or licenses, express or implied, are granted by Apple herein, including but not limited to any patent rights that may be infringed by your derivative works or by other works in which the Apple Software may be incorporated. Unless you explicitly state otherwise, if you provide any ideas, suggestions, recommendations, bug fixes or enhancements to Apple in connection with this software (“Feedback”), you hereby grant to Apple a non-exclusive, fully paid-up, perpetual, irrevocable, worldwide license to make, use, reproduce, incorporate, modify, display, perform, sell, make or have made derivative works of, distribute (directly or indirectly) and sublicense, such Feedback in connection with Apple products and services. Providing this Feedback is voluntary, but if you do provide Feedback to Apple, you acknowledge and agree that Apple may exercise the license granted above without the payment of royalties or further consideration to Participant. The Apple Software is provided by Apple on an "AS IS" basis. APPLE MAKES NO WARRANTIES, EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION THE IMPLIED WARRANTIES OF NON-INFRINGEMENT, MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE, REGARDING THE APPLE SOFTWARE OR ITS USE AND OPERATION ALONE OR IN COMBINATION WITH YOUR PRODUCTS. IN NO EVENT SHALL APPLE BE LIABLE FOR ANY SPECIAL, INDIRECT, INCIDENTAL OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) ARISING IN ANY WAY OUT OF THE USE, REPRODUCTION, MODIFICATION AND/OR DISTRIBUTION OF THE APPLE SOFTWARE, HOWEVER CAUSED AND WHETHER UNDER THEORY OF CONTRACT, TORT (INCLUDING NEGLIGENCE), STRICT LIABILITY OR OTHERWISE, EVEN IF APPLE HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. Copyright (C) 2013-2015 Apple Inc. All Rights Reserved. */ #include "HIDUtils.h" #include <fcntl.h> #include <pthread.h> #include <sys/ioctl.h> #include "CFUtils.h" #include "CommonServices.h" #include "StringUtils.h" #include "ThreadUtils.h" #include "UUIDUtils.h" #include CF_RUNTIME_HEADER #include LIBDISPATCH_HEADER #if( HIDUTILS_HID_RAW ) #include <libudev.h> #include <linux/hidraw.h> #endif //=========================================================================================================================== // Internals //=========================================================================================================================== #if( HIDUTILS_HID_RAW ) static OSStatus _HIDDeviceCreateWithHIDRawDevice( HIDDeviceRef *outDevice, struct udev_device *inDevice ); static CFArrayRef _HIDCopyDevicesWithUdev( struct udev *inUdev, OSStatus *outErr ); #endif static pthread_mutex_t gVirtualHIDLock = PTHREAD_MUTEX_INITIALIZER; static CFMutableArrayRef gVirtualHIDDevices = NULL; ulog_define( HIDUtils, kLogLevelVerbose, kLogFlags_Default, "HID", NULL ); #define hid_dlog( LEVEL, ... ) dlogc( &log_category_from_name( HIDUtils ), (LEVEL), __VA_ARGS__ ) #define hid_ulog( LEVEL, ... ) ulog( &log_category_from_name( HIDUtils ), (LEVEL), __VA_ARGS__ ) #if 0 #pragma mark == HIDBrowser == #endif //=========================================================================================================================== // HIDBrowser //=========================================================================================================================== #if( HIDUTILS_HID_RAW ) typedef struct { HIDBrowserRef browser; // Owning browser. struct udev * udev; // udev object backing the monitor. struct udev_monitor * monitor; // udev monitor object. } HIDMonitorContext; #endif struct HIDBrowserPrivate { CFRuntimeBase base; // CF type info. Must be first. dispatch_queue_t queue; // Queue to run all operations and deliver callbacks on. #if( HIDUTILS_HID_RAW ) dispatch_source_t source; // Source to call us when events are pending. #endif CFMutableArrayRef devices; // Device objects we've detected. pthread_mutex_t devicesLock; // Lock for modifications to "devices". pthread_mutex_t * devicesLockPtr; // Ptr for devicesLock for NULL testing. HIDBrowserEventHandler_f eventHandler; // Function to call when an event occurs. void * eventContext; // Context to pass to function when an event occurs. }; static void _HIDBrowserGetTypeID( void *inContext ); static void _HIDBrowserFinalize( CFTypeRef inCF ); #if( HIDUTILS_HID_RAW ) static void _HIDBrowserReadHandler( void *inContext ); static void _HIDBrowserCancelHandler( void *inContext ); #endif static dispatch_once_t gHIDBrowserInitOnce = 0; static CFTypeID gHIDBrowserTypeID = _kCFRuntimeNotATypeID; static const CFRuntimeClass kHIDBrowserClass = { 0, // version "HIDBrowser", // className NULL, // init NULL, // copy _HIDBrowserFinalize, // finalize NULL, // equal -- NULL means pointer equality. NULL, // hash -- NULL means pointer hash. NULL, // copyFormattingDesc NULL, // copyDebugDesc NULL, // reclaim NULL // refcount }; //=========================================================================================================================== // HIDDevice //=========================================================================================================================== #if( HIDUTILS_HID_RAW ) typedef struct { HIDDeviceRef device; // Owning browser. int fd; // File desriptor for the hidraw device. uint8_t buf[ 4096 ]; // Buffer for reading reports from the device. } HIDDeviceContext; #endif struct HIDDevicePrivate { CFRuntimeBase base; // CF type info. Must be first. dispatch_queue_t queue; // Queue to run all operations and deliver callbacks on. #if( HIDUTILS_HID_RAW ) struct udev_device * hidrawDevice; // Underlying device this object is tracking. struct udev_device * hidDevice; // Weak reference to the HID parent of the device. struct udev_device * usbDevice; // Weak reference to the USB parent of the device. dispatch_source_t source; // Source for reading HID reports from the hidraw dev node. #endif CFNumberRef countryCode; // Country code. CFStringRef displayUUID; // Display this HID device is associated with (or NULL if none). CFStringRef name; // Name of the device (e.g. "ShuttleXpress"). CFNumberRef productID; // USB product ID of device. CFDataRef reportDescriptor; // HID descriptor to describe reports for this device. CFNumberRef sampleRate; // Sample rate of the device. uint8_t uuid[ 16 ]; // UUID for device. May not be persistent. CFNumberRef vendorID; // USB vendor ID of device. Boolean started; // True if the device has been started. HIDDeviceEventHandler_f eventHandler; // Function to call when a event is received from the device. void * eventContext; // Context to pass to event handler. }; static void _HIDDeviceGetTypeID( void *inContext ); static void _HIDDeviceFinalize( CFTypeRef inCF ); #if( HIDUTILS_HID_RAW ) static CFDataRef _HIDDeviceCopyReportDescriptor( HIDDeviceRef inDevice, OSStatus *outErr ); static void _HIDDeviceReadHandler( void *inContext ); static void _HIDDeviceCancelHandler( void *inContext ); #endif static dispatch_once_t gHIDDeviceInitOnce = 0; static CFTypeID gHIDDeviceTypeID = _kCFRuntimeNotATypeID; static const CFRuntimeClass kHIDDeviceClass = { 0, // version "HIDDevice", // className NULL, // init NULL, // copy _HIDDeviceFinalize, // finalize NULL, // equal -- NULL means pointer equality. NULL, // hash -- NULL means pointer hash. NULL, // copyFormattingDesc NULL, // copyDebugDesc NULL, // reclaim NULL // refcount }; #if 0 #pragma mark - #endif //=========================================================================================================================== // HIDBrowserGetTypeID //=========================================================================================================================== CFTypeID HIDBrowserGetTypeID( void ) { dispatch_once_f( &gHIDBrowserInitOnce, NULL, _HIDBrowserGetTypeID ); return( gHIDBrowserTypeID ); } static void _HIDBrowserGetTypeID( void *inContext ) { (void) inContext; gHIDBrowserTypeID = _CFRuntimeRegisterClass( &kHIDBrowserClass ); check( gHIDBrowserTypeID != _kCFRuntimeNotATypeID ); } //=========================================================================================================================== // HIDBrowserCreate //=========================================================================================================================== OSStatus HIDBrowserCreate( HIDBrowserRef *outBrowser ) { OSStatus err; HIDBrowserRef me; size_t extraLen; extraLen = sizeof( *me ) - sizeof( me->base ); me = (HIDBrowserRef) _CFRuntimeCreateInstance( NULL, HIDBrowserGetTypeID(), (CFIndex) extraLen, NULL ); require_action( me, exit, err = kNoMemoryErr ); memset( ( (uint8_t *) me ) + sizeof( me->base ), 0, extraLen ); me->queue = dispatch_get_main_queue(); arc_safe_dispatch_retain( me->queue ); err = pthread_mutex_init( &me->devicesLock, NULL ); require_noerr( err, exit ); me->devicesLockPtr = &me->devicesLock; *outBrowser = me; me = NULL; err = kNoErr; exit: CFReleaseNullSafe( me ); return( err ); } //=========================================================================================================================== // _HIDBrowserFinalize //=========================================================================================================================== static void _HIDBrowserFinalize( CFTypeRef inCF ) { HIDBrowserRef const me = (HIDBrowserRef) inCF; #if( HIDUTILS_HID_RAW ) check( !me->source ); #endif check( !me->devices ); pthread_mutex_forget( &me->devicesLockPtr ); dispatch_forget( &me->queue ); } //=========================================================================================================================== // HIDBrowserCopyProperty //=========================================================================================================================== CFTypeRef HIDBrowserCopyProperty( HIDBrowserRef inBrowser, CFStringRef inProperty, CFTypeRef inQualifier, OSStatus *outErr ) { OSStatus err; CFTypeRef value = NULL; (void) inQualifier; if( 0 ) {} // Devices else if( CFEqual( inProperty, kHIDBrowserProperty_Devices ) ) { pthread_mutex_lock( inBrowser->devicesLockPtr ); if( inBrowser->devices ) { value = CFArrayCreateCopy( NULL, inBrowser->devices ); pthread_mutex_unlock( inBrowser->devicesLockPtr ); require_action( value, exit, err = kNoMemoryErr ); } else { pthread_mutex_unlock( inBrowser->devicesLockPtr ); } if( !value ) { value = CFArrayCreate( NULL, NULL, 0, &kCFTypeArrayCallBacks ); require_action( value, exit, err = kNoMemoryErr ); } } // Unknown... else { err = kNotFoundErr; goto exit; } err = kNoErr; exit: if( outErr ) *outErr = err; return( value ); } //=========================================================================================================================== // HIDBrowserSetProperty //=========================================================================================================================== OSStatus HIDBrowserSetProperty( HIDBrowserRef inBrowser, CFStringRef inProperty, CFTypeRef inQualifier, CFTypeRef inValue ) { OSStatus err; (void) inBrowser; (void) inProperty; (void) inValue; (void) inQualifier; if( 0 ) {} // Unknown... else { err = kNotHandledErr; goto exit; } err = kNoErr; exit: return( err ); } //=========================================================================================================================== // HIDBrowserSetDispatchQueue //=========================================================================================================================== void HIDBrowserSetDispatchQueue( HIDBrowserRef inBrowser, dispatch_queue_t inQueue ) { ReplaceDispatchQueue( &inBrowser->queue, inQueue ); } //=========================================================================================================================== // HIDBrowserSetEventHandler //=========================================================================================================================== void HIDBrowserSetEventHandler( HIDBrowserRef inBrowser, HIDBrowserEventHandler_f inHandler, void *inContext ) { inBrowser->eventHandler = inHandler; inBrowser->eventContext = inContext; } //=========================================================================================================================== // HIDBrowserStart //=========================================================================================================================== static void _HIDBrowserStart( void *inContext ); OSStatus HIDBrowserStart( HIDBrowserRef inBrowser ) { hid_dlog( kLogLevelTrace, "HID browser starting...\n" ); CFRetain( inBrowser ); dispatch_async_f( inBrowser->queue, inBrowser, _HIDBrowserStart ); return( kNoErr ); } static void _HIDBrowserStart( void *inContext ) { HIDBrowserRef const browser = (HIDBrowserRef) inContext; OSStatus err; CFMutableArrayRef array; #if( HIDUTILS_HID_RAW ) struct udev * udev; HIDMonitorContext * ctx; int fd; #endif CFIndex i, n; HIDDeviceRef hidDevice; #if( HIDUTILS_HID_RAW ) dispatch_source_forget( &browser->source ); // Start listening for device attaches and detaches. ctx = (HIDMonitorContext *) calloc( 1, sizeof( *ctx ) ); require_action( ctx, exit, err = kNoMemoryErr ); ctx->browser = browser; ctx->udev = udev = udev_new(); require_action( udev, exit, err = kUnknownErr ); ctx->monitor = udev_monitor_new_from_netlink( udev, "udev" ); require_action( ctx->monitor, exit, err = kUnknownErr ); err = udev_monitor_filter_add_match_subsystem_devtype( ctx->monitor, "hidraw", NULL ); require_noerr( err, exit ); err = udev_monitor_enable_receiving( ctx->monitor ); require_noerr( err, exit ); #endif // Get the already-attached devices. #if( HIDUTILS_HID_RAW ) array = _HIDCopyDevicesWithUdev( udev, NULL ); if( !array ) #endif { array = CFArrayCreateMutable( NULL, 0, &kCFTypeArrayCallBacks ); require_action( array, exit, err = kNoMemoryErr ); } pthread_mutex_lock( browser->devicesLockPtr ); ReplaceCF( &browser->devices, array ); pthread_mutex_unlock( browser->devicesLockPtr ); CFRelease( array ); pthread_mutex_lock( &gVirtualHIDLock ); n = gVirtualHIDDevices ? CFArrayGetCount( gVirtualHIDDevices ) : 0; for( i = 0; i < n; ++i ) { hidDevice = (HIDDeviceRef) CFArrayGetValueAtIndex( gVirtualHIDDevices, i ); pthread_mutex_lock( browser->devicesLockPtr ); CFArrayAppendValue( browser->devices, hidDevice ); pthread_mutex_unlock( browser->devicesLockPtr ); } pthread_mutex_unlock( &gVirtualHIDLock ); #if( HIDUTILS_HID_RAW ) // Set up to be notified when a device is attached/detached. fd = udev_monitor_get_fd( ctx->monitor ); require_action( fd >= 0, exit, err = kUnknownErr ); browser->source = dispatch_source_create( DISPATCH_SOURCE_TYPE_READ, fd, 0, browser->queue ); require_action( browser->source, exit, err = kUnknownErr ); CFRetain( browser ); dispatch_set_context( browser->source, ctx ); dispatch_source_set_event_handler_f( browser->source, _HIDBrowserReadHandler ); dispatch_source_set_cancel_handler_f( browser->source, _HIDBrowserCancelHandler ); dispatch_resume( browser->source ); ctx = NULL; #endif // Fake attach events for each device that was already attached. if( browser->eventHandler ) { n = CFArrayGetCount( browser->devices ); for( i = 0; i < n; ++i ) { hidDevice = (HIDDeviceRef) CFArrayGetValueAtIndex( browser->devices, i ); browser->eventHandler( kHIDBrowserEventAttached, hidDevice, browser->eventContext ); } browser->eventHandler( kHIDBrowserEventStarted, NULL, browser->eventContext ); } err = kNoErr; hid_dlog( kLogLevelTrace, "HID browser started\n" ); exit: #if( HIDUTILS_HID_RAW ) if( ctx ) { if( ctx->monitor ) udev_monitor_unref( ctx->monitor ); if( ctx->udev ) udev_unref( ctx->udev ); free( ctx ); } #endif if( err ) { hid_ulog( kLogLevelNotice, "### HID browser start failed: %#m\n", err ); if( browser->eventHandler ) browser->eventHandler( kHIDBrowserEventStopped, NULL, browser->eventContext ); pthread_mutex_lock( browser->devicesLockPtr ); ForgetCF( &browser->devices ); pthread_mutex_unlock( browser->devicesLockPtr ); } CFRelease( browser ); } //=========================================================================================================================== // HIDBrowserStop //=========================================================================================================================== static void _HIDBrowserStop( void *inContext ); void HIDBrowserStop( HIDBrowserRef inBrowser ) { hid_dlog( kLogLevelTrace, "HID browser stopping...\n" ); CFRetain( inBrowser ); dispatch_async_f( inBrowser->queue, inBrowser, _HIDBrowserStop ); } static void _HIDBrowserStop( void *inContext ) { HIDBrowserRef const browser = (HIDBrowserRef) inContext; #if( HIDUTILS_HID_RAW ) dispatch_source_forget( &browser->source ); #endif if( browser->eventHandler ) browser->eventHandler( kHIDBrowserEventStopped, NULL, browser->eventContext ); pthread_mutex_lock( browser->devicesLockPtr ); ForgetCF( &browser->devices ); pthread_mutex_unlock( browser->devicesLockPtr ); CFRelease( browser ); hid_dlog( kLogLevelTrace, "HID browser stopped\n" ); } //=========================================================================================================================== // HIDBrowserStopDevices //=========================================================================================================================== static void _HIDBrowserStopDevices( void *inContext ); void HIDBrowserStopDevices( HIDBrowserRef inBrowser ) { hid_dlog( kLogLevelTrace, "HID browser stopping devices...\n" ); CFRetain( inBrowser ); dispatch_async_f( inBrowser->queue, inBrowser, _HIDBrowserStopDevices ); } static void _HIDBrowserStopDevices( void *inContext ) { HIDBrowserRef const browser = (HIDBrowserRef) inContext; CFIndex i, n; HIDDeviceRef hidDevice; n = browser->devices ? CFArrayGetCount( browser->devices ) : 0; for( i = 0; i < n; ++i ) { hidDevice = (HIDDeviceRef) CFArrayGetValueAtIndex( browser->devices, i ); HIDDeviceStop( hidDevice ); } CFRelease( browser ); hid_dlog( kLogLevelTrace, "HID browser stopped devices\n" ); } #if( HIDUTILS_HID_RAW ) //=========================================================================================================================== // _HIDBrowserReadHandler //=========================================================================================================================== static void _HIDBrowserReadHandler( void *inContext ) { HIDMonitorContext * const ctx = (HIDMonitorContext *) inContext; HIDBrowserRef const browser = ctx->browser; OSStatus err; const char * action = "?"; struct udev_device * device; const char * path; const char * path2; CFIndex i, n; HIDDeviceRef hidDevice; device = udev_monitor_receive_device( ctx->monitor ); require_action( device, exit, err = kReadErr ); path = udev_device_get_devnode( device ); require_action( path, exit, err = kPathErr ); // Match the device by its /dev path. hidDevice = NULL; n = CFArrayGetCount( browser->devices ); for( i = 0; i < n; ++i ) { hidDevice = (HIDDeviceRef) CFArrayGetValueAtIndex( browser->devices, i ); if( !hidDevice->hidrawDevice ) continue; path2 = udev_device_get_devnode( hidDevice->hidrawDevice ); check( path2 ); if( !path2 ) continue; if( strcmp( path, path2 ) == 0 ) { break; } } if( i >= n ) hidDevice = NULL; // Process event by action. action = udev_device_get_action( device ); require_action( action, exit, err = kParamErr ); if( strcmp( action, "add" ) == 0 ) { if( !hidDevice ) { err = _HIDDeviceCreateWithHIDRawDevice( &hidDevice, device ); require_noerr( err, exit ); pthread_mutex_lock( browser->devicesLockPtr ); CFArrayAppendValue( browser->devices, hidDevice ); pthread_mutex_unlock( browser->devicesLockPtr ); hid_ulog( kLogLevelTrace, "HID device attached: %#U (%@)\n", hidDevice->uuid, hidDevice->name ); if( browser->eventHandler ) browser->eventHandler( kHIDBrowserEventAttached, hidDevice, browser->eventContext ); CFRelease( hidDevice ); } } else if( strcmp( action, "remove" ) == 0 ) { if( hidDevice ) { hid_ulog( kLogLevelTrace, "HID device detached: %#U (%@)\n", hidDevice->uuid, hidDevice->name ); if( browser->eventHandler ) browser->eventHandler( kHIDBrowserEventDetached, hidDevice, browser->eventContext ); pthread_mutex_lock( browser->devicesLockPtr ); CFArrayRemoveValueAtIndex( browser->devices, i ); pthread_mutex_unlock( browser->devicesLockPtr ); } } else { hid_dlog( kLogLevelNotice, "HID device action: '%s'\n" ); } err = kNoErr; exit: if( err ) hid_ulog( kLogLevelNotice, "### HID browser action '%s' failed: %#m\n", action, err ); if( device ) udev_device_unref( device ); } //=========================================================================================================================== // _HIDBrowserCancelHandler //=========================================================================================================================== static void _HIDBrowserCancelHandler( void *inContext ) { HIDMonitorContext * const ctx = (HIDMonitorContext *) inContext; hid_dlog( kLogLevelTrace, "HID browser canceling...\n" ); udev_monitor_unref( ctx->monitor ); udev_unref( ctx->udev ); CFRelease( ctx->browser ); free( ctx ); hid_dlog( kLogLevelTrace, "HID browser canceled\n" ); } #endif // HIDUTILS_HID_RAW #if 0 #pragma mark - #pragma mark == HIDDevice == #endif //=========================================================================================================================== // HIDDeviceGetTypeID //=========================================================================================================================== CFTypeID HIDDeviceGetTypeID( void ) { dispatch_once_f( &gHIDDeviceInitOnce, NULL, _HIDDeviceGetTypeID ); return( gHIDDeviceTypeID ); } static void _HIDDeviceGetTypeID( void *inContext ) { (void) inContext; gHIDDeviceTypeID = _CFRuntimeRegisterClass( &kHIDDeviceClass ); check( gHIDDeviceTypeID != _kCFRuntimeNotATypeID ); } //=========================================================================================================================== // HIDDeviceCreateVirtual //=========================================================================================================================== OSStatus HIDDeviceCreateVirtual( HIDDeviceRef *outDevice, CFDictionaryRef inProperties ) { OSStatus err; HIDDeviceRef me; size_t extraLen; CFTypeRef property; uint8_t uuid[ 16 ]; char cstr[ 128 ]; int64_t s64; extraLen = sizeof( *me ) - sizeof( me->base ); me = (HIDDeviceRef) _CFRuntimeCreateInstance( NULL, HIDDeviceGetTypeID(), (CFIndex) extraLen, NULL ); require_action( me, exit, err = kNoMemoryErr ); memset( ( (uint8_t *) me ) + sizeof( me->base ), 0, extraLen ); me->queue = dispatch_get_main_queue(); arc_safe_dispatch_retain( me->queue ); UUIDGet( me->uuid ); if( inProperties ) { #if 1 s64 = CFDictionaryGetInt64( inProperties, kHIDDeviceProperty_CountryCode, &err ); if( !err ) me->countryCode = CFNumberCreateInt64( s64 ); s64 = CFDictionaryGetInt64( inProperties, kHIDDeviceProperty_ProductID, &err ); if( !err ) me->productID = CFNumberCreateInt64( s64 ); s64 = CFDictionaryGetInt64( inProperties, kHIDDeviceProperty_VendorID, &err ); if( !err ) me->vendorID = CFNumberCreateInt64( s64 ); #endif err = CFDictionaryGetUUID( inProperties, kHIDDeviceProperty_DisplayUUID, uuid ); if( !err ) { UUIDtoCString( uuid, false, cstr ); me->displayUUID = CFStringCreateWithCString( NULL, cstr, kCFStringEncodingUTF8 ); require_action( me->displayUUID, exit, err = kUnknownErr ); } property = CFDictionaryGetCFString( inProperties, kHIDDeviceProperty_Name, NULL ); if( property ) { CFRetain( property ); me->name = (CFStringRef) property; } property = CFDictionaryCopyCFData( inProperties, kHIDDeviceProperty_ReportDescriptor, NULL, NULL ); if( property ) me->reportDescriptor = (CFDataRef) property; s64 = CFDictionaryGetInt64( inProperties, kHIDDeviceProperty_SampleRate, &err ); if( !err ) { me->sampleRate = CFNumberCreateInt64( s64 ); require_action( me->sampleRate, exit, err = kUnknownErr ); } CFDictionaryGetUUID( inProperties, kHIDDeviceProperty_UUID, me->uuid ); } *outDevice = me; me = NULL; err = kNoErr; exit: CFReleaseNullSafe( me ); return( err ); } #if( HIDUTILS_HID_RAW ) //=========================================================================================================================== // _HIDDeviceCreateWithHIDRawDevice //=========================================================================================================================== static OSStatus _HIDDeviceCreateWithHIDRawDevice( HIDDeviceRef *outDevice, struct udev_device *inDevice ) { OSStatus err; HIDDeviceRef me; size_t extraLen; const char * str; extraLen = sizeof( *me ) - sizeof( me->base ); me = (HIDDeviceRef) _CFRuntimeCreateInstance( NULL, HIDDeviceGetTypeID(), (CFIndex) extraLen, NULL ); require_action( me, exit, err = kNoMemoryErr ); memset( ( (uint8_t *) me ) + sizeof( me->base ), 0, extraLen ); me->queue = dispatch_get_main_queue(); arc_safe_dispatch_retain( me->queue ); me->hidDevice = udev_device_get_parent_with_subsystem_devtype( inDevice, "hid", NULL ); require_action( me->hidDevice, exit, err = kIncompatibleErr ); me->usbDevice = udev_device_get_parent_with_subsystem_devtype( inDevice, "usb", "usb_device" ); require_action( me->usbDevice, exit, err = kIncompatibleErr ); str = udev_device_get_sysattr_value( me->usbDevice, "product" ); if( !str ) str = "?"; me->name = CFStringCreateWithCString( NULL, str, kCFStringEncodingUTF8 ); require_action( me->name, exit, err = kFormatErr ); udev_device_ref( inDevice ); me->hidrawDevice = inDevice; UUIDGet( me->uuid ); *outDevice = me; me = NULL; err = kNoErr; exit: CFReleaseNullSafe( me ); return( err ); } #endif //=========================================================================================================================== // _HIDDeviceFinalize //=========================================================================================================================== static void _HIDDeviceFinalize( CFTypeRef inCF ) { HIDDeviceRef const me = (HIDDeviceRef) inCF; ForgetCF( &me->countryCode ); ForgetCF( &me->displayUUID ); ForgetCF( &me->name ); ForgetCF( &me->productID ); ForgetCF( &me->reportDescriptor ); ForgetCF( &me->sampleRate ); ForgetCF( &me->vendorID ); #if( HIDUTILS_HID_RAW ) if( me->hidrawDevice ) udev_device_unref( me->hidrawDevice ); check( !me->source ); #endif dispatch_forget( &me->queue ); hid_dlog( kLogLevelVerbose, "HID device finalized\n" ); } //=========================================================================================================================== // HIDDeviceSetDispatchQueue //=========================================================================================================================== void HIDDeviceSetDispatchQueue( HIDDeviceRef inDevice, dispatch_queue_t inQueue ) { ReplaceDispatchQueue( &inDevice->queue, inQueue ); } //=========================================================================================================================== // HIDDeviceSetEventHandler //=========================================================================================================================== void HIDDeviceSetEventHandler( HIDDeviceRef inDevice, HIDDeviceEventHandler_f inHandler, void *inContext ) { inDevice->eventHandler = inHandler; inDevice->eventContext = inContext; } //=========================================================================================================================== // HIDDeviceCopyProperty //=========================================================================================================================== CFTypeRef HIDDeviceCopyProperty( HIDDeviceRef inDevice, CFStringRef inProperty, CFTypeRef inQualifier, OSStatus *outErr ) { OSStatus err; CFTypeRef value = NULL; char cstr[ 128 ]; (void) inQualifier; if( 0 ) {} // CountryCode else if( CFEqual( inProperty, kHIDDeviceProperty_CountryCode ) ) { value = inDevice->countryCode; if( value ) CFRetain( value ); } // DisplayUUID else if( CFEqual( inProperty, kHIDDeviceProperty_DisplayUUID ) ) { value = inDevice->displayUUID; require_action_quiet( value, exit, err = kNotFoundErr ); CFRetain( value ); } // ProductID else if( CFEqual( inProperty, kHIDDeviceProperty_ProductID ) ) { value = inDevice->productID; if( value ) CFRetain( value ); } // Name else if( CFEqual( inProperty, kHIDDeviceProperty_Name ) ) { value = inDevice->name; CFRetain( value ); } // ReportDescriptor else if( CFEqual( inProperty, kHIDDeviceProperty_ReportDescriptor ) ) { value = inDevice->reportDescriptor; if( value ) { CFRetain( value ); } else { #if( HIDUTILS_HID_RAW ) value = _HIDDeviceCopyReportDescriptor( inDevice, &err ); require_noerr( err, exit ); #else err = kNotFoundErr; goto exit; #endif } } // SampleRate else if( CFEqual( inProperty, kHIDDeviceProperty_SampleRate ) ) { value = inDevice->sampleRate; if( value ) CFRetain( value ); } // UUID else if( CFEqual( inProperty, kHIDDeviceProperty_UUID ) ) { value = CFStringCreateWithCString( NULL, UUIDtoCString( inDevice->uuid, false, cstr ), kCFStringEncodingUTF8 ); require_action( value, exit, err = kNoMemoryErr ); } // VendorID else if( CFEqual( inProperty, kHIDDeviceProperty_VendorID ) ) { value = inDevice->vendorID; if( value ) CFRetain( value ); } // Unknown... else { err = kNotFoundErr; goto exit; } err = kNoErr; exit: if( outErr ) *outErr = err; return( value ); } #if( HIDUTILS_HID_RAW ) //=========================================================================================================================== // _HIDDeviceCopyReportDescriptor //=========================================================================================================================== static CFDataRef _HIDDeviceCopyReportDescriptor( HIDDeviceRef inDevice, OSStatus *outErr ) { CFDataRef data = NULL; OSStatus err; const char * path; int fd = -1; int size; struct hidraw_report_descriptor desc; struct hidraw_devinfo hidrawInfo; HIDInfo hidInfo; const uint8_t * descPtr; uint8_t * descBuf = NULL; size_t descLen; require_action( inDevice->hidrawDevice, exit, err = kUnsupportedErr ); path = udev_device_get_devnode( inDevice->hidrawDevice ); require_action( path, exit, err = kPathErr ); fd = open( path, O_RDWR ); err = map_fd_creation_errno( fd ); require_noerr( err, exit ); err = ioctl( fd, HIDIOCGRAWINFO, &hidrawInfo ); err = map_global_noerr_errno( err ); require_noerr( err, exit ); HIDInfoInit( &hidInfo ); hidInfo.vendorID = hidrawInfo.vendor; hidInfo.productID = hidrawInfo.product; err = HIDCopyOverrideDescriptor( &hidInfo, &descBuf, &descLen ); if( err ) { size = 0; err = ioctl( fd, HIDIOCGRDESCSIZE, &size ); err = map_global_noerr_errno( err ); require_noerr( err, exit ); memset( &desc, 0, sizeof( desc ) ); desc.size = size; err = ioctl( fd, HIDIOCGRDESC, &desc ); err = map_global_noerr_errno( err ); require_noerr( err, exit ); descPtr = desc.value; descLen = desc.size; } else { descPtr = descBuf; } data = CFDataCreate( NULL, descPtr, (CFIndex) descLen ); require_action( data, exit, err = kNoMemoryErr ); exit: FreeNullSafe( descBuf ); ForgetFD( &fd ); if( outErr ) *outErr = err; return( data ); } #endif //=========================================================================================================================== // HIDDeviceSetProperty //=========================================================================================================================== OSStatus HIDDeviceSetProperty( HIDDeviceRef inDevice, CFStringRef inProperty, CFTypeRef inQualifier, CFTypeRef inValue ) { OSStatus err; int64_t s64; CFNumberRef num; (void) inQualifier; if( 0 ) {} // CountryCode else if( CFEqual( inProperty, kHIDDeviceProperty_CountryCode ) ) { s64 = CFGetInt64( inValue, &err ); require_noerr( err, exit ); num = CFNumberCreateInt64( s64 ); require_action( num, exit, err = kUnknownErr ); CFReleaseNullSafe( inDevice->countryCode ); inDevice->countryCode = num; } // DisplayUUID else if( CFEqual( inProperty, kHIDDeviceProperty_DisplayUUID ) ) { require_action( !inValue || CFIsType( inValue, CFString ), exit, err = kTypeErr ); CFRetainNullSafe( inValue ); CFReleaseNullSafe( inDevice->displayUUID ); inDevice->displayUUID = (CFStringRef) inValue; } // Name else if( CFEqual( inProperty, kHIDDeviceProperty_Name ) ) { require_action( !inValue || CFIsType( inValue, CFString ), exit, err = kTypeErr ); CFRetainNullSafe( inValue ); CFReleaseNullSafe( inDevice->name ); inDevice->name = (CFStringRef) inValue; } // ProductID else if( CFEqual( inProperty, kHIDDeviceProperty_ProductID ) ) { s64 = CFGetInt64( inValue, &err ); require_noerr( err, exit ); num = CFNumberCreateInt64( s64 ); require_action( num, exit, err = kUnknownErr ); CFReleaseNullSafe( inDevice->productID ); inDevice->productID = num; } // ReportDescriptor else if( CFEqual( inProperty, kHIDDeviceProperty_ReportDescriptor ) ) { require_action( !inValue || CFIsType( inValue, CFData ), exit, err = kTypeErr ); CFRetainNullSafe( inValue ); CFReleaseNullSafe( inDevice->reportDescriptor ); inDevice->reportDescriptor = (CFDataRef) inValue; } // SampleRate else if( CFEqual( inProperty, kHIDDeviceProperty_SampleRate ) ) { s64 = CFGetInt64( inValue, &err ); require_noerr( err, exit ); num = CFNumberCreateInt64( s64 ); require_action( num, exit, err = kUnknownErr ); CFReleaseNullSafe( inDevice->sampleRate ); inDevice->sampleRate = num; } // VendorID else if( CFEqual( inProperty, kHIDDeviceProperty_VendorID ) ) { s64 = CFGetInt64( inValue, &err ); require_noerr( err, exit ); num = CFNumberCreateInt64( s64 ); require_action( num, exit, err = kUnknownErr ); CFReleaseNullSafe( inDevice->vendorID ); inDevice->vendorID = num; } // Unknown... else { err = kNotHandledErr; goto exit; } err = kNoErr; exit: return( err ); } //=========================================================================================================================== // HIDDevicePostReport //=========================================================================================================================== typedef struct { HIDDeviceRef device; size_t reportLen; uint8_t reportData[ 1 ]; // Variable length. } HIDDevicePostReportParams; static void _HIDDevicePostReport( void *inContext ); OSStatus HIDDevicePostReport( HIDDeviceRef inDevice, const void *inReportPtr, size_t inReportLen ) { OSStatus err; HIDDevicePostReportParams * params; params = (HIDDevicePostReportParams *) malloc( offsetof( HIDDevicePostReportParams, reportData ) + inReportLen ); require_action( params, exit, err = kNoMemoryErr ); CFRetain( inDevice ); params->device = inDevice; params->reportLen = inReportLen; memcpy( params->reportData, inReportPtr, inReportLen ); dispatch_async_f( inDevice->queue, params, _HIDDevicePostReport ); err = kNoErr; exit: return( err ); } static void _HIDDevicePostReport( void *inContext ) { HIDDevicePostReportParams * const params = (HIDDevicePostReportParams *) inContext; HIDDeviceRef const device = params->device; if( device->eventHandler ) { device->eventHandler( device, kHIDDeviceEventReport, kNoErr, params->reportData, params->reportLen, device->eventContext ); } CFRelease( device ); free( params ); } //=========================================================================================================================== // HIDDeviceStart //=========================================================================================================================== static void _HIDDeviceStart( void *inContext ); OSStatus HIDDeviceStart( HIDDeviceRef inDevice ) { hid_dlog( kLogLevelVerbose, "HID device starting...\n" ); CFRetain( inDevice ); dispatch_async_f( inDevice->queue, inDevice, _HIDDeviceStart ); return( kNoErr ); } static void _HIDDeviceStart( void *inContext ) { HIDDeviceRef const device = (HIDDeviceRef) inContext; #if( HIDUTILS_HID_RAW ) OSStatus err; HIDDeviceContext * ctx = NULL; const char * path; // If there's no HID raw device, it's a virtual device so start doesn't need to do anything. if( !device->hidrawDevice ) { device->started = true; err = kNoErr; goto exit; } dispatch_source_forget( &device->source ); ctx = (HIDDeviceContext *) calloc( 1, sizeof( *ctx ) ); require_action( ctx, exit, err = kNoMemoryErr ); ctx->device = device; ctx->fd = -1; path = udev_device_get_devnode( device->hidrawDevice ); require_action( path, exit, err = kPathErr ); ctx->fd = open( path, O_RDWR ); err = map_fd_creation_errno( ctx->fd ); require_noerr( err, exit ); err = fcntl( ctx->fd, F_SETFL, fcntl( ctx->fd, F_GETFL, 0 ) | O_NONBLOCK ); err = map_global_value_errno( err != -1, err ); require_noerr( err, exit ); device->source = dispatch_source_create( DISPATCH_SOURCE_TYPE_READ, ctx->fd, 0, device->queue ); require_action( device->source, exit, err = kUnknownErr ); CFRetain( device ); dispatch_set_context( device->source, ctx ); dispatch_source_set_event_handler_f( device->source, _HIDDeviceReadHandler ); dispatch_source_set_cancel_handler_f( device->source, _HIDDeviceCancelHandler ); dispatch_resume( device->source ); ctx = NULL; #endif device->started = true; hid_dlog( kLogLevelVerbose, "HID device started\n" ); #if( HIDUTILS_HID_RAW ) exit: if( ctx ) { ForgetFD( &ctx->fd ); free( ctx ); } if( err ) { hid_ulog( kLogLevelNotice, "### HID device start failed: %#m\n", err ); if( device->eventHandler ) device->eventHandler( NULL, kHIDDeviceEventStopped, err, NULL, 0, device->eventContext ); } #endif CFRelease( device ); } //=========================================================================================================================== // HIDDeviceStop //=========================================================================================================================== static void _HIDDeviceStop( void *inContext ); void HIDDeviceStop( HIDDeviceRef inDevice ) { hid_dlog( kLogLevelVerbose, "HID device stopping...\n" ); CFRetain( inDevice ); dispatch_async_f( inDevice->queue, inDevice, _HIDDeviceStop ); } static void _HIDDeviceStop( void *inContext ) { HIDDeviceRef const device = (HIDDeviceRef) inContext; Boolean wasStarted; wasStarted = device->started; device->started = false; #if( HIDUTILS_HID_RAW ) dispatch_source_forget( &device->source ); #endif if( wasStarted ) { if( device->eventHandler ) device->eventHandler( NULL, kHIDDeviceEventStopped, kNoErr, NULL, 0, device->eventContext ); hid_dlog( kLogLevelVerbose, "HID device stopped\n" ); } CFRelease( device ); } #if( HIDUTILS_HID_RAW ) //=========================================================================================================================== // _HIDDeviceReadHandler //=========================================================================================================================== static void _HIDDeviceReadHandler( void *inContext ) { HIDDeviceContext * const ctx = (HIDDeviceContext *) inContext; HIDDeviceRef const device = ctx->device; OSStatus err; ssize_t n; n = read( ctx->fd, ctx->buf, sizeof( ctx->buf ) ); err = map_global_value_errno( n >= 0, n ); if( !err ) { if( device->eventHandler ) { device->eventHandler( device, kHIDDeviceEventReport, err, ctx->buf, (size_t) n, device->eventContext ); } } else { dispatch_source_cancel( device->source ); if( device->eventHandler ) { device->eventHandler( device, kHIDDeviceEventReport, kEndingErr, NULL, 0, device->eventContext ); } } } //=========================================================================================================================== // _HIDDeviceCancelHandler //=========================================================================================================================== static void _HIDDeviceCancelHandler( void *inContext ) { HIDDeviceContext * const ctx = (HIDDeviceContext *) inContext; OSStatus err; DEBUG_USE_ONLY( err ); err = close( ctx->fd ); err = map_global_noerr_errno( err ); check_noerr( err ); CFRelease( ctx->device ); free( ctx ); hid_dlog( kLogLevelVerbose, "HID device canceled\n" ); } #endif #if 0 #pragma mark - #pragma mark == Utils == #endif //=========================================================================================================================== // HIDCopyDevices //=========================================================================================================================== CFArrayRef HIDCopyDevices( OSStatus *outErr ) { CFArrayRef result = NULL; OSStatus err; #if( HIDUTILS_HID_RAW ) struct udev * udev; udev = udev_new(); require_action( udev, exit, err = kUnknownErr ); result = _HIDCopyDevicesWithUdev( udev, &err ); udev_unref( udev ); #else result = CFArrayCreate( NULL, NULL, 0, &kCFTypeArrayCallBacks ); require_action( result, exit, err = kNoMemoryErr ); err = kNoErr; #endif exit: if( outErr ) *outErr = err; return( result ); } #if( HIDUTILS_HID_RAW ) //=========================================================================================================================== // _HIDCopyDevicesWithUdev //=========================================================================================================================== static CFArrayRef _HIDCopyDevicesWithUdev( struct udev *inUdev, OSStatus *outErr ) { CFArrayRef result = NULL; CFMutableArrayRef array = NULL; struct udev_enumerate * enumerate = NULL; OSStatus err; struct udev_list_entry * listEntry; const char * path; struct udev_device * hidrawDevice; HIDDeviceRef hidDevice; CFTypeRef obj; array = CFArrayCreateMutable( NULL, 0, &kCFTypeArrayCallBacks ); require_action( array, exit, err = kNoMemoryErr ); enumerate = udev_enumerate_new( inUdev ); require_action( enumerate, exit, err = kUnknownErr ); err = udev_enumerate_add_match_subsystem( enumerate, "hidraw" ); require_noerr( err, exit ); err = udev_enumerate_scan_devices( enumerate ); require_noerr( err, exit ); udev_list_entry_foreach( listEntry, udev_enumerate_get_list_entry( enumerate ) ) { path = udev_list_entry_get_name( listEntry ); check( path ); if( !path ) continue; hidrawDevice = udev_device_new_from_syspath( inUdev, path ); check( hidrawDevice ); if( !hidrawDevice ) continue; err = _HIDDeviceCreateWithHIDRawDevice( &hidDevice, hidrawDevice ); udev_device_unref( hidrawDevice ); check_noerr( err ); if( err ) continue; obj = HIDDeviceCopyProperty( hidDevice, kHIDDeviceProperty_ReportDescriptor, NULL, NULL ); if( obj ) { HIDDeviceSetProperty( hidDevice, kHIDDeviceProperty_ReportDescriptor, NULL, obj ); CFRelease( obj ); } CFArrayAppendValue( array, hidDevice ); CFRelease( hidDevice ); } result = array; array = NULL; exit: CFReleaseNullSafe( array ); if( enumerate ) udev_enumerate_unref( enumerate ); if( outErr ) *outErr = err; return( result ); } #endif // HIDUTILS_HID_RAW //=========================================================================================================================== // HIDRegisterDevice //=========================================================================================================================== OSStatus HIDRegisterDevice( HIDDeviceRef inDevice ) { OSStatus err; pthread_mutex_lock( &gVirtualHIDLock ); if( !gVirtualHIDDevices ) { gVirtualHIDDevices = CFArrayCreateMutable( NULL, 0, &kCFTypeArrayCallBacks ); require_action( gVirtualHIDDevices, exit, err = kNoMemoryErr ); } CFArrayAppendValue( gVirtualHIDDevices, inDevice ); hid_ulog( kLogLevelNotice, "Registered HID %''@, %#U\n", inDevice->name, inDevice->uuid ); err = kNoErr; exit: pthread_mutex_unlock( &gVirtualHIDLock ); return( err ); } //=========================================================================================================================== // HIDDeregisterDevice //=========================================================================================================================== OSStatus HIDDeregisterDevice( HIDDeviceRef inDevice ) { CFIndex i, n; HIDDeviceRef device; pthread_mutex_lock( &gVirtualHIDLock ); n = gVirtualHIDDevices ? CFArrayGetCount( gVirtualHIDDevices ) : 0; for( i = 0; i < n; ++i ) { device = (HIDDeviceRef) CFArrayGetValueAtIndex( gVirtualHIDDevices, i ); if( device == inDevice ) { hid_ulog( kLogLevelNotice, "Deregistered HID %''@, %#U\n", inDevice->name, inDevice->uuid ); CFArrayRemoveValueAtIndex( gVirtualHIDDevices, i ); --i; --n; } } if( n == 0 ) { ForgetCF( &gVirtualHIDDevices ); } pthread_mutex_unlock( &gVirtualHIDLock ); return( kNoErr ); } //=========================================================================================================================== // HIDPostReport //=========================================================================================================================== OSStatus HIDPostReport( CFStringRef inUUID, const void *inReportPtr, size_t inReportLen ) { OSStatus err; uint8_t uuid[ 16 ]; CFIndex i, n; HIDDeviceRef device; err = CFGetUUID( inUUID, uuid ); require_noerr( err, exit ); pthread_mutex_lock( &gVirtualHIDLock ); n = gVirtualHIDDevices ? CFArrayGetCount( gVirtualHIDDevices ) : 0; for( i = 0; i < n; ++i ) { device = (HIDDeviceRef) CFArrayGetValueAtIndex( gVirtualHIDDevices, i ); if( memcmp( uuid, device->uuid, 16 ) == 0 ) { HIDDevicePostReport( device, inReportPtr, inReportLen ); break; } } pthread_mutex_unlock( &gVirtualHIDLock ); require_action_quiet( i < n, exit, err = kNotFoundErr; hid_ulog( kLogLevelNotice, "### Post HID report for %@ not found\n", inUUID ) ); exit: return( err ); } OSStatus HIDRemoveFileConfig( void ) { OSStatus err = 0; CFIndex n; pthread_mutex_lock( &gVirtualHIDLock ); n = gVirtualHIDDevices ? CFArrayGetCount( gVirtualHIDDevices ) : 0; hid_ulog( kLogLevelNotice, "HID remain num[%d]\n",n); CFArrayRemoveAllValues(gVirtualHIDDevices); gVirtualHIDDevices = NULL; pthread_mutex_unlock( &gVirtualHIDLock ); return( err ); }
32.128571
125
0.594143
[ "object" ]
4ad48a209fe15d2bcc58db6a1a18f00ffa1f8852
2,761
c
C
tests/api/test-opt-number.c
wenq1/duktape
5ed3eee19b291f3b3de0b212cc62c0aba0ab4ecb
[ "MIT" ]
4,268
2015-01-01T17:33:40.000Z
2022-03-31T17:53:31.000Z
tests/api/test-opt-number.c
GyonGyon/duktape
3f732345c745059d1d7307b17b5b8d070e9609e9
[ "MIT" ]
1,667
2015-01-01T22:43:03.000Z
2022-02-23T22:27:19.000Z
tests/api/test-opt-number.c
GyonGyon/duktape
3f732345c745059d1d7307b17b5b8d070e9609e9
[ "MIT" ]
565
2015-01-08T14:15:28.000Z
2022-03-31T16:29:31.000Z
/*=== *** test_basic (duk_safe_call) top: 14 index 0: number 123.000000, FP_NAN=0, FP_INFINITE=0, FP_ZERO=0, FP_SUBNORMAL=0, FP_NORMAL=1, signbit=0 index 1: TypeError: number required, found null (stack index 1) index 2: TypeError: number required, found true (stack index 2) index 3: TypeError: number required, found false (stack index 3) index 4: TypeError: number required, found 'foo' (stack index 4) index 5: TypeError: number required, found '123' (stack index 5) index 6: number -inf, FP_NAN=0, FP_INFINITE=1, FP_ZERO=0, FP_SUBNORMAL=0, FP_NORMAL=0, signbit=1 index 7: number -123456789.000000, FP_NAN=0, FP_INFINITE=0, FP_ZERO=0, FP_SUBNORMAL=0, FP_NORMAL=1, signbit=1 index 8: number -0.000000, FP_NAN=0, FP_INFINITE=0, FP_ZERO=1, FP_SUBNORMAL=0, FP_NORMAL=0, signbit=1 index 9: number 0.000000, FP_NAN=0, FP_INFINITE=0, FP_ZERO=1, FP_SUBNORMAL=0, FP_NORMAL=0, signbit=0 index 10: number 123456789.000000, FP_NAN=0, FP_INFINITE=0, FP_ZERO=0, FP_SUBNORMAL=0, FP_NORMAL=1, signbit=0 index 11: number inf, FP_NAN=0, FP_INFINITE=1, FP_ZERO=0, FP_SUBNORMAL=0, FP_NORMAL=0, signbit=0 index 12: number nan, FP_NAN=1, FP_INFINITE=0, FP_ZERO=0, FP_SUBNORMAL=0, FP_NORMAL=0, signbit=0 index 13: TypeError: number required, found [object Object] (stack index 13) index 14: number 123.000000, FP_NAN=0, FP_INFINITE=0, FP_ZERO=0, FP_SUBNORMAL=0, FP_NORMAL=1, signbit=0 ==> rc=0, result='undefined' ===*/ static duk_ret_t safe_helper(duk_context *ctx, void *udata) { duk_idx_t idx = (duk_idx_t) udata & 0xffffffffUL; double d = duk_opt_number(ctx, idx, 123.0); int c = fpclassify(d); (void) udata; printf("index %ld: number %lf, FP_NAN=%d, FP_INFINITE=%d, FP_ZERO=%d, FP_SUBNORMAL=%d, FP_NORMAL=%d, signbit=%d\n", (long) idx, d, (c == FP_NAN ? 1 : 0), (c == FP_INFINITE ? 1 : 0), (c == FP_ZERO ? 1 : 0), (c == FP_SUBNORMAL ? 1 : 0), (c == FP_NORMAL ? 1 : 0), (signbit(d) ? 1 : 0)); return 0; } static duk_ret_t test_basic(duk_context *ctx, void *udata) { duk_idx_t i, n; duk_int_t rc; (void) udata; duk_push_undefined(ctx); duk_push_null(ctx); duk_push_true(ctx); duk_push_false(ctx); duk_push_string(ctx, "foo"); duk_push_string(ctx, "123"); duk_push_number(ctx, -INFINITY); duk_push_number(ctx, -123456789.0); duk_push_number(ctx, -0.0); duk_push_number(ctx, +0.0); duk_push_number(ctx, +123456789.0); duk_push_number(ctx, +INFINITY); duk_push_nan(ctx); duk_push_object(ctx); n = duk_get_top(ctx); printf("top: %ld\n", (long) n); for (i = 0; i <= n; i++) { rc = duk_safe_call(ctx, safe_helper, (void *) i, 0, 1); if (rc != DUK_EXEC_SUCCESS) { printf("index %ld: %s\n", (long) i, duk_safe_to_string(ctx, -1)); } duk_pop(ctx); } return 0; } void test(duk_context *ctx) { TEST_SAFE_CALL(test_basic); }
38.887324
116
0.700471
[ "object" ]
4ae49abb7824fd8233fbd796a7dae3c022e67536
21,634
h
C
BrotGen-Pert-SSE/Compute.h
Panjaksli/BrotGen
83e62c982f0b209b2efae2b7d9019d3999c06a07
[ "MIT" ]
4
2021-06-08T06:51:00.000Z
2021-06-14T17:00:56.000Z
BrotGen-Pert-SSE/Compute.h
Panjaksli/BrotGen
83e62c982f0b209b2efae2b7d9019d3999c06a07
[ "MIT" ]
null
null
null
BrotGen-Pert-SSE/Compute.h
Panjaksli/BrotGen
83e62c982f0b209b2efae2b7d9019d3999c06a07
[ "MIT" ]
null
null
null
#ifndef COMPUTE_H_INCLUDED #define COMPUTE_H_INCLUDED #include <stdio.h> #include <stdlib.h> #include <SDL2/SDL.h> #include <math.h> #include <omp.h> #include <time.h> #include <immintrin.h> #include "Grad.h" __float128 dx[10000],dy[10000],x0,y01; float Ax,Ay,Bx,By,Cx,Cy; float A,B,C,Ai,Bi,Ci; float dxl[10000],dyl[10000]; int apnum; char setpoint=1; inline static void Screenshot(__float128 m,__float128 ph,__float128 pv,int iter, int res,__float128 mcx,__float128 mcy) { char file[30]; int height=HEIGHT*res, width=WIDTH*res; unsigned char *pixels = malloc(height*4*width),tcb,tcg,tcr; __float128 prex=(width*(-0.5)+1.0*m*ph*res),prey=(height*(-0.5)-1.0*m*pv*res); __m128 zx,zy,cx,cy,x,y,four,mask,sum; __m128 xy,tx,tx1; __m128 k,iterace,one; int off,i,j,off1,l,off2,off3,rac,bac,gac; iterace=_mm_set1_ps(iter); one=_mm_set1_ps(1.0); four= _mm_set1_ps(4.0); __float128 invert=1.0/(360*m*res); #pragma omp parallel for simd collapse (2) schedule(dynamic,100) shared(pixels,dx,dy,x0,y01,Ax,Ay,Bx,By,Cx,Cy) private(off,i,j,k,zx,zy,x,y,cy,cx,sum,mask,xy,tx,tx1,tcb,tcg,tcr) for(i=3; i<height-3; i+=3) { for(j=3; j<width-3; j+=3) { off = 4*width*i+(j<<2); off1 = 4*width*(i+1)+(j<<2); off2 = 4*width*(i+2)+(j<<2); x=cx=_mm_setr_ps(((j+prex)*invert-x0),((j+prex+2)*invert-x0),((j+prex)*invert-x0),((j+prex+2)*invert-x0)); y=cy=_mm_setr_ps(((i+prey)*invert-y01),((i+prey)*invert-y01),((i+prey+2)*invert-y01),((i+prey+2)*invert-y01)); k=_mm_setzero_ps(); l=0; rac=bac=gac=0; if(m>1e15&&apnum) { zx=_mm_mul_ps(x,x); zy=_mm_mul_ps(y,y); sum=_mm_sub_ps(zx,zy); xy=x*y; tx=Ax*x-Ay*y+Bx*(sum)-2.0f*By*xy+Cx*x*(zx-3.0f*zy)+Cy*y*(zy-3.0f*zx); y=Ax*y+Ay*x+2.0f*Bx*xy+By*(sum)+Cx*y*(3.0f*zx-zy)+Cy*x*(zx-3.0f*zy); x=tx; l=apnum; k+=(float)apnum; } do { tx=_mm_set1_ps(dxl[l]); tx1=_mm_set1_ps(dyl[l]); zx=_mm_mul_ps(x,x); zy=_mm_mul_ps(y,y); sum=_mm_add_ps(zy,zx); xy=2.0f*(y*(x+tx)+x*tx1); x=2.0f*(tx*x-tx1*y)+zx-zy+cx; y=_mm_add_ps(xy,cy); mask= _mm_cmplt_ps(sum,four); k=_mm_add_ps(k,_mm_and_ps(one,mask)); } while(++l<iter&&_mm_movemask_ps(mask)); k=_mm_div_ps(k,iterace);k*=8000.0f; bac+=tcb=pixels[off] = colb(k[0]); gac+=tcg=pixels[off+1] = colg(k[0]); rac+=tcr=pixels[off+2] = colr(k[0]); bac+=pixels[off+8] = colb(k[1]); gac+=pixels[off+9] = colg(k[1]); rac+=pixels[off+10] = colr(k[1]); bac+=pixels[off2] = colb(k[2]); gac+=pixels[off2+1] = colg(k[2]); rac+=pixels[off2+2] = colr(k[2]); bac+=pixels[off2+8] = colb(k[3]); gac+=pixels[off2+9] = colg(k[3]); rac+=pixels[off2+10] = colr(k[3]); if(tcb==pixels[off+8]&&tcb==pixels[off2]&&tcb==pixels[off2+8]&& tcg==pixels[off+9]&&tcg==pixels[off2+1]&&tcg==pixels[off2+9]&& tcr==pixels[off+10]&&tcr==pixels[off2+2]&&tcr==pixels[off2+10]) { pixels[off+4]=pixels[off1]=pixels[off1+4]=pixels[off1+8]=pixels[off2+4]=tcb; pixels[off+5]=pixels[off1+1]=pixels[off1+5]=pixels[off1+9]=pixels[off2+5]=tcg; pixels[off+6]=pixels[off1+2]=pixels[off1+6]=pixels[off1+10]=pixels[off2+6]=tcr; } else{ x=cx=_mm_setr_ps(((j+prex+1)*invert-x0),((j+prex)*invert-x0),((j+prex+2)*invert-x0),((j+prex+1)*invert-x0)); y=cy=_mm_setr_ps(((i+prey)*invert-y01),((i+prey+1)*invert-y01),((i+prey+1)*invert-y01),((i+prey+2)*invert-y01)); k=_mm_setzero_ps(); l=0; if(m>1e15&&apnum) { zx=_mm_mul_ps(x,x); zy=_mm_mul_ps(y,y); sum=_mm_sub_ps(zx,zy); xy=x*y; tx=Ax*x-Ay*y+Bx*(sum)-2.0f*By*xy+Cx*x*(zx-3.0f*zy)+Cy*y*(zy-3.0f*zx); y=Ax*y+Ay*x+2.0f*Bx*xy+By*(sum)+Cx*y*(3.0f*zx-zy)+Cy*x*(zx-3.0f*zy); x=tx; l=apnum; k+=(float)apnum; } do { tx=_mm_set1_ps(dxl[l]); tx1=_mm_set1_ps(dyl[l]); zx=_mm_mul_ps(x,x); zy=_mm_mul_ps(y,y); sum=_mm_add_ps(zy,zx); xy=2.0f*(y*(x+tx)+x*tx1); x=2.0f*(tx*x-tx1*y)+zx-zy+cx; y=_mm_add_ps(xy,cy); mask= _mm_cmplt_ps(sum,four); k=_mm_add_ps(k,_mm_and_ps(one,mask)); } while(++l<iter&&_mm_movemask_ps(mask)); k=_mm_div_ps(k,iterace);k*=8000.0f; bac+=pixels[off+4] = colb(k[0]); gac+=pixels[off+5] = colg(k[0]); rac+=pixels[off+6] = colr(k[0]); bac+=pixels[off1] = colb(k[1]); gac+=pixels[off1+1] = colg(k[1]); rac+=pixels[off1+2] = colr(k[1]); bac+=pixels[off1+8] = colb(k[2]); gac+=pixels[off1+9] = colg(k[2]); rac+=pixels[off1+10] = colr(k[2]); bac+=pixels[off2+4] = colb(k[3]); gac+=pixels[off2+5] = colg(k[3]); rac+=pixels[off2+6] = colr(k[3]); pixels[off1+4] = bac>>3; pixels[off1+5] = gac>>3; pixels[off1+6] = rac>>3; } } } SDL_Surface *surf = SDL_CreateRGBSurfaceFrom(pixels, width, height, 8*4, width*4, 0, 0, 0, 0); sprintf_s(file,30,"images/%d.bmp",time(NULL)); SDL_SaveBMP(surf,file); SDL_FreeSurface(surf); free(pixels); } ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// inline static void Render(unsigned char *pixels,__float128 m,__float128 ph,__float128 pv,int iter,__float128 mcx, __float128 mcy,char index,char index2,char index3) { __float128 prex=(m*ph-HWIDTH),prey=(-HHEIGHT-m*pv); __float128 px,py; __m128 zx,zy,cx,cy,x,y,four,mask,sum; __m128 xy,tx,tx1; __m128 k,iterace,one; iterace=_mm_set1_ps(iter); one=_mm_set1_ps(1.0f); four= _mm_set1_ps(4.0f); __float128 invert=(1.0/(360.0*m)); int off,i,j,off1,l,f,off2,off3,rac,bac,gac; unsigned char tcb,tcr,tcg; if(setpoint) { dx[0]=x0=mcx; dy[0]=y01=mcy; for(f=0; f<9999; f++) { px=dx[f]*dx[f]; py=dy[f]*dy[f]; dy[f+1]=2.0*dx[f]*dy[f]+y01; dx[f+1]=px-py+x0; } #pragma omp parallel for simd for(i=0; i<9999; i++) { dxl[i]=dx[i]; dyl[i]=dy[i]; } Ax=1.0f; Ay=Bx=By=Cx=Cy=0.0f; apnum=0; for(f=0; f<iter; f++) { C=2.0f*(dxl[f]*Cx-dyl[f]*Cy+Ax*Bx-Ay*By); Ci=2.0f*(dyl[f]*Cx+dxl[f]*Cy+Ay*Bx+Ax*By); B=2.0f*(dxl[f]*Bx-dyl[f]*By)+Ax*Ax-Ay*Ay; Bi=2.0f*(dyl[f]*Bx+dxl[f]*By+Ax*Ay); A=2.0f*(dxl[f]*Ax-dyl[f]*Ay)+1.0f; Ai=2.0f*(dyl[f]*Ax+dxl[f]*Ay); if(A>2e200||Ai>2e200||B>2e200||Bi>2e200||C>2e200||Ci>2e200)break; if(A<-2e200||Ai<-2e200||B<-2e200||Bi<-2e200||C<-2e200||Ci<-2e200)break; Cx=C; Cy=Ci; Bx=B; By=Bi; Ax=A; Ay=Ai; } apnum=f; printf("A %e %e B %e %e C %e %e Skipped: %d/%d\n",Ax,Ay,Bx,By,Cx,Cy,apnum,iter); setpoint=0; } #pragma omp parallel for simd collapse (2) schedule(dynamic,100) shared(pixels,dx,dy,x0,y01,Ax,Ay,Bx,By,Cx,Cy) private(off,i,j,k,zx,zy,x,y,cy,cx,sum,mask,xy,tx,tx1,tcb,tcg,tcr) for(i=3*index*index2+3; i<HEIGHT-3; i+=3*(1+index2)) { for(j=(index*index2+index3)*3; j<WIDTH-3; j+=3+index2*3) { if(j<3)continue; off = 4*WIDTH*i+(j<<2); off1 = 4*WIDTH*(i+1)+(j<<2); off2 = 4*WIDTH*(i+2)+(j<<2); x=cx=_mm_setr_ps(((j+prex)*invert-x0),((j+prex+2)*invert-x0),((j+prex)*invert-x0),((j+prex+2)*invert-x0)); y=cy=_mm_setr_ps(((i+prey)*invert-y01),((i+prey)*invert-y01),((i+prey+2)*invert-y01),((i+prey+2)*invert-y01)); k=_mm_setzero_ps(); l=0; rac=bac=gac=0; if(m>1e15&&apnum) { zx=_mm_mul_ps(x,x); zy=_mm_mul_ps(y,y); sum=_mm_sub_ps(zx,zy); xy=x*y; tx=Ax*x-Ay*y+Bx*(sum)-2.0f*By*xy+Cx*x*(zx-3.0f*zy)+Cy*y*(zy-3.0f*zx); y=Ax*y+Ay*x+2.0f*Bx*xy+By*(sum)+Cx*y*(3.0f*zx-zy)+Cy*x*(zx-3.0f*zy); x=tx; l=apnum; k+=(float)apnum; } do { tx=_mm_set1_ps(dxl[l]); tx1=_mm_set1_ps(dyl[l]); zx=_mm_mul_ps(x,x); zy=_mm_mul_ps(y,y); sum=_mm_add_ps(zy,zx); xy=2.0f*(y*(x+tx)+x*tx1); x=2.0f*(tx*x-tx1*y)+zx-zy+cx; y=_mm_add_ps(xy,cy); mask= _mm_cmplt_ps(sum,four); k=_mm_add_ps(k,_mm_and_ps(one,mask)); } while(++l<iter&&_mm_movemask_ps(mask)); k=_mm_div_ps(k,iterace);k*=8000.0f; bac+=tcb=pixels[off] = colb(k[0]); gac+=tcg=pixels[off+1] = colg(k[0]); rac+=tcr=pixels[off+2] = colr(k[0]); bac+=pixels[off+8] = colb(k[1]); gac+=pixels[off+9] = colg(k[1]); rac+=pixels[off+10] = colr(k[1]); bac+=pixels[off2] = colb(k[2]); gac+=pixels[off2+1] = colg(k[2]); rac+=pixels[off2+2] = colr(k[2]); bac+=pixels[off2+8] = colb(k[3]); gac+=pixels[off2+9] = colg(k[3]); rac+=pixels[off2+10] = colr(k[3]); if(tcb==pixels[off+8]&&tcb==pixels[off2]&&tcb==pixels[off2+8]&& tcg==pixels[off+9]&&tcg==pixels[off2+1]&&tcg==pixels[off2+9]&& tcr==pixels[off+10]&&tcr==pixels[off2+2]&&tcr==pixels[off2+10]) { pixels[off+4]=pixels[off1]=pixels[off1+4]=pixels[off1+8]=pixels[off2+4]=tcb; pixels[off+5]=pixels[off1+1]=pixels[off1+5]=pixels[off1+9]=pixels[off2+5]=tcg; pixels[off+6]=pixels[off1+2]=pixels[off1+6]=pixels[off1+10]=pixels[off2+6]=tcr; } else{ x=cx=_mm_setr_ps(((j+prex+1)*invert-x0),((j+prex)*invert-x0),((j+prex+2)*invert-x0),((j+prex+1)*invert-x0)); y=cy=_mm_setr_ps(((i+prey)*invert-y01),((i+prey+1)*invert-y01),((i+prey+1)*invert-y01),((i+prey+2)*invert-y01)); k=_mm_setzero_ps(); l=0; if(m>1e15&&apnum) { zx=_mm_mul_ps(x,x); zy=_mm_mul_ps(y,y); sum=_mm_sub_ps(zx,zy); xy=x*y; tx=Ax*x-Ay*y+Bx*(sum)-2.0f*By*xy+Cx*x*(zx-3.0f*zy)+Cy*y*(zy-3.0f*zx); y=Ax*y+Ay*x+2.0f*Bx*xy+By*(sum)+Cx*y*(3.0f*zx-zy)+Cy*x*(zx-3.0f*zy); x=tx; l=apnum; k+=(float)apnum; } do { tx=_mm_set1_ps(dxl[l]); tx1=_mm_set1_ps(dyl[l]); zx=_mm_mul_ps(x,x); zy=_mm_mul_ps(y,y); sum=_mm_add_ps(zy,zx); xy=2.0f*(y*(x+tx)+x*tx1); x=2.0f*(tx*x-tx1*y)+zx-zy+cx; y=_mm_add_ps(xy,cy); mask= _mm_cmplt_ps(sum,four); k=_mm_add_ps(k,_mm_and_ps(one,mask)); } while(++l<iter&&_mm_movemask_ps(mask)); k=_mm_div_ps(k,iterace);k*=8000.0f; bac+=pixels[off+4] = colb(k[0]); gac+=pixels[off+5] = colg(k[0]); rac+=pixels[off+6] = colr(k[0]); bac+=pixels[off1] = colb(k[1]); gac+=pixels[off1+1] = colg(k[1]); rac+=pixels[off1+2] = colr(k[1]); bac+=pixels[off1+8] = colb(k[2]); gac+=pixels[off1+9] = colg(k[2]); rac+=pixels[off1+10] = colr(k[2]); bac+=pixels[off2+4] = colb(k[3]); gac+=pixels[off2+5] = colg(k[3]); rac+=pixels[off2+6] = colr(k[3]); pixels[off1+4] = bac>>3; pixels[off1+5] = gac>>3; pixels[off1+6] = rac>>3; } } } //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// } inline static void RenderCol(unsigned char *pixels,__float128 m,__float128 ph,__float128 pv,int iter,__float128 mcx, __float128 mcy,char index,char index2,char index3) { __float128 prex=(m*ph-HWIDTH),prey=(-HHEIGHT-m*pv); __float128 px,py; __m128 zx,zy,cx,cy,x,y,four,mask,sum; __m128 xy,tx,tx1; __m128 k,iterace,one; iterace=_mm_set1_ps(iter); one=_mm_set1_ps(1.0f); four= _mm_set1_ps(4.0f); __float128 invert=(1.0/(360.0*m)); int off,i,j,off1,l,f,off2,off3,rac,bac,gac; unsigned char tcb,tcr,tcg; if(setpoint) { dx[0]=x0=mcx; dy[0]=y01=mcy; for(f=0; f<9999; f++) { px=dx[f]*dx[f]; py=dy[f]*dy[f]; dy[f+1]=2.0*dx[f]*dy[f]+y01; dx[f+1]=px-py+x0; } #pragma omp parallel for simd for(i=0; i<9999; i++) { dxl[i]=dx[i]; dyl[i]=dy[i]; } Ax=1.0f; Ay=Bx=By=Cx=Cy=0.0f; apnum=0; for(f=0; f<iter; f++) { C=2.0f*(dxl[f]*Cx-dyl[f]*Cy+Ax*Bx-Ay*By); Ci=2.0f*(dyl[f]*Cx+dxl[f]*Cy+Ay*Bx+Ax*By); B=2.0f*(dxl[f]*Bx-dyl[f]*By)+Ax*Ax-Ay*Ay; Bi=2.0f*(dyl[f]*Bx+dxl[f]*By+Ax*Ay); A=2.0f*(dxl[f]*Ax-dyl[f]*Ay)+1.0f; Ai=2.0f*(dyl[f]*Ax+dxl[f]*Ay); if(A>2e200||Ai>2e200||B>2e200||Bi>2e200||C>2e200||Ci>2e200)break; if(A<-2e200||Ai<-2e200||B<-2e200||Bi<-2e200||C<-2e200||Ci<-2e200)break; Cx=C; Cy=Ci; Bx=B; By=Bi; Ax=A; Ay=Ai; } apnum=f; printf("A %e %e B %e %e C %e %e Skipped: %d/%d\n",Ax,Ay,Bx,By,Cx,Cy,apnum,iter); setpoint=0; } #pragma omp parallel for simd collapse (2) schedule(dynamic,100) shared(pixels,dx,dy,x0,y01,Ax,Ay,Bx,By,Cx,Cy) private(off,i,j,k,zx,zy,x,y,cy,cx,sum,mask,xy,tx,tx1,tcb,tcg,tcr) for(i=3*index*index2+3; i<HEIGHT-3; i+=3*(1+index2)) { for(j=(index*index2+index3)*3+2*WIDTH/5-3; j<WIDTH-3; j+=3+index2*3) { if(j<2*WIDTH/5)continue; off = 4*WIDTH*i+(j<<2); off1 = 4*WIDTH*(i+1)+(j<<2); off2 = 4*WIDTH*(i+2)+(j<<2); x=cx=_mm_setr_ps(((j+prex)*invert-x0),((j+prex+2)*invert-x0),((j+prex)*invert-x0),((j+prex+2)*invert-x0)); y=cy=_mm_setr_ps(((i+prey)*invert-y01),((i+prey)*invert-y01),((i+prey+2)*invert-y01),((i+prey+2)*invert-y01)); k=_mm_setzero_ps(); l=0; rac=bac=gac=0; if(m>1e15&&apnum) { zx=_mm_mul_ps(x,x); zy=_mm_mul_ps(y,y); sum=_mm_sub_ps(zx,zy); xy=x*y; tx=Ax*x-Ay*y+Bx*(sum)-2.0f*By*xy+Cx*x*(zx-3.0f*zy)+Cy*y*(zy-3.0f*zx); y=Ax*y+Ay*x+2.0f*Bx*xy+By*(sum)+Cx*y*(3.0f*zx-zy)+Cy*x*(zx-3.0f*zy); x=tx; l=apnum; k+=(float)apnum; } do { tx=_mm_set1_ps(dxl[l]); tx1=_mm_set1_ps(dyl[l]); zx=_mm_mul_ps(x,x); zy=_mm_mul_ps(y,y); sum=_mm_add_ps(zy,zx); xy=2.0f*(y*(x+tx)+x*tx1); x=2.0f*(tx*x-tx1*y)+zx-zy+cx; y=_mm_add_ps(xy,cy); mask= _mm_cmplt_ps(sum,four); k=_mm_add_ps(k,_mm_and_ps(one,mask)); } while(++l<iter&&_mm_movemask_ps(mask)); k=_mm_div_ps(k,iterace);k*=8000.0f; bac+=tcb=pixels[off] = colb(k[0]); gac+=tcg=pixels[off+1] = colg(k[0]); rac+=tcr=pixels[off+2] = colr(k[0]); bac+=pixels[off+8] = colb(k[1]); gac+=pixels[off+9] = colg(k[1]); rac+=pixels[off+10] = colr(k[1]); bac+=pixels[off2] = colb(k[2]); gac+=pixels[off2+1] = colg(k[2]); rac+=pixels[off2+2] = colr(k[2]); bac+=pixels[off2+8] = colb(k[3]); gac+=pixels[off2+9] = colg(k[3]); rac+=pixels[off2+10] = colr(k[3]); if(tcb==pixels[off+8]&&tcb==pixels[off2]&&tcb==pixels[off2+8]&& tcg==pixels[off+9]&&tcg==pixels[off2+1]&&tcg==pixels[off2+9]&& tcr==pixels[off+10]&&tcr==pixels[off2+2]&&tcr==pixels[off2+10]) { pixels[off+4]=pixels[off1]=pixels[off1+4]=pixels[off1+8]=pixels[off2+4]=tcb; pixels[off+5]=pixels[off1+1]=pixels[off1+5]=pixels[off1+9]=pixels[off2+5]=tcg; pixels[off+6]=pixels[off1+2]=pixels[off1+6]=pixels[off1+10]=pixels[off2+6]=tcr; } else{ x=cx=_mm_setr_ps(((j+prex+1)*invert-x0),((j+prex)*invert-x0),((j+prex+2)*invert-x0),((j+prex+1)*invert-x0)); y=cy=_mm_setr_ps(((i+prey)*invert-y01),((i+prey+1)*invert-y01),((i+prey+1)*invert-y01),((i+prey+2)*invert-y01)); k=_mm_setzero_ps(); l=0; if(m>1e15&&apnum) { zx=_mm_mul_ps(x,x); zy=_mm_mul_ps(y,y); sum=_mm_sub_ps(zx,zy); xy=x*y; tx=Ax*x-Ay*y+Bx*(sum)-2.0f*By*xy+Cx*x*(zx-3.0f*zy)+Cy*y*(zy-3.0f*zx); y=Ax*y+Ay*x+2.0f*Bx*xy+By*(sum)+Cx*y*(3.0f*zx-zy)+Cy*x*(zx-3.0f*zy); x=tx; l=apnum; k+=(float)apnum; } do { tx=_mm_set1_ps(dxl[l]); tx1=_mm_set1_ps(dyl[l]); zx=_mm_mul_ps(x,x); zy=_mm_mul_ps(y,y); sum=_mm_add_ps(zy,zx); xy=2.0f*(y*(x+tx)+x*tx1); x=2.0f*(tx*x-tx1*y)+zx-zy+cx; y=_mm_add_ps(xy,cy); mask= _mm_cmplt_ps(sum,four); k=_mm_add_ps(k,_mm_and_ps(one,mask)); } while(++l<iter&&_mm_movemask_ps(mask)); k=_mm_div_ps(k,iterace);k*=8000.0f; bac+=pixels[off+4] = colb(k[0]); gac+=pixels[off+5] = colg(k[0]); rac+=pixels[off+6] = colr(k[0]); bac+=pixels[off1] = colb(k[1]); gac+=pixels[off1+1] = colg(k[1]); rac+=pixels[off1+2] = colr(k[1]); bac+=pixels[off1+8] = colb(k[2]); gac+=pixels[off1+9] = colg(k[2]); rac+=pixels[off1+10] = colr(k[2]); bac+=pixels[off2+4] = colb(k[3]); gac+=pixels[off2+5] = colg(k[3]); rac+=pixels[off2+6] = colr(k[3]); pixels[off1+4] = bac>>3; pixels[off1+5] = gac>>3; pixels[off1+6] = rac>>3; } } } //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// } #endif // COMPUTE_H_INCLUDED
44.422998
217
0.418878
[ "render" ]
4ae601859289106ce8d2c477db23f1f4967dc8b8
1,360
h
C
common/SearchPath.h
RobertCNelson/elftosb
16d0f290f6ae20c646d9cdbf4724237a416a4a18
[ "BSD-3-Clause" ]
2
2016-02-18T11:15:32.000Z
2019-06-10T20:51:28.000Z
common/SearchPath.h
eewiki/elftosb
16d0f290f6ae20c646d9cdbf4724237a416a4a18
[ "BSD-3-Clause" ]
1
2019-12-04T20:03:25.000Z
2019-12-04T22:51:51.000Z
common/SearchPath.h
eewiki/elftosb
16d0f290f6ae20c646d9cdbf4724237a416a4a18
[ "BSD-3-Clause" ]
5
2015-05-15T14:41:14.000Z
2018-11-08T14:13:33.000Z
/* * File: SearchPath.h * * Copyright (c) Freescale Semiconductor, Inc. All rights reserved. * See included license file for license details. */ #if !defined(_searchpath_h_) #define _searchpath_h_ #include <string> #include <list> /*! * \brief Handles searching a list of paths for a file. */ class PathSearcher { public: //! enum _target_type { kFindFile, kFindDirectory }; //! typedef enum _target_type target_type_t; protected: //! Global search object singleton. static PathSearcher * s_searcher; public: //! \brief Access global path searching object. static PathSearcher & getGlobalSearcher(); public: //! \brief Constructor. PathSearcher() {} //! \brief Add a new search path to the end of the list. void addSearchPath(std::string & path); //! \brief Attempts to locate a file by using the search paths. bool search(const std::string & base, target_type_t targetType, bool searchCwd, std::string & result); protected: typedef std::list<std::string> string_list_t; //!< Linked list of strings. string_list_t m_paths; //!< Ordered list of paths to search. //! \brief Returns whether \a path is absolute. bool isAbsolute(const std::string & path); //! \brief Combines two paths into a single one. std::string joinPaths(const std::string & first, const std::string & second); }; #endif // _searchpath_h_
23.050847
103
0.7125
[ "object" ]
2b8c3808e75de19336fbbb4637cf208c58bc820b
17,534
h
C
DataCollector/mozilla/xulrunner-sdk/include/nsIEditorSpellCheck.h
andrasigneczi/TravelOptimiser
b08805f97f0823fd28975a36db67193386aceb22
[ "Apache-2.0" ]
1
2016-04-20T08:35:44.000Z
2016-04-20T08:35:44.000Z
DataCollector/mozilla/xulrunner-sdk/include/nsIEditorSpellCheck.h
andrasigneczi/TravelOptimiser
b08805f97f0823fd28975a36db67193386aceb22
[ "Apache-2.0" ]
null
null
null
DataCollector/mozilla/xulrunner-sdk/include/nsIEditorSpellCheck.h
andrasigneczi/TravelOptimiser
b08805f97f0823fd28975a36db67193386aceb22
[ "Apache-2.0" ]
null
null
null
/* * DO NOT EDIT. THIS FILE IS GENERATED FROM ../../../dist/idl\nsIEditorSpellCheck.idl */ #ifndef __gen_nsIEditorSpellCheck_h__ #define __gen_nsIEditorSpellCheck_h__ #ifndef __gen_nsISupports_h__ #include "nsISupports.h" #endif /* For IDL files that don't want to include root IDL files. */ #ifndef NS_NO_VTABLE #define NS_NO_VTABLE #endif class nsIEditor; /* forward declaration */ class nsITextServicesFilter; /* forward declaration */ class nsIEditorSpellCheckCallback; /* forward declaration */ /* starting interface: nsIEditorSpellCheck */ #define NS_IEDITORSPELLCHECK_IID_STR "dd32ef3b-a7d8-43d1-9617-5f2dddbe29eb" #define NS_IEDITORSPELLCHECK_IID \ {0xdd32ef3b, 0xa7d8, 0x43d1, \ { 0x96, 0x17, 0x5f, 0x2d, 0xdd, 0xbe, 0x29, 0xeb }} class NS_NO_VTABLE nsIEditorSpellCheck : public nsISupports { public: NS_DECLARE_STATIC_IID_ACCESSOR(NS_IEDITORSPELLCHECK_IID) /* void checkCurrentDictionary (); */ NS_IMETHOD CheckCurrentDictionary(void) = 0; /* boolean canSpellCheck (); */ NS_IMETHOD CanSpellCheck(bool *_retval) = 0; /* void InitSpellChecker (in nsIEditor editor, in boolean enableSelectionChecking, [optional] in nsIEditorSpellCheckCallback callback); */ NS_IMETHOD InitSpellChecker(nsIEditor *editor, bool enableSelectionChecking, nsIEditorSpellCheckCallback *callback) = 0; /* wstring GetNextMisspelledWord (); */ NS_IMETHOD GetNextMisspelledWord(char16_t * *_retval) = 0; /* wstring GetSuggestedWord (); */ NS_IMETHOD GetSuggestedWord(char16_t * *_retval) = 0; /* boolean CheckCurrentWord (in wstring suggestedWord); */ NS_IMETHOD CheckCurrentWord(const char16_t * suggestedWord, bool *_retval) = 0; /* void ReplaceWord (in wstring misspelledWord, in wstring replaceWord, in boolean allOccurrences); */ NS_IMETHOD ReplaceWord(const char16_t * misspelledWord, const char16_t * replaceWord, bool allOccurrences) = 0; /* void IgnoreWordAllOccurrences (in wstring word); */ NS_IMETHOD IgnoreWordAllOccurrences(const char16_t * word) = 0; /* void GetPersonalDictionary (); */ NS_IMETHOD GetPersonalDictionary(void) = 0; /* wstring GetPersonalDictionaryWord (); */ NS_IMETHOD GetPersonalDictionaryWord(char16_t * *_retval) = 0; /* void AddWordToDictionary (in wstring word); */ NS_IMETHOD AddWordToDictionary(const char16_t * word) = 0; /* void RemoveWordFromDictionary (in wstring word); */ NS_IMETHOD RemoveWordFromDictionary(const char16_t * word) = 0; /* void GetDictionaryList ([array, size_is (count)] out wstring dictionaryList, out uint32_t count); */ NS_IMETHOD GetDictionaryList(char16_t * **dictionaryList, uint32_t *count) = 0; /* AString GetCurrentDictionary (); */ NS_IMETHOD GetCurrentDictionary(nsAString & _retval) = 0; /* void SetCurrentDictionary (in AString dictionary); */ NS_IMETHOD SetCurrentDictionary(const nsAString & dictionary) = 0; /* void UninitSpellChecker (); */ NS_IMETHOD UninitSpellChecker(void) = 0; /* void setFilter (in nsITextServicesFilter filter); */ NS_IMETHOD SetFilter(nsITextServicesFilter *filter) = 0; /* boolean CheckCurrentWordNoSuggest (in wstring suggestedWord); */ NS_IMETHOD CheckCurrentWordNoSuggest(const char16_t * suggestedWord, bool *_retval) = 0; /* void UpdateCurrentDictionary ([optional] in nsIEditorSpellCheckCallback callback); */ NS_IMETHOD UpdateCurrentDictionary(nsIEditorSpellCheckCallback *callback) = 0; }; NS_DEFINE_STATIC_IID_ACCESSOR(nsIEditorSpellCheck, NS_IEDITORSPELLCHECK_IID) /* Use this macro when declaring classes that implement this interface. */ #define NS_DECL_NSIEDITORSPELLCHECK \ NS_IMETHOD CheckCurrentDictionary(void) override; \ NS_IMETHOD CanSpellCheck(bool *_retval) override; \ NS_IMETHOD InitSpellChecker(nsIEditor *editor, bool enableSelectionChecking, nsIEditorSpellCheckCallback *callback) override; \ NS_IMETHOD GetNextMisspelledWord(char16_t * *_retval) override; \ NS_IMETHOD GetSuggestedWord(char16_t * *_retval) override; \ NS_IMETHOD CheckCurrentWord(const char16_t * suggestedWord, bool *_retval) override; \ NS_IMETHOD ReplaceWord(const char16_t * misspelledWord, const char16_t * replaceWord, bool allOccurrences) override; \ NS_IMETHOD IgnoreWordAllOccurrences(const char16_t * word) override; \ NS_IMETHOD GetPersonalDictionary(void) override; \ NS_IMETHOD GetPersonalDictionaryWord(char16_t * *_retval) override; \ NS_IMETHOD AddWordToDictionary(const char16_t * word) override; \ NS_IMETHOD RemoveWordFromDictionary(const char16_t * word) override; \ NS_IMETHOD GetDictionaryList(char16_t * **dictionaryList, uint32_t *count) override; \ NS_IMETHOD GetCurrentDictionary(nsAString & _retval) override; \ NS_IMETHOD SetCurrentDictionary(const nsAString & dictionary) override; \ NS_IMETHOD UninitSpellChecker(void) override; \ NS_IMETHOD SetFilter(nsITextServicesFilter *filter) override; \ NS_IMETHOD CheckCurrentWordNoSuggest(const char16_t * suggestedWord, bool *_retval) override; \ NS_IMETHOD UpdateCurrentDictionary(nsIEditorSpellCheckCallback *callback) override; /* Use this macro to declare functions that forward the behavior of this interface to another object. */ #define NS_FORWARD_NSIEDITORSPELLCHECK(_to) \ NS_IMETHOD CheckCurrentDictionary(void) override { return _to CheckCurrentDictionary(); } \ NS_IMETHOD CanSpellCheck(bool *_retval) override { return _to CanSpellCheck(_retval); } \ NS_IMETHOD InitSpellChecker(nsIEditor *editor, bool enableSelectionChecking, nsIEditorSpellCheckCallback *callback) override { return _to InitSpellChecker(editor, enableSelectionChecking, callback); } \ NS_IMETHOD GetNextMisspelledWord(char16_t * *_retval) override { return _to GetNextMisspelledWord(_retval); } \ NS_IMETHOD GetSuggestedWord(char16_t * *_retval) override { return _to GetSuggestedWord(_retval); } \ NS_IMETHOD CheckCurrentWord(const char16_t * suggestedWord, bool *_retval) override { return _to CheckCurrentWord(suggestedWord, _retval); } \ NS_IMETHOD ReplaceWord(const char16_t * misspelledWord, const char16_t * replaceWord, bool allOccurrences) override { return _to ReplaceWord(misspelledWord, replaceWord, allOccurrences); } \ NS_IMETHOD IgnoreWordAllOccurrences(const char16_t * word) override { return _to IgnoreWordAllOccurrences(word); } \ NS_IMETHOD GetPersonalDictionary(void) override { return _to GetPersonalDictionary(); } \ NS_IMETHOD GetPersonalDictionaryWord(char16_t * *_retval) override { return _to GetPersonalDictionaryWord(_retval); } \ NS_IMETHOD AddWordToDictionary(const char16_t * word) override { return _to AddWordToDictionary(word); } \ NS_IMETHOD RemoveWordFromDictionary(const char16_t * word) override { return _to RemoveWordFromDictionary(word); } \ NS_IMETHOD GetDictionaryList(char16_t * **dictionaryList, uint32_t *count) override { return _to GetDictionaryList(dictionaryList, count); } \ NS_IMETHOD GetCurrentDictionary(nsAString & _retval) override { return _to GetCurrentDictionary(_retval); } \ NS_IMETHOD SetCurrentDictionary(const nsAString & dictionary) override { return _to SetCurrentDictionary(dictionary); } \ NS_IMETHOD UninitSpellChecker(void) override { return _to UninitSpellChecker(); } \ NS_IMETHOD SetFilter(nsITextServicesFilter *filter) override { return _to SetFilter(filter); } \ NS_IMETHOD CheckCurrentWordNoSuggest(const char16_t * suggestedWord, bool *_retval) override { return _to CheckCurrentWordNoSuggest(suggestedWord, _retval); } \ NS_IMETHOD UpdateCurrentDictionary(nsIEditorSpellCheckCallback *callback) override { return _to UpdateCurrentDictionary(callback); } /* Use this macro to declare functions that forward the behavior of this interface to another object in a safe way. */ #define NS_FORWARD_SAFE_NSIEDITORSPELLCHECK(_to) \ NS_IMETHOD CheckCurrentDictionary(void) override { return !_to ? NS_ERROR_NULL_POINTER : _to->CheckCurrentDictionary(); } \ NS_IMETHOD CanSpellCheck(bool *_retval) override { return !_to ? NS_ERROR_NULL_POINTER : _to->CanSpellCheck(_retval); } \ NS_IMETHOD InitSpellChecker(nsIEditor *editor, bool enableSelectionChecking, nsIEditorSpellCheckCallback *callback) override { return !_to ? NS_ERROR_NULL_POINTER : _to->InitSpellChecker(editor, enableSelectionChecking, callback); } \ NS_IMETHOD GetNextMisspelledWord(char16_t * *_retval) override { return !_to ? NS_ERROR_NULL_POINTER : _to->GetNextMisspelledWord(_retval); } \ NS_IMETHOD GetSuggestedWord(char16_t * *_retval) override { return !_to ? NS_ERROR_NULL_POINTER : _to->GetSuggestedWord(_retval); } \ NS_IMETHOD CheckCurrentWord(const char16_t * suggestedWord, bool *_retval) override { return !_to ? NS_ERROR_NULL_POINTER : _to->CheckCurrentWord(suggestedWord, _retval); } \ NS_IMETHOD ReplaceWord(const char16_t * misspelledWord, const char16_t * replaceWord, bool allOccurrences) override { return !_to ? NS_ERROR_NULL_POINTER : _to->ReplaceWord(misspelledWord, replaceWord, allOccurrences); } \ NS_IMETHOD IgnoreWordAllOccurrences(const char16_t * word) override { return !_to ? NS_ERROR_NULL_POINTER : _to->IgnoreWordAllOccurrences(word); } \ NS_IMETHOD GetPersonalDictionary(void) override { return !_to ? NS_ERROR_NULL_POINTER : _to->GetPersonalDictionary(); } \ NS_IMETHOD GetPersonalDictionaryWord(char16_t * *_retval) override { return !_to ? NS_ERROR_NULL_POINTER : _to->GetPersonalDictionaryWord(_retval); } \ NS_IMETHOD AddWordToDictionary(const char16_t * word) override { return !_to ? NS_ERROR_NULL_POINTER : _to->AddWordToDictionary(word); } \ NS_IMETHOD RemoveWordFromDictionary(const char16_t * word) override { return !_to ? NS_ERROR_NULL_POINTER : _to->RemoveWordFromDictionary(word); } \ NS_IMETHOD GetDictionaryList(char16_t * **dictionaryList, uint32_t *count) override { return !_to ? NS_ERROR_NULL_POINTER : _to->GetDictionaryList(dictionaryList, count); } \ NS_IMETHOD GetCurrentDictionary(nsAString & _retval) override { return !_to ? NS_ERROR_NULL_POINTER : _to->GetCurrentDictionary(_retval); } \ NS_IMETHOD SetCurrentDictionary(const nsAString & dictionary) override { return !_to ? NS_ERROR_NULL_POINTER : _to->SetCurrentDictionary(dictionary); } \ NS_IMETHOD UninitSpellChecker(void) override { return !_to ? NS_ERROR_NULL_POINTER : _to->UninitSpellChecker(); } \ NS_IMETHOD SetFilter(nsITextServicesFilter *filter) override { return !_to ? NS_ERROR_NULL_POINTER : _to->SetFilter(filter); } \ NS_IMETHOD CheckCurrentWordNoSuggest(const char16_t * suggestedWord, bool *_retval) override { return !_to ? NS_ERROR_NULL_POINTER : _to->CheckCurrentWordNoSuggest(suggestedWord, _retval); } \ NS_IMETHOD UpdateCurrentDictionary(nsIEditorSpellCheckCallback *callback) override { return !_to ? NS_ERROR_NULL_POINTER : _to->UpdateCurrentDictionary(callback); } #if 0 /* Use the code below as a template for the implementation class for this interface. */ /* Header file */ class nsEditorSpellCheck : public nsIEditorSpellCheck { public: NS_DECL_ISUPPORTS NS_DECL_NSIEDITORSPELLCHECK nsEditorSpellCheck(); private: ~nsEditorSpellCheck(); protected: /* additional members */ }; /* Implementation file */ NS_IMPL_ISUPPORTS(nsEditorSpellCheck, nsIEditorSpellCheck) nsEditorSpellCheck::nsEditorSpellCheck() { /* member initializers and constructor code */ } nsEditorSpellCheck::~nsEditorSpellCheck() { /* destructor code */ } /* void checkCurrentDictionary (); */ NS_IMETHODIMP nsEditorSpellCheck::CheckCurrentDictionary() { return NS_ERROR_NOT_IMPLEMENTED; } /* boolean canSpellCheck (); */ NS_IMETHODIMP nsEditorSpellCheck::CanSpellCheck(bool *_retval) { return NS_ERROR_NOT_IMPLEMENTED; } /* void InitSpellChecker (in nsIEditor editor, in boolean enableSelectionChecking, [optional] in nsIEditorSpellCheckCallback callback); */ NS_IMETHODIMP nsEditorSpellCheck::InitSpellChecker(nsIEditor *editor, bool enableSelectionChecking, nsIEditorSpellCheckCallback *callback) { return NS_ERROR_NOT_IMPLEMENTED; } /* wstring GetNextMisspelledWord (); */ NS_IMETHODIMP nsEditorSpellCheck::GetNextMisspelledWord(char16_t * *_retval) { return NS_ERROR_NOT_IMPLEMENTED; } /* wstring GetSuggestedWord (); */ NS_IMETHODIMP nsEditorSpellCheck::GetSuggestedWord(char16_t * *_retval) { return NS_ERROR_NOT_IMPLEMENTED; } /* boolean CheckCurrentWord (in wstring suggestedWord); */ NS_IMETHODIMP nsEditorSpellCheck::CheckCurrentWord(const char16_t * suggestedWord, bool *_retval) { return NS_ERROR_NOT_IMPLEMENTED; } /* void ReplaceWord (in wstring misspelledWord, in wstring replaceWord, in boolean allOccurrences); */ NS_IMETHODIMP nsEditorSpellCheck::ReplaceWord(const char16_t * misspelledWord, const char16_t * replaceWord, bool allOccurrences) { return NS_ERROR_NOT_IMPLEMENTED; } /* void IgnoreWordAllOccurrences (in wstring word); */ NS_IMETHODIMP nsEditorSpellCheck::IgnoreWordAllOccurrences(const char16_t * word) { return NS_ERROR_NOT_IMPLEMENTED; } /* void GetPersonalDictionary (); */ NS_IMETHODIMP nsEditorSpellCheck::GetPersonalDictionary() { return NS_ERROR_NOT_IMPLEMENTED; } /* wstring GetPersonalDictionaryWord (); */ NS_IMETHODIMP nsEditorSpellCheck::GetPersonalDictionaryWord(char16_t * *_retval) { return NS_ERROR_NOT_IMPLEMENTED; } /* void AddWordToDictionary (in wstring word); */ NS_IMETHODIMP nsEditorSpellCheck::AddWordToDictionary(const char16_t * word) { return NS_ERROR_NOT_IMPLEMENTED; } /* void RemoveWordFromDictionary (in wstring word); */ NS_IMETHODIMP nsEditorSpellCheck::RemoveWordFromDictionary(const char16_t * word) { return NS_ERROR_NOT_IMPLEMENTED; } /* void GetDictionaryList ([array, size_is (count)] out wstring dictionaryList, out uint32_t count); */ NS_IMETHODIMP nsEditorSpellCheck::GetDictionaryList(char16_t * **dictionaryList, uint32_t *count) { return NS_ERROR_NOT_IMPLEMENTED; } /* AString GetCurrentDictionary (); */ NS_IMETHODIMP nsEditorSpellCheck::GetCurrentDictionary(nsAString & _retval) { return NS_ERROR_NOT_IMPLEMENTED; } /* void SetCurrentDictionary (in AString dictionary); */ NS_IMETHODIMP nsEditorSpellCheck::SetCurrentDictionary(const nsAString & dictionary) { return NS_ERROR_NOT_IMPLEMENTED; } /* void UninitSpellChecker (); */ NS_IMETHODIMP nsEditorSpellCheck::UninitSpellChecker() { return NS_ERROR_NOT_IMPLEMENTED; } /* void setFilter (in nsITextServicesFilter filter); */ NS_IMETHODIMP nsEditorSpellCheck::SetFilter(nsITextServicesFilter *filter) { return NS_ERROR_NOT_IMPLEMENTED; } /* boolean CheckCurrentWordNoSuggest (in wstring suggestedWord); */ NS_IMETHODIMP nsEditorSpellCheck::CheckCurrentWordNoSuggest(const char16_t * suggestedWord, bool *_retval) { return NS_ERROR_NOT_IMPLEMENTED; } /* void UpdateCurrentDictionary ([optional] in nsIEditorSpellCheckCallback callback); */ NS_IMETHODIMP nsEditorSpellCheck::UpdateCurrentDictionary(nsIEditorSpellCheckCallback *callback) { return NS_ERROR_NOT_IMPLEMENTED; } /* End of implementation class template. */ #endif /* starting interface: nsIEditorSpellCheckCallback */ #define NS_IEDITORSPELLCHECKCALLBACK_IID_STR "5f0a4bab-8538-4074-89d3-2f0e866a1c0b" #define NS_IEDITORSPELLCHECKCALLBACK_IID \ {0x5f0a4bab, 0x8538, 0x4074, \ { 0x89, 0xd3, 0x2f, 0x0e, 0x86, 0x6a, 0x1c, 0x0b }} class NS_NO_VTABLE nsIEditorSpellCheckCallback : public nsISupports { public: NS_DECLARE_STATIC_IID_ACCESSOR(NS_IEDITORSPELLCHECKCALLBACK_IID) /* void editorSpellCheckDone (); */ NS_IMETHOD EditorSpellCheckDone(void) = 0; }; NS_DEFINE_STATIC_IID_ACCESSOR(nsIEditorSpellCheckCallback, NS_IEDITORSPELLCHECKCALLBACK_IID) /* Use this macro when declaring classes that implement this interface. */ #define NS_DECL_NSIEDITORSPELLCHECKCALLBACK \ NS_IMETHOD EditorSpellCheckDone(void) override; /* Use this macro to declare functions that forward the behavior of this interface to another object. */ #define NS_FORWARD_NSIEDITORSPELLCHECKCALLBACK(_to) \ NS_IMETHOD EditorSpellCheckDone(void) override { return _to EditorSpellCheckDone(); } /* Use this macro to declare functions that forward the behavior of this interface to another object in a safe way. */ #define NS_FORWARD_SAFE_NSIEDITORSPELLCHECKCALLBACK(_to) \ NS_IMETHOD EditorSpellCheckDone(void) override { return !_to ? NS_ERROR_NULL_POINTER : _to->EditorSpellCheckDone(); } #if 0 /* Use the code below as a template for the implementation class for this interface. */ /* Header file */ class nsEditorSpellCheckCallback : public nsIEditorSpellCheckCallback { public: NS_DECL_ISUPPORTS NS_DECL_NSIEDITORSPELLCHECKCALLBACK nsEditorSpellCheckCallback(); private: ~nsEditorSpellCheckCallback(); protected: /* additional members */ }; /* Implementation file */ NS_IMPL_ISUPPORTS(nsEditorSpellCheckCallback, nsIEditorSpellCheckCallback) nsEditorSpellCheckCallback::nsEditorSpellCheckCallback() { /* member initializers and constructor code */ } nsEditorSpellCheckCallback::~nsEditorSpellCheckCallback() { /* destructor code */ } /* void editorSpellCheckDone (); */ NS_IMETHODIMP nsEditorSpellCheckCallback::EditorSpellCheckDone() { return NS_ERROR_NOT_IMPLEMENTED; } /* End of implementation class template. */ #endif #endif /* __gen_nsIEditorSpellCheck_h__ */
45.307494
237
0.773412
[ "object" ]
2baa19291b008ad1adcf8242edccf136ea511678
519
h
C
DigDug/TileComponent.h
keangdavidTouch/C-GameEngine
e276e7cc7c840ca41b005c0cf844cd8d5580200a
[ "MIT" ]
2
2021-03-19T13:29:36.000Z
2021-04-13T23:37:10.000Z
DigDug/TileComponent.h
keangdavidTouch/C-GameEngine
e276e7cc7c840ca41b005c0cf844cd8d5580200a
[ "MIT" ]
null
null
null
DigDug/TileComponent.h
keangdavidTouch/C-GameEngine
e276e7cc7c840ca41b005c0cf844cd8d5580200a
[ "MIT" ]
null
null
null
#pragma once #include "BaseComponent.h" #include <SDL.h> namespace kd { struct SpriteInfo; class SpriteComponent; class TileRenderComponent final : public BaseComponent { public: TileRenderComponent(const SpriteInfo& info, int cols, int rows); ~TileRenderComponent(); void Initialize() override; void Update() override; void Render() const override; private: std::vector<SDL_Rect*> m_DescRects; int m_Rows, m_Cols; SDL_Rect* m_SpriteSourceRect; std::shared_ptr<Texture2D> m_Texture; }; }
19.222222
67
0.739884
[ "render", "vector" ]
2bb13bae7d19a3efd4aec970eade8c9658021d31
3,303
h
C
include/xsheet/table.h
GeekerClub/xsheet
bc01a945a919e6974ea6f92f633063fc9fbdbf17
[ "MIT" ]
null
null
null
include/xsheet/table.h
GeekerClub/xsheet
bc01a945a919e6974ea6f92f633063fc9fbdbf17
[ "MIT" ]
null
null
null
include/xsheet/table.h
GeekerClub/xsheet
bc01a945a919e6974ea6f92f633063fc9fbdbf17
[ "MIT" ]
null
null
null
// Copyright (C) 2018, For GeekerClub authors. // Author: An Qin (anqin.qin@gmail.com) // // Description: #ifndef XSHEET_TABLE_H #define XSHEET_TABLE_H #include <stdint.h> #include <string> #include <vector> #include "error_code.h" #include "mutation.h" #include "reader.h" #include "scan.h" #include "table_descriptor.h" #pragma GCC visibility push(default) namespace xsheet { struct TableInfo { TableDescriptor* table_desc; std::string status; }; // struct TabletInfo { // std::string table_name; // std::string path; // std::string server_addr; // std::string start_key; // std::string end_key; // int64_t data_size; // std::string status; // }; class RowMutation; class RowReader; class Transaction; class Table { public: virtual const std::string GetName() = 0; virtual RowMutation* NewRowMutation(const std::string& row_key) = 0; virtual void Put(RowMutation* row_mutation) = 0; virtual void Put(const std::vector<RowMutation*>& row_mutations) = 0; virtual bool IsPutFinished() = 0; virtual bool Put(const std::string& row_key, const std::string& family, const std::string& qualifier, const std::string& value, ErrorCode* err) = 0; virtual bool Put(const std::string& row_key, const std::string& family, const std::string& qualifier, const int64_t value, ErrorCode* err) = 0; virtual bool Add(const std::string& row_key, const std::string& family, const std::string& qualifier, int64_t delta, ErrorCode* err) = 0; virtual bool PutIfAbsent(const std::string& row_key, const std::string& family, const std::string& qualifier, const std::string& value, ErrorCode* err) = 0; virtual bool Append(const std::string& row_key, const std::string& family, const std::string& qualifier, const std::string& value, ErrorCode* err) = 0; // Return a row reader handle. User should delete it when it is no longer // needed. virtual RowReader* NewRowReader(const std::string& row_key) = 0; virtual void Get(RowReader* row_reader) = 0; virtual void Get(const std::vector<RowReader*>& row_readers) = 0; virtual bool IsGetFinished() = 0; virtual bool Get(const std::string& row_key, const std::string& family, const std::string& qualifier, std::string* value, ErrorCode* err) = 0; virtual bool Get(const std::string& row_key, const std::string& family, const std::string& qualifier, int64_t* value, ErrorCode* err) = 0; // Return a result stream described by "desc". virtual ResultStream* Scan(const ScanDescriptor& desc, ErrorCode* err) = 0; // EXPERIMENTAL // Return a row transaction handle. virtual Transaction* StartRowTransaction(const std::string& row_key) = 0; // Commit a row transaction. virtual void CommitRowTransaction(Transaction* transaction) = 0; Table() {} virtual ~Table() {} private: Table(const Table&); void operator=(const Table&); }; } // namespace xsheet #pragma GCC visibility pop #endif // XSHEET_TABLE_H
33.704082
84
0.633666
[ "vector" ]
2bb1f0cf45c7e76b48f88c54b1412e0d08ebb57b
4,152
h
C
src/mongo/db/cst/bson_lexer.h
benety/mongo
203430ac9559f82ca01e3cbb3b0e09149fec0835
[ "Apache-2.0" ]
null
null
null
src/mongo/db/cst/bson_lexer.h
benety/mongo
203430ac9559f82ca01e3cbb3b0e09149fec0835
[ "Apache-2.0" ]
null
null
null
src/mongo/db/cst/bson_lexer.h
benety/mongo
203430ac9559f82ca01e3cbb3b0e09149fec0835
[ "Apache-2.0" ]
null
null
null
/** * Copyright (C) 2020-present MongoDB, Inc. * * This program is free software: you can redistribute it and/or modify * it under the terms of the Server Side Public License, version 1, * as published by MongoDB, Inc. * * 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 * Server Side Public License for more details. * * You should have received a copy of the Server Side Public License * along with this program. If not, see * <http://www.mongodb.com/licensing/server-side-public-license>. * * As a special exception, the copyright holders give permission to link the * code of portions of this program with the OpenSSL library under certain * conditions as described in each individual source file and distribute * linked combinations including the program with the OpenSSL library. You * must comply with the Server Side Public License in all respects for * all of the code used other than as permitted herein. If you modify file(s) * with this exception, you may extend this exception to your version of the * file(s), but you are not obligated to do so. If you do not wish to do so, * delete this exception statement from your version. If you delete this * exception statement from all source files in the program, then also delete * it in the license file. */ #pragma once #include <sstream> #include <string> #include <vector> #include "mongo/bson/bsonobj.h" #include "mongo/db/cst/bson_location.h" #include "mongo/db/cst/parser_gen.hpp" namespace mongo { class BSONLexer { public: BSONLexer(BSONObj obj, ParserGen::token_type startingToken); /** * Retrieves the next token in the stream. */ ParserGen::symbol_type getNext() { return _tokens[_position++]; } /** * Sorts the object that the lexer just entered (i.e., a START_OBJECT token was just emitted, * and currentPosition is now one past the start of the object), based on the enum for each of * the field name tokens. */ void sortObjTokens(); /** * Convenience for retrieving the token at the given offset. */ auto& operator[](int offset) { return _tokens[offset]; } /** * Scoped struct which pushes a location prefix for subsequently generated tokens. Pops the * prefix off the stack upon destruction. */ struct ScopedLocationTracker { ScopedLocationTracker(BSONLexer* lexer, BSONLocation::LocationPrefix prefix) : _lexer(lexer) { _lexer->_locationPrefixes.emplace_back(prefix); } ~ScopedLocationTracker() { _lexer->_locationPrefixes.pop_back(); } BSONLexer* _lexer{nullptr}; }; private: // Tokenizes the given BSONElement, traversing its children if necessary. If the field name // should not be considered, set 'includeFieldName' to false. void tokenize(BSONElement elem, bool includeFieldName); template <class LocationType, class... Args> void pushToken(LocationType name, Args&&... args) { auto token = ParserGen::symbol_type(std::forward<Args>(args)..., BSONLocation{std::move(name), _locationPrefixes}); _tokens.emplace_back(std::move(token)); _position++; } // Track the position of the input, both during construction of the list of tokens as well as // during parse. unsigned int _position = 0; // note: counter_type is only available on 3.5+ // A set of prefix strings that describe the current location in the lexer. As we walk the input // BSON, this will change depending on the context that we're parsing. std::vector<BSONLocation::LocationPrefix> _locationPrefixes; std::vector<ParserGen::symbol_type> _tokens; }; // This is the entry point for retrieving the next token from the lexer, invoked from Bison's // yyparse(). ParserGen::symbol_type yylex(mongo::BSONLexer& lexer); } // namespace mongo
36.743363
100
0.686657
[ "object", "vector" ]
2bb44fdbd3c453d211eedebe5775b53a1a45f780
907
h
C
src/HardwareTest.h
rdpeake/Wheelson-Firmware
c6df620ee6996fc24a24635ab00a8109b1879f71
[ "MIT" ]
2
2021-08-05T12:24:45.000Z
2021-10-07T18:13:43.000Z
src/HardwareTest.h
rdpeake/Wheelson-Firmware
c6df620ee6996fc24a24635ab00a8109b1879f71
[ "MIT" ]
null
null
null
src/HardwareTest.h
rdpeake/Wheelson-Firmware
c6df620ee6996fc24a24635ab00a8109b1879f71
[ "MIT" ]
1
2021-12-31T13:19:51.000Z
2021-12-31T13:19:51.000Z
#ifndef WHEELSON_FIRMWARE_HARDWARETEST_H #define WHEELSON_FIRMWARE_HARDWARETEST_H #include <Display/Display.h> #include <Util/Vector.h> #include <Input/Input.h> #include <FS.h> #include <Wheelson.h> #include <Util/Task.h> struct Test { bool (*test)(); const char* name; }; class HardwareTest { public: HardwareTest(Display& display); void start(); private: Sprite *canvas; Display *display; static HardwareTest* test; Vector<Test> tests; const char* currentTest; void log(const char* property, char* value); void log(const char* property, float value); void log(const char* property, double value); void log(const char* property, bool value); void log(const char *property, uint32_t value); void log(const char *property, String value); static bool psram(); static bool nuvotonTest(); static bool SPIFFSTest(); static bool camera(); }; #endif //WHEELSON_FIRMWARE_HARDWARETEST_H
19.717391
48
0.739802
[ "vector" ]
2bb4f78662e29f56e48f2d667327c20939483a95
4,774
h
C
gpudb/protocol/admin_show_shards.h
GPUdb/gpudb-api-cpp
cabab17bf84c56386e2d74caffaec041c2abeace
[ "MIT" ]
1
2018-07-13T17:18:02.000Z
2018-07-13T17:18:02.000Z
gpudb/protocol/admin_show_shards.h
GPUdb/gpudb-api-cpp
cabab17bf84c56386e2d74caffaec041c2abeace
[ "MIT" ]
2
2018-05-16T19:16:22.000Z
2018-05-17T20:28:06.000Z
gpudb/protocol/admin_show_shards.h
GPUdb/gpudb-api-cpp
cabab17bf84c56386e2d74caffaec041c2abeace
[ "MIT" ]
3
2018-07-13T17:18:04.000Z
2021-07-29T14:04:11.000Z
/* * This file was autogenerated by the GPUdb schema processor. * * DO NOT EDIT DIRECTLY. */ #ifndef __ADMIN_SHOW_SHARDS_H__ #define __ADMIN_SHOW_SHARDS_H__ namespace gpudb { /** * A set of input parameters for {@link * #adminShowShards(const AdminShowShardsRequest&) const}. * <p> * Show the mapping of shards to the corresponding rank and tom. The * response message contains list of 16384 (total number of shards in the * system) Rank and TOM numbers corresponding to each shard. */ struct AdminShowShardsRequest { /** * Constructs an AdminShowShardsRequest object with default parameter * values. */ AdminShowShardsRequest() : options(std::map<std::string, std::string>()) { } /** * Constructs an AdminShowShardsRequest object with the specified * parameters. * * @param[in] options_ Optional parameters. * */ AdminShowShardsRequest(const std::map<std::string, std::string>& options_): options( options_ ) { } std::map<std::string, std::string> options; }; } namespace avro { template<> struct codec_traits<gpudb::AdminShowShardsRequest> { static void encode(Encoder& e, const gpudb::AdminShowShardsRequest& v) { ::avro::encode(e, v.options); } static void decode(Decoder& d, gpudb::AdminShowShardsRequest& v) { if (::avro::ResolvingDecoder *rd = dynamic_cast< ::avro::ResolvingDecoder*>(&d)) { const std::vector<size_t> fo = rd->fieldOrder(); for (std::vector<size_t>::const_iterator it = fo.begin(); it != fo.end(); ++it) { switch (*it) { case 0: ::avro::decode(d, v.options); break; default: break; } } } else { ::avro::decode(d, v.options); } } }; } namespace gpudb { /** * A set of output parameters for {@link * #adminShowShards(const AdminShowShardsRequest&) const}. * <p> * Show the mapping of shards to the corresponding rank and tom. The * response message contains list of 16384 (total number of shards in the * system) Rank and TOM numbers corresponding to each shard. */ struct AdminShowShardsResponse { /** * Constructs an AdminShowShardsResponse object with default parameter * values. */ AdminShowShardsResponse() : version(int64_t()), rank(std::vector<int32_t>()), tom(std::vector<int32_t>()), info(std::map<std::string, std::string>()) { } int64_t version; std::vector<int32_t> rank; std::vector<int32_t> tom; std::map<std::string, std::string> info; }; } namespace avro { template<> struct codec_traits<gpudb::AdminShowShardsResponse> { static void encode(Encoder& e, const gpudb::AdminShowShardsResponse& v) { ::avro::encode(e, v.version); ::avro::encode(e, v.rank); ::avro::encode(e, v.tom); ::avro::encode(e, v.info); } static void decode(Decoder& d, gpudb::AdminShowShardsResponse& v) { if (::avro::ResolvingDecoder *rd = dynamic_cast< ::avro::ResolvingDecoder*>(&d)) { const std::vector<size_t> fo = rd->fieldOrder(); for (std::vector<size_t>::const_iterator it = fo.begin(); it != fo.end(); ++it) { switch (*it) { case 0: ::avro::decode(d, v.version); break; case 1: ::avro::decode(d, v.rank); break; case 2: ::avro::decode(d, v.tom); break; case 3: ::avro::decode(d, v.info); break; default: break; } } } else { ::avro::decode(d, v.version); ::avro::decode(d, v.rank); ::avro::decode(d, v.tom); ::avro::decode(d, v.info); } } }; } #endif
27.755814
95
0.470465
[ "object", "vector" ]
2bb604a0adfdc5d641272d7fd94bc1c03c829f02
3,892
h
C
steerlib/include/simulation/SteeringCommand.h
x-y-z/SteerSuite-CUDA
7b76c4e2cd2ddf216f4befa80ea9c91c71678719
[ "BSD-3-Clause" ]
1
2019-08-29T09:30:27.000Z
2019-08-29T09:30:27.000Z
steerlib/include/simulation/SteeringCommand.h
x-y-z/SteerSuite-CUDA
7b76c4e2cd2ddf216f4befa80ea9c91c71678719
[ "BSD-3-Clause" ]
null
null
null
steerlib/include/simulation/SteeringCommand.h
x-y-z/SteerSuite-CUDA
7b76c4e2cd2ddf216f4befa80ea9c91c71678719
[ "BSD-3-Clause" ]
null
null
null
// // Copyright (c) 2009-2010 Shawn Singh, Mubbasir Kapadia, Petros Faloutsos, Glenn Reinman // See license.txt for complete license. // #ifndef __STEERLIB_STEERING_COMMAND_H__ #define __STEERLIB_STEERING_COMMAND_H__ /// @file SteeringCommand.h /// @brief Declares the SteeringCommand class #include <vector> #include "util/Geometry.h" #include "Globals.h" #ifdef _WIN32 // on win32, there is an unfortunate conflict between exporting symbols for a // dynamic/shared library and STL code. A good document describing the problem // in detail is http://www.unknownroad.com/rtfm/VisualStudio/warningC4251.html // the "least evil" solution is just to simply ignore this warning. #pragma warning( push ) #pragma warning( disable : 4251 ) #endif namespace SteerLib { /** * @brief Helper class for representing steering decisions. * * This data structure is an abstraction of a steering decision. It can be * used as output of a steering AI algorithm. The intention is that the user * will freely modify and access the data members of this class, so everything * is declared public. * * <b> executeCommandForParticle() is not implemented yet.</b> For now, you can * assimilate the code from PPRAgent::doSteering(). * The executeCommandForParticle() function receives information about an agent * represented by an oriented point-mass, and returns the new position and * orientation of the agent following that command. * * If the agent is more complicated than a point-mass particle, this steering decision * can still be used, for example as input into an animation framework, i.e., motion * synthesis. (%SteerSuite does not currently have any motion synthesis framework, but it * may be considered in the long term). * * The data provided will be used in different ways depending on the value of steeringMode: * - If steeringMode is LOCOMOTION_MODE_COMMAND, then the user must define speed and direction * commands. There are three parts to this command: speed, direction, and scoot. * - aimForTargetSpeed is a boolean flag. If it is true, then targetSpeed will be the speed that the * agent should try to maintain. Optionally, the acceleration value may hint how fast it should try to * accelerate to maintain that speed. If aimForTargetSpeed is false, then targetSpeed is ignored, and * acceleration will be a value (in meters per second) that describes the acceleration of the agent. * - turning uses the same specification method as speed, using the aimForTargetDirection, targetDirection, * and turningAmount values. * - scoot describes an additional amount of side-to-side motion. If used properly, it allows a character to * side-step when appropriate. * - If steeringMode is LOCOMOTION_MODE_DYNAMICS, then the user must provide a force vector in * dynamicsSteeringForce. * - If steeringMode is LOCOMOTION_MODE_SPACETIMEPATH, then the user must provide the * exact path and timing information. * * * @todo * - LOCOMOTION_MODE_SPACETIMEPATH is not fully implemented yet, and should be ignored for now. * */ class STEERLIB_API SteeringCommand { public: /// See documentation of SteeringCommand class to understand the different steering modes. enum LocomotionType { LOCOMOTION_MODE_COMMAND, LOCOMOTION_MODE_DYNAMICS, LOCOMOTION_MODE_SPACETIMEPATH }; void clear(); LocomotionType steeringMode; // // command steering mode: // bool aimForTargetDirection; Util::Vector targetDirection; float turningAmount; bool aimForTargetSpeed; float targetSpeed; float acceleration; float scoot; // dynamics steering mode: Util::Vector dynamicsSteeringForce; // space-time path following mode: // not implemented yet!! }; } // namespace SteerLib #ifdef _WIN32 #pragma warning( pop ) #endif #endif
36.373832
114
0.743834
[ "geometry", "vector" ]
2bbe6e9f362942c332d16fa7cb0d6404c6f9d96d
627
h
C
Sources/Qonversion/Qonversion/Models/Protected/QNEntitlement+Protected.h
qonversion/qonversion-ios-sdk
5633f10c40e659999deda4238fd78557d9c12117
[ "MIT" ]
264
2019-10-31T15:05:06.000Z
2022-03-21T16:56:54.000Z
Sources/Qonversion/Qonversion/Models/Protected/QNEntitlement+Protected.h
qonversion/qonversion-ios-sdk
5633f10c40e659999deda4238fd78557d9c12117
[ "MIT" ]
19
2019-08-18T16:17:22.000Z
2022-02-14T09:59:57.000Z
Sources/Qonversion/Qonversion/Models/Protected/QNEntitlement+Protected.h
qonversion/qonversion-ios-sdk
5633f10c40e659999deda4238fd78557d9c12117
[ "MIT" ]
16
2020-02-05T14:37:33.000Z
2021-08-30T22:42:38.000Z
// // QNEntitlement+Protected.h // Qonversion // // Created by Surik Sarkisyan on 20.05.2021. // Copyright © 2021 Qonversion Inc. All rights reserved. // #import "QNEntitlement.h" NS_ASSUME_NONNULL_BEGIN @interface QNEntitlement (Protected) - (instancetype)initWithID:(NSString *)entitlementID userID:(NSString *)userID active:(BOOL)active startedDate:(NSDate *)startedDate expirationDate:(NSDate *)expirationDate purchases:(NSArray<QNPurchase *> *)purchases object:(NSString *)object; @end NS_ASSUME_NONNULL_END
24.115385
61
0.642743
[ "object" ]
2bc67480a2328e90ff62fff14dd94ee409ad84ed
3,503
h
C
benchmark/benchmark.h
alfishe/thread-pool-cpp
ddf4468b056c686917082f0570a7c8c926231214
[ "MIT" ]
null
null
null
benchmark/benchmark.h
alfishe/thread-pool-cpp
ddf4468b056c686917082f0570a7c8c926231214
[ "MIT" ]
null
null
null
benchmark/benchmark.h
alfishe/thread-pool-cpp
ddf4468b056c686917082f0570a7c8c926231214
[ "MIT" ]
null
null
null
#pragma once #ifndef THREAD_POOL_CPP_H #define THREAD_POOL_CPP_H #ifdef WITH_ASIO #include <asio_thread_pool.hpp> #endif #include <thread_pool.hpp> #include <iostream> #include <chrono> #include <thread> #include <vector> #include <future> #define CONCURRENCY 16 #define REPOST_COUNT 1000000 using namespace tp; struct Heavy { bool verbose; std::vector<char> resource; Heavy(bool verbose = false) : verbose(verbose), resource(100 * 1024 * 1024) { if(verbose) { std::cout << "heavy default constructor" << std::endl; } } Heavy(const Heavy& o) : verbose(o.verbose), resource(o.resource) { if(verbose) { std::cout << "heavy copy constructor" << std::endl; } } Heavy(Heavy&& o) : verbose(o.verbose), resource(std::move(o.resource)) { if(verbose) { std::cout << "heavy move constructor" << std::endl; } } Heavy& operator==(const Heavy& o) { verbose = o.verbose; resource = o.resource; if(verbose) { std::cout << "heavy copy operator" << std::endl; } return *this; } Heavy& operator==(const Heavy&& o) { verbose = o.verbose; resource = std::move(o.resource); if(verbose) { std::cout << "heavy move operator" << std::endl; } return *this; } ~Heavy() { if(verbose) { std::cout << "heavy destructor. " << (resource.size() ? "Owns resource" : "Doesn't own resource") << std::endl; } } }; struct RepostJob { // Heavy heavy; ThreadPool* thread_pool; #ifdef WITH_ASIO AsioThreadPool* asio_thread_pool; #endif volatile size_t counter; long long int begin_count; std::promise<void>* waiter; RepostJob(ThreadPool* thread_pool, std::promise<void>* waiter) : thread_pool(thread_pool) #ifdef WITH_ASIO , asio_thread_pool(0) #endif , counter(0), waiter(waiter) { begin_count = std::chrono::high_resolution_clock::now() .time_since_epoch() .count(); } #endif #ifdef WITH_ASIO RepostJob(AsioThreadPool* asio_thread_pool, std::promise<void>* waiter) : thread_pool(0), asio_thread_pool(asio_thread_pool), counter(0), waiter(waiter) { begin_count = std::chrono::high_resolution_clock::now() .time_since_epoch() .count(); } #endif void operator()() { if (++counter < REPOST_COUNT) { #ifdef WITH_ASIO if(asio_thread_pool) { asio_thread_pool->post(*this); return; } #endif if (thread_pool) { thread_pool->post(*this); return; } } else { long long int end_count = std::chrono::high_resolution_clock::now() .time_since_epoch() .count(); std::cout << "reposted " << counter << " in " << (double)(end_count - begin_count) / (double)1000000 << " ms" << std::endl; waiter->set_value(); } } };
22.746753
79
0.498144
[ "vector" ]
2bcac32750ab412ecc2943d3ad8a1453ccf537ca
13,633
h
C
src/bm_trans_probs.h
MyersResearchGroup/ATACS
d6eeec63fbc53794f0376592e7357ad08a7dddd1
[ "Apache-2.0" ]
6
2017-03-10T14:55:45.000Z
2021-09-10T10:44:21.000Z
src/bm_trans_probs.h
MyersResearchGroup/ATACS
d6eeec63fbc53794f0376592e7357ad08a7dddd1
[ "Apache-2.0" ]
77
2016-11-07T08:44:57.000Z
2018-07-11T03:19:13.000Z
src/bm_trans_probs.h
MyersResearchGroup/ATACS
d6eeec63fbc53794f0376592e7357ad08a7dddd1
[ "Apache-2.0" ]
1
2021-09-10T10:44:22.000Z
2021-09-10T10:44:22.000Z
/////////////////////////////////////////////////////////////////////////////// // @name Timed Asynchronous Circuit Optimization // @version 0.1 alpha // // (c)opyright 1998 by Eric G. Mercer // // @author Eric G. Mercer // // Permission to use, copy, modify and/or distribute, but not sell, this // software and its documentation for any purpose is hereby granted // without fee, subject to the following terms and conditions: // // 1. The above copyright notice and this permission notice must // appear in all copies of the software and related documentation. // // 2. The name of University of Utah may not be used in advertising or // publicity pertaining to distribution of the software without the // specific, prior written permission of Univsersity of Utah. // // 3. This software may not be called "Taco" if it has been modified // in any way, without the specific prior written permission of // Eric G. Mercer // // 4. THE SOFTWARE IS PROVIDED "AS-IS" AND WITHOUT WARRANTY OF ANY KIND, // EXPRESS, IMPLIED, OR OTHERWISE, INCLUDING WITHOUT LIMITATION, ANY // WARRANTY OF MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE. // // IN NO EVENT SHALL THE UNIVERSITY OF UTAH OR THE AUTHORS OF THIS // SOFTWARE BE LIABLE FOR ANY SPECIAL, INCIDENTAL, INDIRECT OR CONSEQUENTIAL // DAMAGES OF ANY KIND, OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, // DATA OR PROFITS, WHETHER OR NOT ADVISED OF THE POSSIBILITY OF DAMAGE, AND ON // ANY THEORY OF LIABILITY, ARISING OUT OF OR IN CONNECTION WITH THE USE // OR PERFORMANCE OF THIS SOFTWARE. /////////////////////////////////////////////////////////////////////////////// #ifndef __INTERNAL_BM_TRANS_PROB_H #define __INTERNAL_BM_TRANS_PROB_H #include "def.h" #include <vector> #include <list> #include "struct.h" #include "markov_types.h" #include "CPdf.h" using namespace std; ///////////////////////////////////////////////////////////////////////////// // ///////////////////////////////////////////////////////////////////////////// // find_state_zero systematically tranverses the stateADT s[] until it finds // a state that is assigned to number zero and returns the pointer to that // state. ///////////////////////////////////////////////////////////////////////////// stateADT find_state_zero( stateADT s[] ); // ///////////////////////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////////////////////// // ///////////////////////////////////////////////////////////////////////////// // clearColors traverses the state_table[] setting all color entries to the // value color. The actual location of this code is in stateasgn.c and is // not exported through the stateasgn.h interface, hence the extern statement // bringing it into this scope. ///////////////////////////////////////////////////////////////////////////// extern void clearColors( stateADT state_table[], int color ); // /////////////////////////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////////////////////// // ///////////////////////////////////////////////////////////////////////////// // find_state_zero systematically tranverses the stateADT s[] until it finds // a state that is assigned to number zero and returns the pointer to that // state. ///////////////////////////////////////////////////////////////////////////// stateADT find_state_zero( stateADT s[] ); // ///////////////////////////////////////////////////////////////////////////// /////////////////////////////////////////////////////////////////////////////// // ///////////////////////////////////////////////////////////////////////////// // The pdf_cache is used to associate event numbers with rule distributions. // Under this implementation, when a lookup is invoked on an event, the // cache searches the rule matrix until it finds the first rule associated // with the specified event number. Once the rule is located, its pdf // (ruleADT->dist) is placed in a cache, to speed up future lookups and // dist is returned to the caller. // NOTE: This enforces a single distribution for each event, irregardless of // the actual trigger signal. More advanced distributions that are based // on the trigger cannot be modeled with this structure. ///////////////////////////////////////////////////////////////////////////// class pdf_cache { protected: typedef const CPdf* CPdf_ptr; typedef vector<CPdf_ptr> CPdf_ptr_vector; CPdf_ptr_vector m_cache; // CPdf cache ruleADT** m_rules; // Rule matrix where the CPdfs are found protected: ///////////////////////////////////////////////////////////////////////////// // Searched the rule matrix on the column specified by event until it finds // the first none NORULE entry. Once this entry(rule) is located, // the function return rule->dist which is the CPdf associated with the rule. // NOTE: This returns the distribution in the first rule it finds, therefore // each unique event maps to a single distribution irregardless of the // trigger signal or causal rule. ///////////////////////////////////////////////////////////////////////////// CPdf_ptr find_pdf( const unsigned int& event ); public: ///////////////////////////////////////////////////////////////////////////// // constructor that initializes the cache to empty and directs the // rule matrix pointer to rules. ///////////////////////////////////////////////////////////////////////////// pdf_cache( const unsigned int& nevents, ruleADT** rules ); ///////////////////////////////////////////////////////////////////////////// // I wonder why I keep adding these things, since they never actually // need to contain code! ///////////////////////////////////////////////////////////////////////////// ~pdf_cache(); ///////////////////////////////////////////////////////////////////////////// // lookup checks the cache at location event and if its full returns the // cache contents. Otherwise, it goes to the rule matrix and finds 'a' CPdf // for the event, places the CPdf in the cache at the event location, and // then returns the CPdf. ///////////////////////////////////////////////////////////////////////////// CPdf_ptr lookup( const unsigned int& event ); }; // /////////////////////////////////////////////////////////////////////////////// /////////////////////////////////////////////////////////////////////////////// // ///////////////////////////////////////////////////////////////////////////// // front_queue is a container adapter for sequenced containers that models // more religiously an actual queue. This implies that this adapter provides // absolutely no method for accessing the back of the queue. The only visible // part is the front element of the queue. To use this adapter, a sequence // must support the following functions: // // size() : Returns the number of elements in the sequence // empty(): Returns true is no elements are in the sequence // front(): Returns a reference or value_type& to the first // element in the sequence ( const and non-const // versions of this ) // insert( iterator i, T ): This is necessary to add new elements to the // end of the sequence. // pop_front(): Physically removes the first element from the // sequence. // operator==(...): Returns true iff two sequences are equal // operator<(...): Returns true iff the left sequence is less // than the right sequence // ///////////////////////////////////////////////////////////////////////////// template <class T, class Sequence = list<T> > class front_queue { public: typedef typename Sequence::value_type value_type; typedef typename Sequence::size_type size_type; protected: Sequence c; // Storage class used to manage elements in the queue public: ///////////////////////////////////////////////////////////////////////////// // Returns true iff the are no elements currently in the queue ///////////////////////////////////////////////////////////////////////////// bool empty() const { return c.empty(); } ///////////////////////////////////////////////////////////////////////////// // Returns the number of elements currently in the queue ///////////////////////////////////////////////////////////////////////////// size_type size() const { return c.size(); } ///////////////////////////////////////////////////////////////////////////// // Returns a non-constant reference to the first element in the queue ///////////////////////////////////////////////////////////////////////////// value_type& front() { return c.front(); } ///////////////////////////////////////////////////////////////////////////// // returns a constant reference to the first element in the queue ///////////////////////////////////////////////////////////////////////////// const value_type& front() const { return c.front(); } ///////////////////////////////////////////////////////////////////////////// // pushes the object x onto the back of the queue ///////////////////////////////////////////////////////////////////////////// void push( const value_type& x ) { c.insert( c.end(), x ); } ///////////////////////////////////////////////////////////////////////////// // Removes the first element from the queue. I have no idea what this will // do if its run on an empty queue. It really depends on the behavior of // the class sequence and how its defined to handle a pop on an empty // sequence. ///////////////////////////////////////////////////////////////////////////// void pop() { c.pop_front(); } ///////////////////////////////////////////////////////////////////////////// // Returns true iff the 'this' queus the y are equal. Equality is defined // by the Sequence class. ///////////////////////////////////////////////////////////////////////////// inline bool operator==( const front_queue<T, Sequence>& y ) { return c == y.c; } ///////////////////////////////////////////////////////////////////////////// // Returns true iff 'this' queue is less than y. Less than is defined by the // Sequence class. ///////////////////////////////////////////////////////////////////////////// inline bool operator<( const front_queue<T, Sequence>& y) { return c < y.c; } }; // end front_queue // /////////////////////////////////////////////////////////////////////////////// /////////////////////////////////////////////////////////////////////////////// // ///////////////////////////////////////////////////////////////////////////// // I would like to replace this with a template parameter at some time, but // I only want to include the declaration of burst_mode_transition_ // probabilities in this file. Since currently the export keyword is not // supported, I cannot seperate the definition and declaration. Therefore, // I'm not going to use the template parameters, but substitute in the // typedef until the export keyword is supported. ///////////////////////////////////////////////////////////////////////////// typedef insert_iterator<matrix_type> OutputIterator; ///////////////////////////////////////////////////////////////////////////// // This function uses a burst more approximation algorithm to assign // transition probabilities to the edges in the state table states. The // rules matrix is necessary as an entry point to the distribution functions // for the events. Tolerance is used as a stepsize suggestion for all of // the numerical integrations. The actual transition probabilities are // assigned as matrix_type::value_types to the iterator out. The function // returns true if all went well, otherwise it returns false. // // The heuristic algorithm is based on synchronization points in the state // graph between successive concurrent bursts. When non-burst mode type // designs are fed into this heuristic, accuracy of the results quickly // degrades, since the algorithm must guess where synchronization points // occur. // // NOTE: This only works with TER structures! Anything TEL, all bets // are off, you get what you deserve. // // NOTE: Change the structure of the breadth first search to mark entries // as being queued, rather than as being visited. This will prevent duplicate // state entries from being pushed on the stack! ///////////////////////////////////////////////////////////////////////////// bool burst_mode_transition_probabilities( stateADT states[], ruleADT* rules[], const unsigned int& nevents, const CPdf::real_type& tolerance, OutputIterator i_out ); // /////////////////////////////////////////////////////////////////////////////// #endif // __INTERNAL_BM_TRANS_PROB_H
45.595318
79
0.468789
[ "object", "vector" ]
2bd11f2e6d95c1a92daa48f17bc787bf5d05d1b5
2,342
h
C
ess/include/tencentcloud/ess/v20201111/model/DescribeThirdPartyAuthCodeRequest.h
suluner/tencentcloud-sdk-cpp
a56c73cc3f488c4d1e10755704107bb15c5e000d
[ "Apache-2.0" ]
null
null
null
ess/include/tencentcloud/ess/v20201111/model/DescribeThirdPartyAuthCodeRequest.h
suluner/tencentcloud-sdk-cpp
a56c73cc3f488c4d1e10755704107bb15c5e000d
[ "Apache-2.0" ]
null
null
null
ess/include/tencentcloud/ess/v20201111/model/DescribeThirdPartyAuthCodeRequest.h
suluner/tencentcloud-sdk-cpp
a56c73cc3f488c4d1e10755704107bb15c5e000d
[ "Apache-2.0" ]
null
null
null
/* * Copyright (c) 2017-2019 THL A29 Limited, a Tencent company. 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. */ #ifndef TENCENTCLOUD_ESS_V20201111_MODEL_DESCRIBETHIRDPARTYAUTHCODEREQUEST_H_ #define TENCENTCLOUD_ESS_V20201111_MODEL_DESCRIBETHIRDPARTYAUTHCODEREQUEST_H_ #include <string> #include <vector> #include <map> #include <tencentcloud/core/AbstractModel.h> namespace TencentCloud { namespace Ess { namespace V20201111 { namespace Model { /** * DescribeThirdPartyAuthCode请求参数结构体 */ class DescribeThirdPartyAuthCodeRequest : public AbstractModel { public: DescribeThirdPartyAuthCodeRequest(); ~DescribeThirdPartyAuthCodeRequest() = default; std::string ToJsonString() const; /** * 获取AuthCode 值 * @return AuthCode AuthCode 值 */ std::string GetAuthCode() const; /** * 设置AuthCode 值 * @param AuthCode AuthCode 值 */ void SetAuthCode(const std::string& _authCode); /** * 判断参数 AuthCode 是否已赋值 * @return AuthCode 是否已赋值 */ bool AuthCodeHasBeenSet() const; private: /** * AuthCode 值 */ std::string m_authCode; bool m_authCodeHasBeenSet; }; } } } } #endif // !TENCENTCLOUD_ESS_V20201111_MODEL_DESCRIBETHIRDPARTYAUTHCODEREQUEST_H_
30.025641
83
0.549957
[ "vector", "model" ]
2bdc8d376694851b173daf140caf747f44903872
1,722
h
C
dev/Gems/EMotionFX/Code/EMotionFX/Source/LimitVisualization.h
horvay/lumberyardtutor
63b0681a7ed2a98d651b699984de92951721353e
[ "AML" ]
5
2018-08-17T21:05:55.000Z
2021-04-17T10:48:26.000Z
dev/Gems/EMotionFX/Code/EMotionFX/Source/LimitVisualization.h
horvay/lumberyardtutor
63b0681a7ed2a98d651b699984de92951721353e
[ "AML" ]
null
null
null
dev/Gems/EMotionFX/Code/EMotionFX/Source/LimitVisualization.h
horvay/lumberyardtutor
63b0681a7ed2a98d651b699984de92951721353e
[ "AML" ]
5
2017-12-05T16:36:00.000Z
2021-04-27T06:33:54.000Z
/* * All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or * its licensors. * * For complete copyright and license terms please see the LICENSE at the root of this * distribution (the "License"). All use of this software is governed by the License, * or, if provided, by the license below or the license accompanying this file. Do not * remove or modify any license notices. This file is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * */ #pragma once // include required headers #include "EMotionFXConfig.h" #include "BaseObject.h" #include <MCore/Source/Array.h> #include <MCore/Source/UnicodeString.h> #include <MCore/Source/Vector.h> namespace EMotionFX { class EMFX_API LimitVisualization : public BaseObject { MCORE_MEMORYOBJECTCATEGORY(LimitVisualization, EMFX_DEFAULT_ALIGNMENT, EMFX_MEMCATEGORY_VISUALIZATION_LIMITS); public: static LimitVisualization* Create(uint32 numHSegments, uint32 numVSegments); MCore::Vector3 GeneratePointOnSphere(uint32 horizontalIndex, uint32 verticalIndex); void SetFlag(uint32 horizontalIndex, uint32 verticalIndex, bool flag); bool GetFlag(uint32 horizontalIndex, uint32 verticalIndex) const; void Init(const AZ::Vector2& ellipseRadii); void Render(const MCore::Matrix& globalTM, uint32 color, float scale); private: MCore::Array<bool> mFlags; AZ::Vector2 mEllipseRadii; uint32 mNumHSegments; uint32 mNumVSegments; LimitVisualization(uint32 numHSegments, uint32 numVSegments); }; } // namespace EMotionFX
33.764706
118
0.713124
[ "render", "vector" ]
2be86bc7112d33df18355d0c6cb7c9f123282e8a
1,408
h
C
crypto_labs/sigma_ec/client.h
yerseg/mephi_projects
503321a4726dcd18714ac35d459ed6f41281346b
[ "MIT" ]
null
null
null
crypto_labs/sigma_ec/client.h
yerseg/mephi_projects
503321a4726dcd18714ac35d459ed6f41281346b
[ "MIT" ]
null
null
null
crypto_labs/sigma_ec/client.h
yerseg/mephi_projects
503321a4726dcd18714ac35d459ed6f41281346b
[ "MIT" ]
null
null
null
#ifndef __CLIENT_H__ #define __CLIENT_H__ #include <unordered_map> #include <string> #include <queue.h> #include <speck.h> namespace CryptoPP { using SecByteBlockPair = std::pair<SecByteBlock, SecByteBlock>; } using namespace CryptoPP; class Client { public: explicit Client(const std::string& clientName); void SetSignatureFriendKey(const std::string& friendName, const ByteQueue& key); void SetFriendDataForSharedSecret(const std::string& name, const SecByteBlockPair& keys); std::string GetName() const; ByteQueue GetSignaturePublicKey() const; SecByteBlockPair GetDataForSharedSecret(Client& receiver); std::vector<SecByteBlock> GetSignatureAndData(const std::string& name); void Connect(const std::vector<SecByteBlock>& data); void ComputeSharedKeys(const std::string& name); SecByteBlock SendMessage(const std::string& message); std::string ReceiveMessage(const SecByteBlock& message); private: void SetOrder(const std::string& name, bool status); const std::string m_clientName; ByteQueue m_ecdsaSK; ByteQueue m_ecdsaPK; SecByteBlock m_dhSK; SecByteBlock m_dhPK; SecByteBlock m_sharedM; SecByteBlock m_sharedE; SecByteBlock m_r; std::unordered_map<std::string, std::pair<ByteQueue, SecByteBlockPair>> m_friendKeys; std::unordered_map<std::string, bool> m_isFirstForCompute; }; #endif // __CLIENT_H__
26.566038
93
0.74929
[ "vector" ]
2bf810d1a2311e8131828b5c7566e05e770ce8bb
1,941
h
C
src/geometry/CCPACSGenericSystem.h
Mk-arc/tigl
45ace0b17008e2beab3286babe310a817fcd6578
[ "Apache-2.0" ]
171
2015-04-13T11:24:34.000Z
2022-03-26T00:56:38.000Z
src/geometry/CCPACSGenericSystem.h
Mk-arc/tigl
45ace0b17008e2beab3286babe310a817fcd6578
[ "Apache-2.0" ]
620
2015-01-20T08:34:36.000Z
2022-03-30T11:05:33.000Z
src/geometry/CCPACSGenericSystem.h
Mk-arc/tigl
45ace0b17008e2beab3286babe310a817fcd6578
[ "Apache-2.0" ]
56
2015-02-09T13:33:56.000Z
2022-03-19T04:52:51.000Z
/* * Copyright (C) 2015 German Aerospace Center (DLR/SC) * * Created: 2015-10-21 Jonas Jepsen <Jonas.Jepsen@dlr.de> * * 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. */ /** * @file * @brief Implementation of CPACS wing handling routines. */ #ifndef CCPACSGENERICSYSTEM_H #define CCPACSGENERICSYSTEM_H #include "generated/CPACSGenericSystem.h" #include "CTiglRelativelyPositionedComponent.h" namespace tigl { class CCPACSConfiguration; class CCPACSGenericSystem : public generated::CPACSGenericSystem, public CTiglRelativelyPositionedComponent { public: // Constructor TIGL_EXPORT CCPACSGenericSystem(CCPACSGenericSystems* parent, CTiglUIDManager* uidMgr); // Virtual destructor TIGL_EXPORT virtual ~CCPACSGenericSystem(); TIGL_EXPORT std::string GetDefaultedUID() const override; // Returns the parent configuration TIGL_EXPORT CCPACSConfiguration & GetConfiguration() const; // Returns the Component Type TIGL_COMPONENT_GENERICSYSTEM. TIGL_EXPORT TiglGeometricComponentType GetComponentType() const override {return TIGL_COMPONENT_GENERICSYSTEM;} TIGL_EXPORT TiglGeometricComponentIntent GetComponentIntent() const override {return TIGL_INTENT_PHYSICAL;} protected: // Build the shape of the system PNamedShape BuildLoft() const override; private: // get short name for loft std::string GetShortShapeName() const; }; } // end namespace tigl #endif // CCPACSGENERICSYSTEM_H
30.328125
115
0.773313
[ "shape" ]
2bf8dbc14fbc01d61ed9567b7e5a002b589a8cef
4,387
h
C
kern/arch/x86/arch.h
7perl/akaros
19eb5f42223afd2be2968fef4dd50b940045ac90
[ "LPL-1.02" ]
1
2022-01-10T23:42:13.000Z
2022-01-10T23:42:13.000Z
kern/arch/x86/arch.h
7perl/akaros
19eb5f42223afd2be2968fef4dd50b940045ac90
[ "LPL-1.02" ]
null
null
null
kern/arch/x86/arch.h
7perl/akaros
19eb5f42223afd2be2968fef4dd50b940045ac90
[ "LPL-1.02" ]
null
null
null
#ifndef ROS_INC_ARCH_H #define ROS_INC_ARCH_H #include <ros/arch/arch.h> #include <ros/common.h> #include <arch/x86.h> /* Arch Constants */ #define ARCH_CL_SIZE 64 #define __always_inline __attribute__((always_inline)) static inline void breakpoint(void) __attribute__((always_inline)); static inline void invlpg(void *addr) __attribute__((always_inline)); static inline void tlbflush(void) __attribute__((always_inline)); static inline void icache_flush_page(void *va, void *kva) __attribute__((always_inline)); static inline uint64_t read_tsc(void) __attribute__((always_inline)); static inline uint64_t read_tscp(void) __attribute__((always_inline)); static inline uint64_t read_tsc_serialized(void) __attribute__((always_inline)); static inline void enable_irq(void) __attribute__((always_inline)); static inline void disable_irq(void) __attribute__((always_inline)); static inline void enable_irqsave(int8_t *state) __attribute__((always_inline)); static inline void disable_irqsave(int8_t *state) __attribute__((always_inline)); static inline void cpu_relax(void) __attribute__((always_inline)); static inline void cpu_halt(void) __attribute__((always_inline)); static inline void clflush(uintptr_t* addr) __attribute__((always_inline)); static inline int irq_is_enabled(void) __attribute__((always_inline)); static inline void cache_flush(void) __attribute__((always_inline)); static inline void reboot(void) __attribute__((always_inline)) __attribute__((noreturn)); /* in trap.c */ void send_ipi(uint32_t os_coreid, uint8_t vector); /* in cpuinfo.c */ void print_cpuinfo(void); void show_mapping(pde_t *pgdir, uintptr_t start, size_t size); int vendor_id(char *); static inline void breakpoint(void) { asm volatile("int3"); } static inline void invlpg(void *addr) { asm volatile("invlpg (%0)" : : "r" (addr) : "memory"); } static inline void tlbflush(void) { unsigned long cr3; asm volatile("mov %%cr3,%0" : "=r" (cr3)); asm volatile("mov %0,%%cr3" : : "r" (cr3)); } static inline void icache_flush_page(void *va, void *kva) { // x86 handles self-modifying code (mostly) without SW support } static inline uint64_t read_tsc(void) { uint32_t edx, eax; asm volatile("rdtsc" : "=d"(edx), "=a"(eax)); return (uint64_t)edx << 32 | eax; } /* non-core-id reporting style (it is in ecx) */ static inline uint64_t read_tscp(void) { uint32_t edx, eax; asm volatile("rdtscp" : "=d"(edx), "=a"(eax) : : X86_REG_CX); return (uint64_t)edx << 32 | eax; } /* Check out k/a/x86/rdtsc_test.c for more info */ static inline uint64_t read_tsc_serialized(void) { asm volatile("lfence" ::: "memory"); /* mfence on amd? */ return read_tsc(); } static inline void enable_irq(void) { asm volatile("sti"); } static inline void disable_irq(void) { asm volatile("cli"); } static inline void enable_irqsave(int8_t *state) { // *state tracks the number of nested enables and disables // initial value of state: 0 = first run / no favorite // > 0 means more enabled calls have been made // < 0 means more disabled calls have been made // Mostly doing this so we can call disable_irqsave first if we want // one side or another "gets a point" if interrupts were already the // way it wanted to go. o/w, state stays at 0. if the state was not 0 // then, enabling/disabling isn't even an option. just increment/decrement // if enabling is winning or tied, make sure it's enabled if ((*state == 0) && !irq_is_enabled()) enable_irq(); else (*state)++; } static inline void disable_irqsave(int8_t *state) { if ((*state == 0) && irq_is_enabled()) disable_irq(); else (*state)--; } static inline void cpu_relax(void) { __cpu_relax(); } /* This doesn't atomically enable interrupts and then halt, like we want, so * x86 needs to use a custom helper in the irq handler in trap.c. */ static inline void cpu_halt(void) { asm volatile("sti; hlt" : : : "memory"); } static inline void clflush(uintptr_t* addr) { asm volatile("clflush %0" : : "m"(*addr)); } static inline int irq_is_enabled(void) { return read_flags() & FL_IF; } static inline void cache_flush(void) { wbinvd(); } static inline void reboot(void) { uint8_t cf9 = inb(0xcf9) & ~6; outb(0x92, 0x3); outb(0xcf9, cf9 | 2); outb(0xcf9, cf9 | 6); asm volatile ("mov $0, %"X86_REG_SP"; int $0"); while (1); } #endif /* !ROS_INC_ARCH_H */
27.591195
80
0.715067
[ "vector" ]
6000078ce8f9c6529c04a35a8dff3f86d5404123
2,064
h
C
rdbModel/Db/MysqlResults.h
fermi-lat/rdbModel
b7d0846a2736ff2fb202f4c0c6c50c4f4467ded9
[ "BSD-3-Clause" ]
null
null
null
rdbModel/Db/MysqlResults.h
fermi-lat/rdbModel
b7d0846a2736ff2fb202f4c0c6c50c4f4467ded9
[ "BSD-3-Clause" ]
null
null
null
rdbModel/Db/MysqlResults.h
fermi-lat/rdbModel
b7d0846a2736ff2fb202f4c0c6c50c4f4467ded9
[ "BSD-3-Clause" ]
null
null
null
// $Header: /nfs/slac/g/glast/ground/cvs/rdbModel/rdbModel/Db/MysqlResults.h,v 1.4 2004/04/07 23:06:48 jrb Exp $ #ifndef RDBMODEL_MYSQLRESULTS_H #define RDBMODEL_MYSQLRESULTS_H #include "rdbModel/Db/ResultHandle.h" typedef struct st_mysql_res MYSQL_RES; namespace rdbModel{ class MysqlConnection; /** Concrete implementation of ResultHandle, to accompany MysqlConnection. */ class MysqlResults : virtual public ResultHandle { friend class MysqlConnection; public: virtual ~MysqlResults(); /// Return number of rows in results virtual unsigned int getNRows() const; /** Get array of field values for ith row of result set */ virtual bool getRow(std::vector<std::string>& fields, unsigned int i = 0, bool clear = true); /** Get array of field values for ith row of result set. If a field value is NULL, return a zero ptr for that element of the array. --> It is the responsibility of the caller to delete the strings containing the field values. See service cleanFieldPtrs in base class ResultHandle. */ virtual bool getRowPtrs(std::vector<std::string*>& fieldPtrs, unsigned int i = 0, bool clear=true); /* // Return specified row in results as a string virtual bool getRowString(std::string& row, unsigned int iRow=0) const; Return vector of rows @param rows to hold returned data @param iRow starting row @param maxRow maximum number of rows requested. 0 means "all" @param clear if true, clear @a rows before storing new data @return status virtual bool getRowStrings(std::vector<std::string>& rows, unsigned int iRow=0, unsigned int maxRow=0, bool clear=true) const; */ private: // Only MysqlConnection calls constructor MysqlResults(MYSQL_RES* results = 0); MYSQL_RES* m_myres; }; } #endif
31.272727
112
0.633721
[ "vector" ]
600867b2e40767b4037305c35252db828952e639
18,538
h
C
extensions/third_party/perfetto/protos/perfetto/trace/ftrace/i2c.gen.h
blockspacer/chromium_base_conan
b4749433cf34f54d2edff52e2f0465fec8cb9bad
[ "Apache-2.0", "BSD-3-Clause" ]
6
2020-12-22T05:48:31.000Z
2022-02-08T19:49:49.000Z
extensions/third_party/perfetto/protos/perfetto/trace/ftrace/i2c.gen.h
blockspacer/chromium_base_conan
b4749433cf34f54d2edff52e2f0465fec8cb9bad
[ "Apache-2.0", "BSD-3-Clause" ]
4
2020-05-22T18:36:43.000Z
2021-05-19T10:20:23.000Z
extensions/third_party/perfetto/protos/perfetto/trace/ftrace/i2c.gen.h
blockspacer/chromium_base_conan
b4749433cf34f54d2edff52e2f0465fec8cb9bad
[ "Apache-2.0", "BSD-3-Clause" ]
2
2019-12-06T11:48:16.000Z
2021-09-16T04:44:47.000Z
// DO NOT EDIT. Autogenerated by Perfetto cppgen_plugin #ifndef PERFETTO_PROTOS_PROTOS_PERFETTO_TRACE_FTRACE_I2C_PROTO_CPP_H_ #define PERFETTO_PROTOS_PROTOS_PERFETTO_TRACE_FTRACE_I2C_PROTO_CPP_H_ #include <stdint.h> #include <bitset> #include <vector> #include <string> #include <type_traits> #include "perfetto/protozero/cpp_message_obj.h" #include "perfetto/protozero/copyable_ptr.h" #include "perfetto/base/export.h" namespace perfetto { namespace protos { namespace gen { class SmbusReplyFtraceEvent; class SmbusResultFtraceEvent; class SmbusWriteFtraceEvent; class SmbusReadFtraceEvent; class I2cReplyFtraceEvent; class I2cResultFtraceEvent; class I2cWriteFtraceEvent; class I2cReadFtraceEvent; } // namespace perfetto } // namespace protos } // namespace gen namespace protozero { class Message; } // namespace protozero namespace perfetto { namespace protos { namespace gen { class PERFETTO_EXPORT SmbusReplyFtraceEvent : public ::protozero::CppMessageObj { public: enum FieldNumbers { kAdapterNrFieldNumber = 1, kAddrFieldNumber = 2, kFlagsFieldNumber = 3, kCommandFieldNumber = 4, kLenFieldNumber = 5, kProtocolFieldNumber = 6, }; SmbusReplyFtraceEvent(); ~SmbusReplyFtraceEvent() override; SmbusReplyFtraceEvent(SmbusReplyFtraceEvent&&) noexcept; SmbusReplyFtraceEvent& operator=(SmbusReplyFtraceEvent&&); SmbusReplyFtraceEvent(const SmbusReplyFtraceEvent&); SmbusReplyFtraceEvent& operator=(const SmbusReplyFtraceEvent&); bool operator==(const SmbusReplyFtraceEvent&) const; bool operator!=(const SmbusReplyFtraceEvent& other) const { return !(*this == other); } bool ParseFromArray(const void*, size_t) override; std::string SerializeAsString() const override; std::vector<uint8_t> SerializeAsArray() const override; void Serialize(::protozero::Message*) const; bool has_adapter_nr() const { return _has_field_[1]; } int32_t adapter_nr() const { return adapter_nr_; } void set_adapter_nr(int32_t value) { adapter_nr_ = value; _has_field_.set(1); } bool has_addr() const { return _has_field_[2]; } uint32_t addr() const { return addr_; } void set_addr(uint32_t value) { addr_ = value; _has_field_.set(2); } bool has_flags() const { return _has_field_[3]; } uint32_t flags() const { return flags_; } void set_flags(uint32_t value) { flags_ = value; _has_field_.set(3); } bool has_command() const { return _has_field_[4]; } uint32_t command() const { return command_; } void set_command(uint32_t value) { command_ = value; _has_field_.set(4); } bool has_len() const { return _has_field_[5]; } uint32_t len() const { return len_; } void set_len(uint32_t value) { len_ = value; _has_field_.set(5); } bool has_protocol() const { return _has_field_[6]; } uint32_t protocol() const { return protocol_; } void set_protocol(uint32_t value) { protocol_ = value; _has_field_.set(6); } private: int32_t adapter_nr_{}; uint32_t addr_{}; uint32_t flags_{}; uint32_t command_{}; uint32_t len_{}; uint32_t protocol_{}; // Allows to preserve unknown protobuf fields for compatibility // with future versions of .proto files. std::string unknown_fields_; std::bitset<7> _has_field_{}; }; class PERFETTO_EXPORT SmbusResultFtraceEvent : public ::protozero::CppMessageObj { public: enum FieldNumbers { kAdapterNrFieldNumber = 1, kAddrFieldNumber = 2, kFlagsFieldNumber = 3, kReadWriteFieldNumber = 4, kCommandFieldNumber = 5, kResFieldNumber = 6, kProtocolFieldNumber = 7, }; SmbusResultFtraceEvent(); ~SmbusResultFtraceEvent() override; SmbusResultFtraceEvent(SmbusResultFtraceEvent&&) noexcept; SmbusResultFtraceEvent& operator=(SmbusResultFtraceEvent&&); SmbusResultFtraceEvent(const SmbusResultFtraceEvent&); SmbusResultFtraceEvent& operator=(const SmbusResultFtraceEvent&); bool operator==(const SmbusResultFtraceEvent&) const; bool operator!=(const SmbusResultFtraceEvent& other) const { return !(*this == other); } bool ParseFromArray(const void*, size_t) override; std::string SerializeAsString() const override; std::vector<uint8_t> SerializeAsArray() const override; void Serialize(::protozero::Message*) const; bool has_adapter_nr() const { return _has_field_[1]; } int32_t adapter_nr() const { return adapter_nr_; } void set_adapter_nr(int32_t value) { adapter_nr_ = value; _has_field_.set(1); } bool has_addr() const { return _has_field_[2]; } uint32_t addr() const { return addr_; } void set_addr(uint32_t value) { addr_ = value; _has_field_.set(2); } bool has_flags() const { return _has_field_[3]; } uint32_t flags() const { return flags_; } void set_flags(uint32_t value) { flags_ = value; _has_field_.set(3); } bool has_read_write() const { return _has_field_[4]; } uint32_t read_write() const { return read_write_; } void set_read_write(uint32_t value) { read_write_ = value; _has_field_.set(4); } bool has_command() const { return _has_field_[5]; } uint32_t command() const { return command_; } void set_command(uint32_t value) { command_ = value; _has_field_.set(5); } bool has_res() const { return _has_field_[6]; } int32_t res() const { return res_; } void set_res(int32_t value) { res_ = value; _has_field_.set(6); } bool has_protocol() const { return _has_field_[7]; } uint32_t protocol() const { return protocol_; } void set_protocol(uint32_t value) { protocol_ = value; _has_field_.set(7); } private: int32_t adapter_nr_{}; uint32_t addr_{}; uint32_t flags_{}; uint32_t read_write_{}; uint32_t command_{}; int32_t res_{}; uint32_t protocol_{}; // Allows to preserve unknown protobuf fields for compatibility // with future versions of .proto files. std::string unknown_fields_; std::bitset<8> _has_field_{}; }; class PERFETTO_EXPORT SmbusWriteFtraceEvent : public ::protozero::CppMessageObj { public: enum FieldNumbers { kAdapterNrFieldNumber = 1, kAddrFieldNumber = 2, kFlagsFieldNumber = 3, kCommandFieldNumber = 4, kLenFieldNumber = 5, kProtocolFieldNumber = 6, }; SmbusWriteFtraceEvent(); ~SmbusWriteFtraceEvent() override; SmbusWriteFtraceEvent(SmbusWriteFtraceEvent&&) noexcept; SmbusWriteFtraceEvent& operator=(SmbusWriteFtraceEvent&&); SmbusWriteFtraceEvent(const SmbusWriteFtraceEvent&); SmbusWriteFtraceEvent& operator=(const SmbusWriteFtraceEvent&); bool operator==(const SmbusWriteFtraceEvent&) const; bool operator!=(const SmbusWriteFtraceEvent& other) const { return !(*this == other); } bool ParseFromArray(const void*, size_t) override; std::string SerializeAsString() const override; std::vector<uint8_t> SerializeAsArray() const override; void Serialize(::protozero::Message*) const; bool has_adapter_nr() const { return _has_field_[1]; } int32_t adapter_nr() const { return adapter_nr_; } void set_adapter_nr(int32_t value) { adapter_nr_ = value; _has_field_.set(1); } bool has_addr() const { return _has_field_[2]; } uint32_t addr() const { return addr_; } void set_addr(uint32_t value) { addr_ = value; _has_field_.set(2); } bool has_flags() const { return _has_field_[3]; } uint32_t flags() const { return flags_; } void set_flags(uint32_t value) { flags_ = value; _has_field_.set(3); } bool has_command() const { return _has_field_[4]; } uint32_t command() const { return command_; } void set_command(uint32_t value) { command_ = value; _has_field_.set(4); } bool has_len() const { return _has_field_[5]; } uint32_t len() const { return len_; } void set_len(uint32_t value) { len_ = value; _has_field_.set(5); } bool has_protocol() const { return _has_field_[6]; } uint32_t protocol() const { return protocol_; } void set_protocol(uint32_t value) { protocol_ = value; _has_field_.set(6); } private: int32_t adapter_nr_{}; uint32_t addr_{}; uint32_t flags_{}; uint32_t command_{}; uint32_t len_{}; uint32_t protocol_{}; // Allows to preserve unknown protobuf fields for compatibility // with future versions of .proto files. std::string unknown_fields_; std::bitset<7> _has_field_{}; }; class PERFETTO_EXPORT SmbusReadFtraceEvent : public ::protozero::CppMessageObj { public: enum FieldNumbers { kAdapterNrFieldNumber = 1, kFlagsFieldNumber = 2, kAddrFieldNumber = 3, kCommandFieldNumber = 4, kProtocolFieldNumber = 5, }; SmbusReadFtraceEvent(); ~SmbusReadFtraceEvent() override; SmbusReadFtraceEvent(SmbusReadFtraceEvent&&) noexcept; SmbusReadFtraceEvent& operator=(SmbusReadFtraceEvent&&); SmbusReadFtraceEvent(const SmbusReadFtraceEvent&); SmbusReadFtraceEvent& operator=(const SmbusReadFtraceEvent&); bool operator==(const SmbusReadFtraceEvent&) const; bool operator!=(const SmbusReadFtraceEvent& other) const { return !(*this == other); } bool ParseFromArray(const void*, size_t) override; std::string SerializeAsString() const override; std::vector<uint8_t> SerializeAsArray() const override; void Serialize(::protozero::Message*) const; bool has_adapter_nr() const { return _has_field_[1]; } int32_t adapter_nr() const { return adapter_nr_; } void set_adapter_nr(int32_t value) { adapter_nr_ = value; _has_field_.set(1); } bool has_flags() const { return _has_field_[2]; } uint32_t flags() const { return flags_; } void set_flags(uint32_t value) { flags_ = value; _has_field_.set(2); } bool has_addr() const { return _has_field_[3]; } uint32_t addr() const { return addr_; } void set_addr(uint32_t value) { addr_ = value; _has_field_.set(3); } bool has_command() const { return _has_field_[4]; } uint32_t command() const { return command_; } void set_command(uint32_t value) { command_ = value; _has_field_.set(4); } bool has_protocol() const { return _has_field_[5]; } uint32_t protocol() const { return protocol_; } void set_protocol(uint32_t value) { protocol_ = value; _has_field_.set(5); } private: int32_t adapter_nr_{}; uint32_t flags_{}; uint32_t addr_{}; uint32_t command_{}; uint32_t protocol_{}; // Allows to preserve unknown protobuf fields for compatibility // with future versions of .proto files. std::string unknown_fields_; std::bitset<6> _has_field_{}; }; class PERFETTO_EXPORT I2cReplyFtraceEvent : public ::protozero::CppMessageObj { public: enum FieldNumbers { kAdapterNrFieldNumber = 1, kMsgNrFieldNumber = 2, kAddrFieldNumber = 3, kFlagsFieldNumber = 4, kLenFieldNumber = 5, kBufFieldNumber = 6, }; I2cReplyFtraceEvent(); ~I2cReplyFtraceEvent() override; I2cReplyFtraceEvent(I2cReplyFtraceEvent&&) noexcept; I2cReplyFtraceEvent& operator=(I2cReplyFtraceEvent&&); I2cReplyFtraceEvent(const I2cReplyFtraceEvent&); I2cReplyFtraceEvent& operator=(const I2cReplyFtraceEvent&); bool operator==(const I2cReplyFtraceEvent&) const; bool operator!=(const I2cReplyFtraceEvent& other) const { return !(*this == other); } bool ParseFromArray(const void*, size_t) override; std::string SerializeAsString() const override; std::vector<uint8_t> SerializeAsArray() const override; void Serialize(::protozero::Message*) const; bool has_adapter_nr() const { return _has_field_[1]; } int32_t adapter_nr() const { return adapter_nr_; } void set_adapter_nr(int32_t value) { adapter_nr_ = value; _has_field_.set(1); } bool has_msg_nr() const { return _has_field_[2]; } uint32_t msg_nr() const { return msg_nr_; } void set_msg_nr(uint32_t value) { msg_nr_ = value; _has_field_.set(2); } bool has_addr() const { return _has_field_[3]; } uint32_t addr() const { return addr_; } void set_addr(uint32_t value) { addr_ = value; _has_field_.set(3); } bool has_flags() const { return _has_field_[4]; } uint32_t flags() const { return flags_; } void set_flags(uint32_t value) { flags_ = value; _has_field_.set(4); } bool has_len() const { return _has_field_[5]; } uint32_t len() const { return len_; } void set_len(uint32_t value) { len_ = value; _has_field_.set(5); } bool has_buf() const { return _has_field_[6]; } uint32_t buf() const { return buf_; } void set_buf(uint32_t value) { buf_ = value; _has_field_.set(6); } private: int32_t adapter_nr_{}; uint32_t msg_nr_{}; uint32_t addr_{}; uint32_t flags_{}; uint32_t len_{}; uint32_t buf_{}; // Allows to preserve unknown protobuf fields for compatibility // with future versions of .proto files. std::string unknown_fields_; std::bitset<7> _has_field_{}; }; class PERFETTO_EXPORT I2cResultFtraceEvent : public ::protozero::CppMessageObj { public: enum FieldNumbers { kAdapterNrFieldNumber = 1, kNrMsgsFieldNumber = 2, kRetFieldNumber = 3, }; I2cResultFtraceEvent(); ~I2cResultFtraceEvent() override; I2cResultFtraceEvent(I2cResultFtraceEvent&&) noexcept; I2cResultFtraceEvent& operator=(I2cResultFtraceEvent&&); I2cResultFtraceEvent(const I2cResultFtraceEvent&); I2cResultFtraceEvent& operator=(const I2cResultFtraceEvent&); bool operator==(const I2cResultFtraceEvent&) const; bool operator!=(const I2cResultFtraceEvent& other) const { return !(*this == other); } bool ParseFromArray(const void*, size_t) override; std::string SerializeAsString() const override; std::vector<uint8_t> SerializeAsArray() const override; void Serialize(::protozero::Message*) const; bool has_adapter_nr() const { return _has_field_[1]; } int32_t adapter_nr() const { return adapter_nr_; } void set_adapter_nr(int32_t value) { adapter_nr_ = value; _has_field_.set(1); } bool has_nr_msgs() const { return _has_field_[2]; } uint32_t nr_msgs() const { return nr_msgs_; } void set_nr_msgs(uint32_t value) { nr_msgs_ = value; _has_field_.set(2); } bool has_ret() const { return _has_field_[3]; } int32_t ret() const { return ret_; } void set_ret(int32_t value) { ret_ = value; _has_field_.set(3); } private: int32_t adapter_nr_{}; uint32_t nr_msgs_{}; int32_t ret_{}; // Allows to preserve unknown protobuf fields for compatibility // with future versions of .proto files. std::string unknown_fields_; std::bitset<4> _has_field_{}; }; class PERFETTO_EXPORT I2cWriteFtraceEvent : public ::protozero::CppMessageObj { public: enum FieldNumbers { kAdapterNrFieldNumber = 1, kMsgNrFieldNumber = 2, kAddrFieldNumber = 3, kFlagsFieldNumber = 4, kLenFieldNumber = 5, kBufFieldNumber = 6, }; I2cWriteFtraceEvent(); ~I2cWriteFtraceEvent() override; I2cWriteFtraceEvent(I2cWriteFtraceEvent&&) noexcept; I2cWriteFtraceEvent& operator=(I2cWriteFtraceEvent&&); I2cWriteFtraceEvent(const I2cWriteFtraceEvent&); I2cWriteFtraceEvent& operator=(const I2cWriteFtraceEvent&); bool operator==(const I2cWriteFtraceEvent&) const; bool operator!=(const I2cWriteFtraceEvent& other) const { return !(*this == other); } bool ParseFromArray(const void*, size_t) override; std::string SerializeAsString() const override; std::vector<uint8_t> SerializeAsArray() const override; void Serialize(::protozero::Message*) const; bool has_adapter_nr() const { return _has_field_[1]; } int32_t adapter_nr() const { return adapter_nr_; } void set_adapter_nr(int32_t value) { adapter_nr_ = value; _has_field_.set(1); } bool has_msg_nr() const { return _has_field_[2]; } uint32_t msg_nr() const { return msg_nr_; } void set_msg_nr(uint32_t value) { msg_nr_ = value; _has_field_.set(2); } bool has_addr() const { return _has_field_[3]; } uint32_t addr() const { return addr_; } void set_addr(uint32_t value) { addr_ = value; _has_field_.set(3); } bool has_flags() const { return _has_field_[4]; } uint32_t flags() const { return flags_; } void set_flags(uint32_t value) { flags_ = value; _has_field_.set(4); } bool has_len() const { return _has_field_[5]; } uint32_t len() const { return len_; } void set_len(uint32_t value) { len_ = value; _has_field_.set(5); } bool has_buf() const { return _has_field_[6]; } uint32_t buf() const { return buf_; } void set_buf(uint32_t value) { buf_ = value; _has_field_.set(6); } private: int32_t adapter_nr_{}; uint32_t msg_nr_{}; uint32_t addr_{}; uint32_t flags_{}; uint32_t len_{}; uint32_t buf_{}; // Allows to preserve unknown protobuf fields for compatibility // with future versions of .proto files. std::string unknown_fields_; std::bitset<7> _has_field_{}; }; class PERFETTO_EXPORT I2cReadFtraceEvent : public ::protozero::CppMessageObj { public: enum FieldNumbers { kAdapterNrFieldNumber = 1, kMsgNrFieldNumber = 2, kAddrFieldNumber = 3, kFlagsFieldNumber = 4, kLenFieldNumber = 5, }; I2cReadFtraceEvent(); ~I2cReadFtraceEvent() override; I2cReadFtraceEvent(I2cReadFtraceEvent&&) noexcept; I2cReadFtraceEvent& operator=(I2cReadFtraceEvent&&); I2cReadFtraceEvent(const I2cReadFtraceEvent&); I2cReadFtraceEvent& operator=(const I2cReadFtraceEvent&); bool operator==(const I2cReadFtraceEvent&) const; bool operator!=(const I2cReadFtraceEvent& other) const { return !(*this == other); } bool ParseFromArray(const void*, size_t) override; std::string SerializeAsString() const override; std::vector<uint8_t> SerializeAsArray() const override; void Serialize(::protozero::Message*) const; bool has_adapter_nr() const { return _has_field_[1]; } int32_t adapter_nr() const { return adapter_nr_; } void set_adapter_nr(int32_t value) { adapter_nr_ = value; _has_field_.set(1); } bool has_msg_nr() const { return _has_field_[2]; } uint32_t msg_nr() const { return msg_nr_; } void set_msg_nr(uint32_t value) { msg_nr_ = value; _has_field_.set(2); } bool has_addr() const { return _has_field_[3]; } uint32_t addr() const { return addr_; } void set_addr(uint32_t value) { addr_ = value; _has_field_.set(3); } bool has_flags() const { return _has_field_[4]; } uint32_t flags() const { return flags_; } void set_flags(uint32_t value) { flags_ = value; _has_field_.set(4); } bool has_len() const { return _has_field_[5]; } uint32_t len() const { return len_; } void set_len(uint32_t value) { len_ = value; _has_field_.set(5); } private: int32_t adapter_nr_{}; uint32_t msg_nr_{}; uint32_t addr_{}; uint32_t flags_{}; uint32_t len_{}; // Allows to preserve unknown protobuf fields for compatibility // with future versions of .proto files. std::string unknown_fields_; std::bitset<6> _has_field_{}; }; } // namespace perfetto } // namespace protos } // namespace gen #endif // PERFETTO_PROTOS_PROTOS_PERFETTO_TRACE_FTRACE_I2C_PROTO_CPP_H_
34.457249
90
0.731201
[ "vector" ]
6009401f27a7c447b55c11d55f6362756298aa95
4,419
h
C
src-plugins/v3dView/v3dViewAnnotationInteractor.h
gpasquie/medInria-public
1efa82292698695f6ee69fe00114aabce5431246
[ "BSD-4-Clause" ]
null
null
null
src-plugins/v3dView/v3dViewAnnotationInteractor.h
gpasquie/medInria-public
1efa82292698695f6ee69fe00114aabce5431246
[ "BSD-4-Clause" ]
null
null
null
src-plugins/v3dView/v3dViewAnnotationInteractor.h
gpasquie/medInria-public
1efa82292698695f6ee69fe00114aabce5431246
[ "BSD-4-Clause" ]
null
null
null
/*========================================================================= medInria Copyright (c) INRIA 2013. All rights reserved. See LICENSE.txt for details. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. =========================================================================*/ #pragma once #include "medAbstractVtkViewInteractor.h" #include <medAnnotationData.h> #include <medAttachedData.h> #include "v3dViewPluginExport.h" #include <vtkAbstractWidget.h> class v3dViewAnnotationInteractorPrivate; class v3dView; class v3dViewAnnotationInteractor; // Helper class for v3dViewAnnotationInteractor class V3DVIEWPLUGIN_EXPORT v3dViewAnnIntHelper { public : v3dViewAnnIntHelper(v3dViewAnnotationInteractor * annInt); virtual ~v3dViewAnnIntHelper(); virtual bool addAnnotation( medAnnotationData* annData ) = 0; virtual void removeAnnotation( medAnnotationData * annData ) = 0; virtual void annotationModified( medAnnotationData* annData ) = 0; protected: v3dView * getV3dView(); v3dViewAnnotationInteractor * m_v3dViewAnnInt; }; //! Interface between annotations and the v3dview. class V3DVIEWPLUGIN_EXPORT v3dViewAnnotationInteractor: public medAbstractVtkViewInteractor { typedef medAbstractVtkViewInteractor BaseClass; Q_OBJECT public: v3dViewAnnotationInteractor(); virtual ~v3dViewAnnotationInteractor(); //! Override dtkAbstractObject virtual QString description() const; virtual QString identifier() const; virtual QStringList handled() const; virtual bool isDataTypeHandled(QString dataType) const; static bool registered(); virtual void enable(); virtual void disable(); //! Override dtkAbstractViewInteractor. virtual bool isAutoEnabledWith ( dtkAbstractData * data ); //! Implement dtkAbstractViewInteractor virtual void setData(dtkAbstractData *data); virtual void setView(dtkAbstractView* view); //! Whether the interactor should be on when the view is in 2d and 3d mode. virtual bool showIn2dView() const; virtual bool showIn3dView() const; //! Return true if the annotation should be shown in the given slice. virtual bool isInSlice( const QVector3D & slicePoint, const QVector3D & sliceNormal, qreal thickness) const; static QString s_identifier(); signals: public slots: virtual bool onAddAnnotation( medAnnotationData * annItem ); virtual void onRemoveAnnotation( medAnnotationData * annItem ); //! Respond to add / removal of attached data to data items viewed. virtual void onAttachedDataAdded(medAttachedData* data); virtual void onAttachedDataRemoved(medAttachedData* data); //! Called when the annotation data is altered. virtual void onDataModified(medAbstractData* data); // Mandatory implementations from medVtkViewInteractor virtual void setOpacity(dtkAbstractData * data, double opacity); virtual double opacity(dtkAbstractData * data) const; virtual void setVisible(dtkAbstractData * data, bool visible); virtual bool isVisible(dtkAbstractData * data) const; protected: void onPropertySet(const QString& key, const QString& value); void onVisibilityPropertySet (const QString& value); v3dView * getV3dView(); void initialize(medAbstractView * view, medAbstractData* data); virtual QPointF worldToScene( const QVector3D & worldVec ) const; virtual QVector3D sceneToWorld( const QPointF & sceneVec ) const; //! Get the view plane up vector in world space. virtual QVector3D viewUp() const; bool isPointInSlice( const QVector3D & testPoint, const QVector3D & slicePoint, const QVector3D & sliceNormal, qreal thickness) const; bool isPointInCurrentSlice( const QVector3D & testPoint) const; virtual medAbstractViewCoordinates * coordinates(); virtual const medAbstractViewCoordinates * coordinates() const; void addAnnotation( medAnnotationData * annData ); void removeAnnotation( medAnnotationData * annData ); friend class v3dViewAnnotationInteractorPrivate; friend class v3dViewAnnIntHelper; private: v3dViewAnnotationInteractorPrivate *d; }; // Inline this for speed. inline v3dView * v3dViewAnnIntHelper::getV3dView() { return m_v3dViewAnnInt->getV3dView(); }
31.340426
139
0.728219
[ "vector", "3d" ]
601065179e4429d7644039aa0f72112b2b5f9dca
6,933
h
C
source/Ssp/hdk_ccsp_mbus.h
lgirdk/ccsp-home-security
0c7d6a87dd7c553bb8536f9175aecfad1dff695f
[ "Apache-2.0" ]
2
2021-05-27T16:42:27.000Z
2021-11-08T10:28:43.000Z
source/Ssp/hdk_ccsp_mbus.h
lgirdk/ccsp-home-security
0c7d6a87dd7c553bb8536f9175aecfad1dff695f
[ "Apache-2.0" ]
null
null
null
source/Ssp/hdk_ccsp_mbus.h
lgirdk/ccsp-home-security
0c7d6a87dd7c553bb8536f9175aecfad1dff695f
[ "Apache-2.0" ]
4
2017-07-30T15:41:59.000Z
2021-05-27T16:42:28.000Z
/* * If not stated otherwise in this file or this component's Licenses.txt file the * following copyright and licenses apply: * * Copyright 2015 RDK Management * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /********************************************************************** Copyright [2014] [Cisco Systems, Inc.] Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. **********************************************************************/ /* * hdk_ccsp_mbus.h * * CCSP message bus APIs, which are used to access Data Model. * * leichen2@cisco.com * 2011.11.04 - Initialize */ #ifndef __HDK_CCSP_MBUS_H__ #define __HDK_CCSP_MBUS_H__ /* Max size of TR-181's object/parameter's path */ #define MAX_PATH_NAME 256 #ifndef NELEMS #define NELEMS(arr) (sizeof(arr) / sizeof((arr)[0])) #endif /* parameter types */ typedef enum MBusParamType_e { MBUS_PT_UNSPEC = 0, MBUS_PT_STRING, MBUS_PT_INT, MBUS_PT_UINT, MBUS_PT_BOOL, MBUS_PT_DATETIME, MBUS_PT_BASE64, MBUS_PT_LONG, MBUS_PT_ULONG, MBUS_PT_FLOAT, MBUS_PT_DOUBLE, MBUS_PT_BYTE, } MBusParamType_t; typedef struct MBusParam_s { char *name; char *value; MBusParamType_t type; } MBusParam_t; /* MBusObj_s is an internal structure */ typedef struct MBusObj_s MBusObj_t; /* * Description: * * Create a mbus object to access TR-181 data modle. * * Parameters: * * @subSystem [in] * Sub-system ID, e.g., "eRT", "eMG", "eGW", or "" for default. * @confFile [in] * Config file of CCSP message bus. * @compId [in] * Component ID of the module attend to use mbus. It's should be * a unique ID, e.g., "com.cisco.spvtg.ccsp.<SOMEID>" * @compCrId [in] * CR's component ID. CR is used to lookup the component of speicific path. * * Return: * * mbus object pointer or NULL if error. */ MBusObj_t * MBus_Create(const char *subSystem, const char *confFile, const char *compId, const char *compCrId); /* * Description: * * Destory the mbus created by MBus_Create(). * * Parameters: * * @mbus [in] * mbus object to destroy. * * Return: * * 0 if success and -1 on error. */ int MBus_Destroy(MBusObj_t *mbus); /* * Description: * * Get parameter's value. * * Parameters: * * @mbus [in] * mbus created by MBus_Create. * @path [in] * Full path the parameter. It must be an parameter, e.g., Device.IP.Interface.{1}.Name * instead of an object (e.g. Device.IP.). * @val [out] * Buffer to save value. * @size [in] * Buffer size of @val. * * Return: * * 0 if success and -1 on error. */ int MBus_GetParamVal(MBusObj_t *mbus, const char *path, char *val, int size); /* * Description: * * Set parameter's value. * * Parameters: * * @mbus [in] * mbus created by MBus_Create. * @path [in] * Full path the parameter. It must be an parameter, e.g., Device.IP.Interface.{1}.Name * instead of an object (e.g. Device.IP.). * @type [in] * The parameter's type, it should be one of MBUS_PT_XXX (except MBUS_PT_UNSPEC). * @val [in] * Buffer to save value. * @commit [in] * Commit after set or not. 1 means commit, 0 for not. * * Return: * * 0 if success and -1 on error. */ int MBus_SetParamVal(MBusObj_t *mbus, const char *path, MBusParamType_t type, const char *val, int commit); /* * Description: * * Commit parameters set before. * * Parameters: * * @mbus [in] * mbus created by MBus_Create. * @path [in] * the parameter/object set before. * * Return: * * 0 if success and -1 on error. */ int MBus_Commit(MBusObj_t *mbus, const char *path); /* * Description: * * Lookup the path of object's instance(s), by object prefix. * A object path (prefix) is like "IP.Device.Interface." * and a instance is like "IP.Device.Interface.1." * so the format of instance path must be "<prefix>.%d." . * * Parameters: * * @mbus [in] * mbus created by MBus_Create. * @objPath [in] * Object path (prefix), see the defination above. * @paramName [in] <optional> * If exit, the parameter must be exist for the instance. * @paramVal [in] <optional> * If exit and @paramName is exist, the value must match. * @insPath [out] * Path names of the instance(s) found. * @insNum [in-out] * As an input, it's the max size of the @insPath[][MAX_PATH_NAME], * as an output, it's the number of instance(s) stored in @insPath. * * Return: * * 0 if success and -1 on error. */ int MBus_FindObjectIns(MBusObj_t *mbus, const char *objPath, const char *paramName, const char *paramVal, char insPath[][MAX_PATH_NAME], int *insNum); /* * Description: * * Add an instance of an object * * Parameters: * * @mbus [in] * mbus created by MBus_Create. * @objPath [in] * the object's name (instance's prefix). * @ins [out] (optional) * instance number of new instance. * * Return: * * 0 if success and -1 on error. */ int MBus_AddObjectIns(MBusObj_t *mbus, const char *objPath, int *ins); /* * Description: * * Delete an instance of an object * * Parameters: * * @mbus [in] * mbus created by MBus_Create. * @objPath [in] * the instance's path * @ins [in] * instance number of object * * Return: * * 0 if success and -1 on error. */ int MBus_DelObjectIns(MBusObj_t *mbus, const char *objPath, int ins); int FindFirstInstance(MBusObj_t *mbus, const char *object, char *ins, int size); /* @ins: 0 for first instance, else as the instance number for specific instance */ int GetParamValueForIns(MBusObj_t *mbus, const char *object, const char *param, int ins, char *value, int size); int MBus_SetParamVect(MBusObj_t *mbus, const char *object, const MBusParam_t params[], int num, int commit); #endif /* __HDK_CCSP_MBUS_H__ */
24.938849
91
0.642579
[ "object", "model" ]
602dcb09b71b858a93375cb3eebeb7f595b4b9de
7,856
h
C
components/render/manager/sources/cache_map.h
untgames/funner
c91614cda55fd00f5631d2bd11c4ab91f53573a3
[ "MIT" ]
7
2016-03-30T17:00:39.000Z
2017-03-27T16:04:04.000Z
components/render/manager/sources/cache_map.h
untgames/Funner
c91614cda55fd00f5631d2bd11c4ab91f53573a3
[ "MIT" ]
4
2017-11-21T11:25:49.000Z
2018-09-20T17:59:27.000Z
components/render/manager/sources/cache_map.h
untgames/Funner
c91614cda55fd00f5631d2bd11c4ab91f53573a3
[ "MIT" ]
4
2016-11-29T15:18:40.000Z
2017-03-27T16:04:08.000Z
/////////////////////////////////////////////////////////////////////////////////////////////////// ///Предикат необходимости удаления /////////////////////////////////////////////////////////////////////////////////////////////////// struct CacheMapDefaultRemovePred { template <class T> bool operator () (const T&) const { return true; } }; /////////////////////////////////////////////////////////////////////////////////////////////////// ///Кэшированное отображение (стратегия кэширования - LRU) /////////////////////////////////////////////////////////////////////////////////////////////////// template <class Key, class Value, class RemovePred = CacheMapDefaultRemovePred> class CacheMap: public Cache { public: /////////////////////////////////////////////////////////////////////////////////////////////////// ///Конструктор /////////////////////////////////////////////////////////////////////////////////////////////////// CacheMap (const CacheManagerPtr&); /////////////////////////////////////////////////////////////////////////////////////////////////// ///Количество элементов / проверка на пустоту /////////////////////////////////////////////////////////////////////////////////////////////////// size_t Size (); bool IsEmpty (); /////////////////////////////////////////////////////////////////////////////////////////////////// ///Поиск элемента /////////////////////////////////////////////////////////////////////////////////////////////////// Value* Find (const Key&); Value& Get (const Key&); Value& operator [] (const Key& key) { return Get (key); } /////////////////////////////////////////////////////////////////////////////////////////////////// ///Вставка и удаление элемента /////////////////////////////////////////////////////////////////////////////////////////////////// void Add (const Key& key, const Value& value); void Remove (const Key& key); /////////////////////////////////////////////////////////////////////////////////////////////////// ///Очистка /////////////////////////////////////////////////////////////////////////////////////////////////// void Clear (); /////////////////////////////////////////////////////////////////////////////////////////////////// ///Перебор элементов /////////////////////////////////////////////////////////////////////////////////////////////////// template <class Fn> void ForEach (Fn fn); private: /////////////////////////////////////////////////////////////////////////////////////////////////// ///Сброс закэшированных элементов /////////////////////////////////////////////////////////////////////////////////////////////////// void FlushCache (); /////////////////////////////////////////////////////////////////////////////////////////////////// ///Вставка /////////////////////////////////////////////////////////////////////////////////////////////////// Value& AddCore (const Key& key, const Value& value); private: struct Item; typedef stl::hash_map<Key, Item> ItemMap; typedef stl::list<typename ItemMap::iterator> ItemList; struct Item: public Value { FrameId last_use_frame; //кадр последнего использования элемента FrameTime last_use_time; //время последнего использования элемента typename ItemList::iterator position; //положение в списке элементов }; private: ItemMap item_map; ItemList item_list; RemovePred remove_pred; }; /* Реализация */ /* Конструктор */ template <class Key, class Value, class RemovePred> CacheMap<Key, Value, RemovePred>::CacheMap (const CacheManagerPtr& manager) : Cache (manager) { } /* Количество элементов / проверка на пустоту */ template <class Key, class Value, class RemovePred> size_t CacheMap<Key, Value, RemovePred>::Size () { return item_map.size (); } template <class Key, class Value, class RemovePred> bool CacheMap<Key, Value, RemovePred>::IsEmpty () { return item_map.empty (); } /* Поиск элемента */ template <class Key, class Value, class RemovePred> Value* CacheMap<Key, Value, RemovePred>::Find (const Key& key) { typename ItemMap::iterator iter = item_map.find (key); if (iter == item_map.end ()) return 0; iter->second.last_use_time = CurrentTime (); iter->second.last_use_frame = CurrentFrame (); item_list.splice (item_list.begin (), item_list, iter->second.position); return &iter->second; } template <class Key, class Value, class RemovePred> Value& CacheMap<Key, Value, RemovePred>::Get (const Key& key) { if (Value* result = Find (key)) return *result; return AddCore (key, Value ()); } /* Вставка и удаление элемента */ template <class Key, class Value, class RemovePred> Value& CacheMap<Key, Value, RemovePred>::AddCore (const Key& key, const Value& value) { Item item; item.last_use_time = CurrentTime (); item.last_use_frame = CurrentFrame (); static_cast<Value&> (item) = value; stl::pair<typename ItemMap::iterator, bool> result = item_map.insert_pair (key, item); if (!result.second) throw xtl::make_argument_exception ("render::manager::CacheMap<Key, Value, RemovePred>::Add", "Internal error: item with specified key/value has been already inserted"); try { item_list.push_front (result.first); result.first->second.position = item_list.begin (); return result.first->second; } catch (...) { item_map.erase (result.first); throw; } } template <class Key, class Value, class RemovePred> void CacheMap<Key, Value, RemovePred>::Add (const Key& key, const Value& value) { typename ItemMap::iterator iter = item_map.find (key); if (iter != item_map.end ()) throw xtl::make_argument_exception ("render::manager::CacheMap<Key, Value, RemovePred>::Add", "Item with specified key/value has been already inserted"); AddCore (key, value); } template <class Key, class Value, class RemovePred> void CacheMap<Key, Value, RemovePred>::Remove (const Key& key) { typename ItemMap::iterator iter = item_map.find (key); if (iter == item_map.end ()) return; item_list.erase (iter->second.position); item_map.erase (iter); } /* Очистка */ template <class Key, class Value, class RemovePred> void CacheMap<Key, Value, RemovePred>::Clear () { item_map.clear (); item_list.clear (); } /* Итераторы */ template <class Key, class Value, class RemovePred> template <class Fn> void CacheMap<Key, Value, RemovePred>::ForEach (Fn fn) { for (typename ItemMap::iterator iter=item_map.begin (); iter!=item_map.end (); ++iter) fn (iter->first, iter->second); } /* Сброс закэшированных элементов которые не использовались с кадра min_frame или времени min_time */ template <class Key, class Value, class RemovePred> void CacheMap<Key, Value, RemovePred>::FlushCache () { FrameTime current_time = CurrentTime (), time_delay = TimeDelay (); FrameId current_frame = CurrentFrame (), frame_delay = FrameDelay (); typename ItemList::iterator iter = item_list.end (); while (!item_list.empty () && iter != item_list.begin ()) { --iter; Item& item = (*iter)->second; if (current_time - item.last_use_time <= time_delay && current_frame - item.last_use_frame <= frame_delay) return; if (remove_pred (item)) { typename ItemList::iterator next = iter; ++next; item_map.erase (*iter); item_list.erase (iter); iter = next; } } }
31.174603
178
0.474414
[ "render" ]
603c0dc0f7fc3613a7a9cc030c8cbc89cd4b7d43
1,765
h
C
src/be_vector.h
BadDecisionsAlex/berry
af2c725febb13b855e8a6c91da6082d1b3014858
[ "MIT" ]
null
null
null
src/be_vector.h
BadDecisionsAlex/berry
af2c725febb13b855e8a6c91da6082d1b3014858
[ "MIT" ]
null
null
null
src/be_vector.h
BadDecisionsAlex/berry
af2c725febb13b855e8a6c91da6082d1b3014858
[ "MIT" ]
null
null
null
#ifndef BE_VECTOR_H #define BE_VECTOR_H #include "be_object.h" /* =============================== defines =============================== */ #define be_vector_count( vector ) ( ( vector )->count ) #define be_vector_data( vector ) ( ( vector )->data ) #define be_vector_first( vector ) ( ( vector )->data ) #define be_vector_isend( vector, item ) ( ( item ) > ( vector )->end ) #define be_vector_isempty( stack ) ( be_vector_count( stack ) == 0 ) #define be_vector_end( vector ) ( ( vector )->end ) #define be_stack_init( stack, size ) be_vector_init( stack, size ) #define be_stack_delete( stack ) be_vector_delete( stack ) #define be_stack_clear( stack ) be_vector_clear( stack ) #define be_stack_push( stack, data ) be_vector_append( stack, data ) #define be_stack_pop( stack ) be_vector_remove_end( stack ) #define be_stack_top( stack ) be_vector_end( stack ) #define be_stack_base( stack ) be_vector_first( stack ) #define be_stack_count( stack ) be_vector_count( stack ) #define be_stack_isempty( stack ) be_vector_isempty( stack ) /* ========================== function extern ========================== */ void be_vector_init( bvector * vector, int size ); void be_vector_delete( bvector * vector ); void * be_vector_at( bvector * vector, int index ); void be_vector_append( bvector * vector, void * data ); void be_vector_remove_end( bvector * vector ); void be_vector_resize( bvector * vector, int count ); void be_vector_clear( bvector * vector ); void * be_vector_release( bvector * vector ); int be_nextpow( int v ); #endif /* ndef BE_VECTOR_H */
49.027778
77
0.602266
[ "vector" ]
604619ff50410dac7362e8688c9108e695760cb1
275
h
C
src/hac/OverlayPatcher.h
Chaosvex/HAC2
0ce0d929037b688cc4dc03a55a3a39325d131874
[ "MIT" ]
18
2018-04-19T15:31:02.000Z
2021-12-18T00:40:53.000Z
src/hac/OverlayPatcher.h
num0005/HAC2
0ce0d929037b688cc4dc03a55a3a39325d131874
[ "MIT" ]
null
null
null
src/hac/OverlayPatcher.h
num0005/HAC2
0ce0d929037b688cc4dc03a55a3a39325d131874
[ "MIT" ]
1
2020-07-19T16:20:36.000Z
2020-07-19T16:20:36.000Z
#pragma once #include <vector> #include <memory> class PatchGroup; class OverlayPatcher { public: OverlayPatcher() { } ~OverlayPatcher(); void patch(); private: std::vector<std::unique_ptr<PatchGroup>> hooks; OverlayPatcher(const OverlayPatcher&); };
16.176471
49
0.690909
[ "vector" ]
604ccafec3ad72b0066cc28788b988f53346f2f8
9,143
c
C
src/utils/randomNumbers.c
Bhaskers-Blu-Org2/SynthaCorpus
68b72eecbcf3ffba3a54d909100315d65c53e2cb
[ "MIT", "BSD-3-Clause" ]
7
2019-08-14T00:12:06.000Z
2021-11-11T19:42:51.000Z
src/utils/randomNumbers.c
microsoft/SynthaCorpus
68b72eecbcf3ffba3a54d909100315d65c53e2cb
[ "MIT", "BSD-3-Clause" ]
null
null
null
src/utils/randomNumbers.c
microsoft/SynthaCorpus
68b72eecbcf3ffba3a54d909100315d65c53e2cb
[ "MIT", "BSD-3-Clause" ]
9
2019-11-03T12:22:44.000Z
2021-06-08T19:10:21.000Z
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT license. #include <stdio.h> // Needed for printf() #include <stdlib.h> // Needed for exit() and ato*() #include <math.h> // Needed for sqrt() #include <string.h> // Needed for strcpy() #include "../definitions.h" #include "../imported/TinyMT_cutdown/tinymt64.h" #include "randomNumbers.h" void test_random_number_generation(double alpha, double N) { double r, expected; int buckets[100] = { 0 }, i, bucket, iters = 1000000; // First check uniformity of rand_val(0); for (i = 0; i < iters; i++) { r = rand_val(0) * 100.0; bucket = (int)floor(r); buckets[bucket]++; } expected = (double)iters / 100.00; printf("test_random_number_generation: 100 buckets, %d trials, expected frequency: %.0f Testing for freq. deviations > 2%%\n", iters, expected); for (i = 0; i < 100; i++) { double dev = fabs((double)buckets[i] - expected); if (dev / expected > 0.02) printf(" Bucket %3d: %d v. %.0f\n", i, buckets[i], expected); } printf("\n"); } void setup_linseg_derived_values(midseg_desc_t *linseg) { double AFL; linseg->ap1 = linseg->alpha + 1.0; // alpha plus 1 linseg->rap1 = 1.0 / linseg->ap1; // reciprocal of alpha + 1 AFL = (pow(linseg->L, linseg->ap1) - pow(linseg->F, linseg->ap1)) / linseg->ap1; // AFL is initially the calculated area between F and L linseg->area_scale_factor = 1.0 / AFL; // Now c is the scale up factor to ensure that the random numbers in 0-1 map to areas under the curve between F and L linseg->area_toF = linseg->area_scale_factor * pow(linseg->F, linseg->ap1) / linseg->ap1; // I think it makes sense that this area must also be scaled up. } void setup_linseg_full(midseg_desc_t *linseg, double alpha, double F, double L, double probrange, double cumprob) { // From slope alpha and term rank range f - l, set up linseg to // record those values and all the other fixed constants which will // be needed by getZipfianTermRandomNumber() // This is the revised maths from Guy Fawkes Day 2015 -- "Guy // Fawkes, the only man ever to enter parliament with honest // intentions." // // logic is as follows: Basic function is x ** alpha whose integral // is x ** (alpha + 1) / (alpha + 1). The area under the curve // between x = F and x = L is A = (L ** (alpha + 1) - F ** (alpha + // 1)) / (alpha + 1) but the area is a sum of all probabilities so // we must scale up by c = 1/A to ensure that the total area is 1.0 // // Given a uniform random number r in the range 0 - 1, we treat it // as an area, beyond x = F and solve for x Let area_toF be the area // under the curve between x = 0 and x = F: area_toF = c * (F ** // (alpha + 1) / (alpha + 1)) Let r' = r + area_toF; r' = c * ((x ** // (alpha + 1)) / (alpha + 1)) Thus x ** (alpha + 1) = r' * (alpha + // 1) / c; and x = pow(r' * (alpha + 1) / c, 1/(alpha + 1)) if (0) printf("setup linseg\n"); linseg->alpha = alpha; linseg->F = F; linseg->L = L; linseg->probrange = probrange; linseg->cumprob = cumprob; setup_linseg_derived_values(linseg); } double rand_val(u_ll seed) { // Get a random double r in 0.0 <= r < 1.0. If seed != 0, initialise the // underlying generator first. // Calls the cache-friendly Tiny version of the Mersenne Twister. See // ../imported/TinyMT_cutdown/tinymt64.[ch] // // Note that the parameter array values are hard-coded rather than settable static tinymt64_t tinymt; double rez; if (seed != 0) { tinymt.mat1 = 0Xfa051f40; tinymt.mat2 = 0Xffd0fff4; tinymt.tmat = 0X58d02ffeffbfffbcULL; tinymt64_init(&tinymt, seed); if (0) printf("Initialized.\n"); return 0.0; } rez = tinymt64_generate_double(&tinymt); return rez; } double rand_normal(double mean, double stddev) { // Generate a random number from a normal distribution // with specified mean and standard deviation. The // method used is Marsaglia's polar method. See // https://en.wikipedia.org/wiki/Marsaglia_polar_method // When the loop finishes, we calculate a common expression // from which we derive a pair of results. We return // one and save the second for the next call. static double r2 = 0.0; static BOOL r2_ready = FALSE; double ce, r1, result; if (!r2_ready) { double x, y, s; do { x = 2.0 * rand_val(0) - 1; y = 2.0 * rand_val(0) - 1; s = x*x + y*y; } while ((s == 0.0) || (s > 1.0)); ce = sqrt(-2.0 * log(s) / s); r1 = x * ce; r2 = y * ce; result = r1 * stddev + mean; r2_ready = TRUE; // Indicate that r2 is ready for the next call. return result; } else { r2_ready = FALSE; return r2 * stddev + mean; } } static double prev_alpha = -1; double rand_gamma(double alpha, double lambda) { // Gamma(alpha, lambda) generator, where alpha is the shape // parameter and lambda is the scale. using Marsaglia and Tsang // (2000) method. // @article{MarsagliaTsangGamma2000, // author = {Marsaglia, George and Tsang, Wai Wan}, // title = {A Simple Method for Generating Gamma Variables}, // journal = {ACM Transactions on Mathematical Software}, // volume = {26}, // number = {3}, // year = {2000}, // pages = {363--372}, // url = {http://doi.acm.org/10.1145/358407.358414}, // } double u, v, x; static double c, d; if (alpha != prev_alpha) { // Set up c and d (only needed if alpha changes. d = alpha - 1 / 3; c = 1.0 / sqrt(9.0 * d); prev_alpha = alpha; } if (alpha >= 1) { while (1) { do { x = rand_normal(0.0, 1.0); // Should think about using the Ziggurat inline // method from Marsaglia and Tsang v = (1.0 + c * x); } while (v <= 0.0); // According to M & T looping is rare v *= (v * v); // Fastest way to do a cube? u = rand_val(0); if (u < 1.0 - 0.0331*(x*x)*(x*x)) return d * v * lambda; if (log(u) < 0.5 * x * x + d * (1.0 - v + log(v))) return d * v * lambda; } // End of infinite loop; } else { // See the note in Marsagia and Tsang p. 371 double res; res = rand_gamma(alpha + 1, lambda); res *= pow(rand_val(0), (1.0 / alpha)); return res * lambda; } } void test_rand_gamma() { int i, b, trials = 10000000; double alpha, lambda, x, *buckets, unit_weight = 1.0 / (double)trials; buckets = (double *)malloc(200 * sizeof(double)); for (i = 0; i < 200; i++) buckets[i] = 0.0; rand_val(53); alpha = 5.0; lambda = 1.0; for (i = 0; i < trials; i++) { x = rand_gamma(alpha, lambda); b = (int)floor(x * 10.0); if (b < 0) b = 0; if (b >= 200) b = 199; buckets[b] += unit_weight; } printf("GAMMA(5.0, 1.0) #x y\n"); for (i = 0; i < 200; i++) { printf("GAMMA(5.0, 1.0) %.3f %.5f\n", (double) i / 10.0, buckets[i]); } free(buckets); printf("test_rand_gamma(): %d trials\n", trials); } double rand_cumdist(int num_segs, double *cumprobs, double *xvals) { // If there were a lot of segments we should implement something // like a binary search. Let's assume that there aren't that many // and that the shape of the cumulative distribution is biased // toward the early segments which will tend to reduce the number of // steps necessary It is assumed that cumprobs[num_segs - 1] = 1.0 // and that the values are in ascending order; double unirand = rand_val(0); // Uniform in range 0 -1 double probstep, loprob, frac, xvalstep, loxval, rslt; int s; // s - segment number for (s = 0; s < num_segs; s++) { if (unirand <= cumprobs[s]) { if (s == 0) { loprob = 0.0; loxval = 0; } else { loprob = cumprobs[s - 1]; loxval = xvals[s - 1]; } probstep = cumprobs[s] - loprob; // This is the range of probabilities covered by this segment frac = (unirand - loprob) / probstep; xvalstep = xvals[s] - loxval; rslt = loxval + frac * xvalstep; return rslt; } } printf("Error: in rand_cumdist. (Fell off the end.)\n"); exit(1); } void test_rand_cumdist() { // Simulate a uniform distributions between lengths 1 and 100 using 10 unequal segments. int i, b, trials = 100000000; double x, buckets[101], lengths[10] = { 1,2,3,10,20,30,40,80,99,100 }, cumprobs[10] = {0.01, 0.02, 0.03, 0.10, 0.20, 0.30, 0.40, 0.80, 0.99, 1.00}, unit_weight = 1.0 / (double)trials; for (i = 0; i <= 100; i++) buckets[i] = 0.0; rand_val(53); for (i = 0; i < trials; i++) { x = rand_cumdist(10, cumprobs, lengths); b = (int)round(x); if (b < 1 || b > 100) { printf("Error in test_rand_cumdist() - value %.5f is assigned to out-of-range bucket %d\n", x, b); exit(1); } buckets[b] += unit_weight; } printf("Rand_cumdist #x y\n"); for (i = 0; i <= 100; i++) { if (fabs(buckets[i] - 0.0100)> 0.005) printf("** "); else if (fabs(buckets[i] - 0.0100)> 0.001) printf("* "); else printf(" "); printf("CUMDIST %d %.5f\n", i, buckets[i]); } printf("test_rand_cumdist(): %d trials\n", trials); }
32.653571
159
0.605162
[ "shape", "3d" ]
605191f524b0ce6c9c175dadd1e008225c937fe5
6,193
h
C
source/MyAstVisitor.h
dougpuob/namelint
6a144cdc4b3935994059961fe712525ce30ff269
[ "MIT" ]
30
2020-08-01T07:29:23.000Z
2022-03-30T13:21:43.000Z
source/MyAstVisitor.h
dougpuob/namelint
6a144cdc4b3935994059961fe712525ce30ff269
[ "MIT" ]
48
2019-01-02T18:19:41.000Z
2020-04-26T02:53:23.000Z
source/MyAstVisitor.h
dougpuob/namelint
6a144cdc4b3935994059961fe712525ce30ff269
[ "MIT" ]
5
2019-08-30T08:41:17.000Z
2020-05-19T01:17:15.000Z
#ifndef __NAMELINT_MY_AST_VISITOR__H__ #define __NAMELINT_MY_AST_VISITOR__H__ #include <iostream> #include <vector> #include "Config.h" #include "Detection.h" #include "DumpDecl.h" #include "MyAstConsumer.h" #include "TraceMemo.h" using namespace std; using namespace clang; using namespace clang::tooling; using namespace llvm; using namespace clang::driver; using namespace clang::tooling; using namespace namelint; class MyASTVisitor : public RecursiveASTVisitor<MyASTVisitor> { private: DumpDecl m_DumpDecl; ASTContext *m_pAstCxt; const SourceManager *m_pSrcMgr; Detection m_Detect; shared_ptr<ConfigData> m_pConfig; bool isMainFile(Decl *pDecl); bool getPos(Decl *pDecl, string &FileName, size_t &nLineNumb, size_t &nColNumb); bool removeKeywords(string &TyeName); ErrorDetail *createErrorDetail(const string &FileName, const string &Suggestion); ErrorDetail *createErrorDetail(Decl *pDecl, const CheckType &CheckType, const bool &bIsPtr, const bool &bIsArray, const string &TargetName, const string &Expected); ErrorDetail *createErrorDetail(Decl *pDecl, const CheckType &CheckType, const bool &bIsPtr, const bool &bIsArray, const string &TypeName, const string &TargetName, const string &Suggestion); bool getClassInfo(CXXRecordDecl* pDecl, string& Name); bool getFunctionInfo(FunctionDecl *pDecl, string &FuncName); bool getParmsInfo(ParmVarDecl *pDecl, string &VarType, string &VarName, bool &bIsPtr, bool &bAnonymous); bool getStructVarInfo(ValueDecl *pDecl, string &VarType, string &VarName, bool &bIsPtr); bool getValueInfo(ValueDecl *pDecl, string &ValueType, string &ValueName, bool &bIsPtr, bool &bIsArray, bool &bIsBuiltinType); bool checkRuleForVariable(ValueDecl *pDecl); bool checkRuleForUnionValue(ValueDecl *pDecl); bool checkRuleForStructValue(ValueDecl *pDecl); bool checkRuleForEnumValue(EnumConstantDecl *pDecl); public: MyASTVisitor(const SourceManager *pSM, const ASTContext *pAstCxt, const Config *pConfig); // bool VisitStmt(Stmt *pStmt); // bool VisitCXXRecordDecl(CXXRecordDecl *D); // bool VisitCXXConstructorDecl(CXXConstructorDecl *D); bool VisitCXXRecordDecl(CXXRecordDecl *pDecl); bool VisitFunctionDecl(FunctionDecl *pDecl); bool VisitCXXMethodDecl(CXXMethodDecl *pDecl); bool VisitRecordDecl(RecordDecl *pDecl); bool VisitVarDecl(VarDecl *pDecl); bool VisitFieldDecl(FieldDecl *pDecl); bool VisitReturnStmt(ReturnStmt *pRetStmt); bool VisitParmVarDecl(ParmVarDecl *pDecl); bool VisitTypedefDecl(TypedefDecl *pDecl); bool VisitEnumConstantDecl(EnumConstantDecl *pDecl); bool VisitEnumDecl(EnumDecl *pDecl); bool VisitTagTypeLoc(TagTypeLoc TL); bool VisitArrayTypeLoc(ArrayTypeLoc TL); bool VisitFunctionTypeLoc(FunctionTypeLoc TL, bool SkipResultType = false); }; /* // Declaration visitors bool VisitTypeAliasTemplateDecl(TypeAliasTemplateDecl *D); bool VisitTypeAliasDecl(TypeAliasDecl *D); bool VisitAttributes(Decl *D); bool VisitBlockDecl(BlockDecl *B); bool VisitCXXRecordDecl(CXXRecordDecl *D); Optional<bool> shouldVisitCursor(CXCursor C); bool VisitDeclContext(DeclContext *DC); bool VisitTranslationUnitDecl(TranslationUnitDecl *D); bool VisitTypedefDecl(TypedefDecl *D); bool VisitTagDecl(TagDecl *D); bool VisitClassTemplateSpecializationDecl(ClassTemplateSpecializationDecl *D); bool VisitClassTemplatePartialSpecializationDecl( ClassTemplatePartialSpecializationDecl *D); bool VisitTemplateTypeParmDecl(TemplateTypeParmDecl *D); bool VisitEnumConstantDecl(EnumConstantDecl *D); bool VisitDeclaratorDecl(DeclaratorDecl *DD); bool VisitFunctionDecl(FunctionDecl *ND); bool VisitFieldDecl(FieldDecl *D); bool VisitVarDecl(VarDecl *); bool VisitNonTypeTemplateParmDecl(NonTypeTemplateParmDecl *D); bool VisitFunctionTemplateDecl(FunctionTemplateDecl *D); bool VisitClassTemplateDecl(ClassTemplateDecl *D); bool VisitTemplateTemplateParmDecl(TemplateTemplateParmDecl *D); bool VisitObjCTypeParamDecl(ObjCTypeParamDecl *D); bool VisitObjCMethodDecl(ObjCMethodDecl *ND); bool VisitObjCContainerDecl(ObjCContainerDecl *D); bool VisitObjCCategoryDecl(ObjCCategoryDecl *ND); bool VisitObjCProtocolDecl(ObjCProtocolDecl *PID); bool VisitObjCPropertyDecl(ObjCPropertyDecl *PD); bool VisitObjCTypeParamList(ObjCTypeParamList *typeParamList); bool VisitObjCInterfaceDecl(ObjCInterfaceDecl *D); bool VisitObjCImplDecl(ObjCImplDecl *D); bool VisitObjCCategoryImplDecl(ObjCCategoryImplDecl *D); bool VisitObjCImplementationDecl(ObjCImplementationDecl *D); // FIXME: ObjCCompatibleAliasDecl requires aliased-class locations. bool VisitObjCPropertyImplDecl(ObjCPropertyImplDecl *PD); bool VisitLinkageSpecDecl(LinkageSpecDecl *D); bool VisitNamespaceDecl(NamespaceDecl *D); bool VisitNamespaceAliasDecl(NamespaceAliasDecl *D); bool VisitUsingDirectiveDecl(UsingDirectiveDecl *D); bool VisitUsingDecl(UsingDecl *D); bool VisitUnresolvedUsingValueDecl(UnresolvedUsingValueDecl *D); bool VisitUnresolvedUsingTypenameDecl(UnresolvedUsingTypenameDecl *D); bool VisitStaticAssertDecl(StaticAssertDecl *D); bool VisitFriendDecl(FriendDecl *D); // Name visitor bool VisitDeclarationNameInfo(DeclarationNameInfo Name); bool VisitNestedNameSpecifier(NestedNameSpecifier *NNS, SourceRange Range); bool VisitNestedNameSpecifierLoc(NestedNameSpecifierLoc NNS); // Template visitors bool VisitTemplateParameters(const TemplateParameterList *Params); bool VisitTemplateName(TemplateName Name, SourceLocation Loc); bool VisitTemplateArgumentLoc(const TemplateArgumentLoc &TAL); // Type visitors #define ABSTRACT_TYPELOC(CLASS, PARENT) #define TYPELOC(CLASS, PARENT) \ bool Visit##CLASS##TypeLoc(CLASS##TypeLoc TyLoc); #include "clang/AST/TypeLocNodes.def" bool VisitTagTypeLoc(TagTypeLoc TL); bool VisitArrayTypeLoc(ArrayTypeLoc TL); bool VisitFunctionTypeLoc(FunctionTypeLoc TL, bool SkipResultType = false); */ #endif // __NAMELINT_MY_AST_VISITOR__H__
40.743421
93
0.777491
[ "vector" ]
0071bf78e3ceffc949c4b1c89a16210ca0c7d3a7
13,418
h
C
src/mcleave.h
kevinkovalchik/X-Tandem-for-CentOS
5c65d2ffdea37f5787631e13c4c3bbf1706b072a
[ "Artistic-1.0-Perl" ]
null
null
null
src/mcleave.h
kevinkovalchik/X-Tandem-for-CentOS
5c65d2ffdea37f5787631e13c4c3bbf1706b072a
[ "Artistic-1.0-Perl" ]
null
null
null
src/mcleave.h
kevinkovalchik/X-Tandem-for-CentOS
5c65d2ffdea37f5787631e13c4c3bbf1706b072a
[ "Artistic-1.0-Perl" ]
null
null
null
/* Copyright (C) 2003 Ronald C Beavis, all rights reserved X! tandem This software is a component of the X! proteomics software development project Use of this software governed by the Artistic license, as reproduced here: The Artistic License for all X! software, binaries and documentation Preamble The intent of this document is to state the conditions under which a Package may be copied, such that the Copyright Holder maintains some semblance of artistic control over the development of the package, while giving the users of the package the right to use and distribute the Package in a more-or-less customary fashion, plus the right to make reasonable modifications. Definitions "Package" refers to the collection of files distributed by the Copyright Holder, and derivatives of that collection of files created through textual modification. "Standard Version" refers to such a Package if it has not been modified, or has been modified in accordance with the wishes of the Copyright Holder as specified below. "Copyright Holder" is whoever is named in the copyright or copyrights for the package. "You" is you, if you're thinking about copying or distributing this Package. "Reasonable copying fee" is whatever you can justify on the basis of media cost, duplication charges, time of people involved, and so on. (You will not be required to justify it to the Copyright Holder, but only to the computing community at large as a market that must bear the fee.) "Freely Available" means that no fee is charged for the item itself, though there may be fees involved in handling the item. It also means that recipients of the item may redistribute it under the same conditions they received it. 1. You may make and give away verbatim copies of the source form of the Standard Version of this Package without restriction, provided that you duplicate all of the original copyright notices and associated disclaimers. 2. You may apply bug fixes, portability fixes and other modifications derived from the Public Domain or from the Copyright Holder. A Package modified in such a way shall still be considered the Standard Version. 3. You may otherwise modify your copy of this Package in any way, provided that you insert a prominent notice in each changed file stating how and when you changed that file, and provided that you do at least ONE of the following: a. place your modifications in the Public Domain or otherwise make them Freely Available, such as by posting said modifications to Usenet or an equivalent medium, or placing the modifications on a major archive site such as uunet.uu.net, or by allowing the Copyright Holder to include your modifications in the Standard Version of the Package. b. use the modified Package only within your corporation or organization. c. rename any non-standard executables so the names do not conflict with standard executables, which must also be provided, and provide a separate manual page for each non-standard executable that clearly documents how it differs from the Standard Version. d. make other distribution arrangements with the Copyright Holder. 4. You may distribute the programs of this Package in object code or executable form, provided that you do at least ONE of the following: a. distribute a Standard Version of the executables and library files, together with instructions (in the manual page or equivalent) on where to get the Standard Version. b. accompany the distribution with the machine-readable source of the Package with your modifications. c. give non-standard executables non-standard names, and clearly document the differences in manual pages (or equivalent), together with instructions on where to get the Standard Version. d. make other distribution arrangements with the Copyright Holder. 5. You may charge a reasonable copying fee for any distribution of this Package. You may charge any fee you choose for support of this Package. You may not charge a fee for this Package itself. However, you may distribute this Package in aggregate with other (possibly commercial) programs as part of a larger (possibly commercial) software distribution provided that you do not a dvertise this Package as a product of your own. You may embed this Package's interpreter within an executable of yours (by linking); this shall be construed as a mere form of aggregation, provided that the complete Standard Version of the interpreter is so embedded. 6. The scripts and library files supplied as input to or produced as output from the programs of this Package do not automatically fall under the copyright of this Package, but belong to whomever generated them, and may be sold commercially, and may be aggregated with this Package. If such scripts or library files are aggregated with this Package via the so-called "undump" or "unexec" methods of producing a binary executable image, then distribution of such an image shall neither be construed as a distribution of this Package nor shall it fall under the restrictions of Paragraphs 3 and 4, provided that you do not represent such an executable image as a Standard Version of this Package. 7. C subroutines (or comparably compiled subroutines in other languages) supplied by you and linked into this Package in order to emulate subroutines and variables of the language defined by this Package shall not be considered part of this Package, but are the equivalent of input as in Paragraph 6, provided these subroutines do not change the language in any way that would cause it to fail the regression tests for the language. 8. Aggregation of this Package with a commercial distribution is always permitted provided that the use of this Package is embedded; that is, when no overt attempt is made to make this Package's interfaces visible to the end user of the commercial distribution. Such use shall not be construed as a distribution of this Package. 9. The name of the Copyright Holder may not be used to endorse or promote products derived from this software without specific prior written permission. 10. THIS PACKAGE IS PROVIDED "AS IS" AND WITHOUT ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED WARRANTIES OF MERCHANTIBILITY AND FITNESS FOR A PARTICULAR PURPOSE. The End */ #ifndef MCLEAVE_H #define MCLEAVE_H // File version: 2006-03-10 /* * mcleave is a specialty class meant to store information about protein cleavage specificity * and rapidly test a peptide sequence to see if it is cleavable. * NOTE: mcleave.h does not have a corresponding .cpp file */ class mcleave_single { public: mcleave_single(void) { strcpy(m_pNCleave,"KR"); strcpy(m_pCCleave,"P"); m_bN = true; m_bC = false; m_bNX = false; m_bCX = false; m_lType = 0; } virtual ~mcleave_single(void) { } char m_pNCleave[32]; // residues that are valid cleavage sites (or invalid if m_bN = false) char m_pCCleave[32]; // residues that are valid cleavage sites (or invalid if m_bC = false) bool m_bN; // if true, all residues in m_pNCleave can be N-temrinal to a cleavable bond bool m_bC; // if true, all residues in m_pNCleave can be C-temrinal to a cleavable bond bool m_bCX; bool m_bNX; unsigned long m_lType; string m_strCleave; mcleave_single& operator=(const mcleave_single &rhs) { strcpy(m_pNCleave,rhs.m_pNCleave); strcpy(m_pCCleave,rhs.m_pCCleave); m_bN = rhs.m_bN; m_bC = rhs.m_bC; m_bNX = rhs.m_bNX; m_bCX = rhs.m_bCX; m_lType = rhs.m_lType; return *this; } /* * load takes a string containing cleavage information and parses it * these strings take the format: * A|B, where A or B are expressions of the form [xyz] or {xyz}. if square brackets, only the single letter * abbreviations in the brackets are valid at that position for a cleavage, and if french brackets, those * single letter abbreviations are the only non-valid residues at that position. For example, trypsin * can be represented by [KR]|{P}, i.e. cleave C-terminal to a K or R residue, except when followed by * a P. The expression [X]|[X] means cleave at all residues. * NOTE: use of upper case characters is required for amino acid abbreviations */ bool load(string &_s) { m_strCleave = _s; if(_s == "[X]|[X]") { m_lType = 0x01; return true; } else if(_s == "[KR]|{P}" || _s == "[RK]|{P}") { m_lType = 0x02; return true; } m_lType = 0x04; size_t a = 0; size_t b = 0; if(_s[a] == '[') { m_bN = true; a++; b = 0; while(a < _s.size() && _s[a] != ']') { m_pNCleave[b] = _s[a]; a++; b++; } m_pNCleave[b] = '\0'; a = _s.find('|'); if(a == _s.npos) return false; a++; if(_s[a] == '{') { m_bC = false; a++; b = 0; while(a < _s.size() && _s[a] != '}') { m_pCCleave[b] = _s[a]; a++; b++; } m_pCCleave[b] = '\0'; } else if(_s[a] == '[') { m_bC = true; a++; b = 0; while(a < _s.size() && _s[a] != ']') { m_pCCleave[b] = _s[a]; a++; b++; } m_pCCleave[b] = '\0'; } } else if(_s[a] == '{') { m_bN = false; a++; b = 0; while(a < _s.size() && _s[a] != '}') { m_pNCleave[b] = _s[a]; a++; b++; } m_pNCleave[b] = '\0'; a = _s.find('|'); if(a == _s.npos) return false; a++; if(_s[a] == '{') { m_bC = false; a++; b = 0; while(a < _s.size() && _s[a] != '}') { m_pCCleave[b] = _s[a]; a++; b++; } m_pCCleave[b] = '\0'; } else if(_s[a] == '[') { m_bC = true; a++; b = 0; while(a < _s.size() && _s[a] != ']') { m_pCCleave[b] = _s[a]; a++; b++; } m_pCCleave[b] = '\0'; } } if(m_pNCleave[0] == 'X') { m_bNX = true; } if(m_pCCleave[0] == 'X') { m_bCX = true; } return true; } /* * test takes the abbreviations for the residue N-terminal to a potentially cleaved bond * and the residue C-terminal to the bond and checks to see if the bond can be cleaved * according to the rules stored in the load method. load must always be called at least once * prior to using test, or the results may be unpredictable */ bool test(const char _n,const char _c) { if(m_lType & 0x01) return true; if(m_lType & 0x02) { if(_n == 'K' || _n == 'R') { if(_c != 'P') { return true; } } return false; } bool bReturn = false; bool bN = false; bool bC = false; if(m_bNX) { bN = true; } else { if(strchr(m_pNCleave,_n)) bN = true; } if(m_bN) { bReturn = bN; } else { bReturn = !bN; } if(!bReturn) return false; if(m_bCX) { bC = true; } else { if(strchr(m_pCCleave,_c)) bC = true; } if(m_bC && bC) { return true; } else if(!m_bC && !bC) { return true; } return false; } }; class mcleave { public: mcleave(void) { m_lType = 0; m_vCleaves.clear(); m_itStart = m_vCleaves.begin(); m_itEnd = m_vCleaves.end(); } virtual ~mcleave(void) { } vector<mcleave_single> m_vCleaves; vector<mcleave_single>::iterator m_itStart; vector<mcleave_single>::iterator m_itEnd; vector<mcleave_single>::iterator m_itValue; string m_strCleave; unsigned long m_lType; /* * load takes a string containing cleavage information and parses it * these strings take the format: * A|B, where A or B are expressions of the form [xyz] or {xyz}. if square brackets, only the single letter * abbreviations in the brackets are valid at that position for a cleavage, and if french brackets, those * single letter abbreviations are the only non-valid residues at that position. For example, trypsin * can be represented by [KR]|{P}, i.e. cleave C-terminal to a K or R residue, except when followed by * a P. The expression [X]|[X] means cleave at all residues. * NOTE: use of upper case characters is required for amino acid abbreviations */ bool load(string &_s) { m_strCleave = _s; m_lType = 0x04; size_t a = 0; size_t tEnd = _s.size(); string strTemp; mcleave_single clvTemp; m_vCleaves.clear(); while(a < tEnd) { if(_s[a] == ',') { if(clvTemp.load(strTemp)) { m_vCleaves.push_back(clvTemp); } strTemp.erase(0,strTemp.size()); } else if(strchr("ABCDEFGHIJKLMNOPQRSTUVWXYZ[]{}|",_s[a])) { strTemp += _s[a]; } else if(_s[a] >= 'a' && _s[a] <= 'z') { strTemp += (char)(_s[a]-32); } a++; } if(!strTemp.empty()) { if(clvTemp.load(strTemp)) { m_vCleaves.push_back(clvTemp); } } m_itStart = m_vCleaves.begin(); m_itEnd = m_vCleaves.end(); if(m_vCleaves.size() == 1) { m_lType = m_vCleaves[0].m_lType; } return !m_vCleaves.empty(); } /* * test takes the abbreviations for the residue N-terminal to a potentially cleaved bond * and the residue C-terminal to the bond and checks to see if the bond can be cleaved * according to the rules stored in the load method. load must always be called at least once * prior to using test, or the results may be unpredictable */ bool test(const char _n,const char _c) { if(m_lType & 0x01) return true; if(m_lType & 0x02) { if(_n == 'K' || _n == 'R') { if(_c != 'P') { return true; } } return false; } m_itValue = m_itStart; while(m_itValue != m_itEnd) { if(m_itValue->test(_n,_c)) { return true; } m_itValue++; } return false; } }; #endif //ifdef MCLEAVE_H
32.023866
107
0.694738
[ "object", "vector" ]
00834cc6f3a4274933101dcad86b31c93e2f5656
373
h
C
src/wm/monitor.h
Sweets/custard
68b796c8162c0c067cd3c6e929e33fbe38f27775
[ "MIT" ]
149
2018-01-13T22:44:05.000Z
2020-07-27T16:06:23.000Z
src/wm/monitor.h
bocke/custard
68b796c8162c0c067cd3c6e929e33fbe38f27775
[ "MIT" ]
19
2018-02-18T22:59:15.000Z
2020-07-03T08:15:43.000Z
src/wm/monitor.h
Sweets/custard
68b796c8162c0c067cd3c6e929e33fbe38f27775
[ "MIT" ]
21
2018-02-18T22:49:04.000Z
2020-06-03T16:22:01.000Z
#pragma once #include "geometry.h" #include "../vector.h" extern vector_t *monitors; struct monitor { char *name; screen_geometry_t *geometry; vector_t *geometries; vector_t *configuration; unsigned int workspace; }; void setup_monitors(void); monitor_t *monitor_from_name(char*); monitor_t *monitor_with_cursor_residence(void);
18.65
48
0.699732
[ "geometry", "vector" ]
008bd2a1e109dc46ce86b5257dcfc0fbcd229b84
1,206
h
C
Source/iOSBlocksProtocol.h
renmoqiqi/iOSBlocks
fc3fea83e98478738a8052b96a742eb0b935e0ba
[ "MIT" ]
1
2015-06-10T09:28:10.000Z
2015-06-10T09:28:10.000Z
Source/iOSBlocksProtocol.h
renmoqiqi/iOSBlocks
fc3fea83e98478738a8052b96a742eb0b935e0ba
[ "MIT" ]
null
null
null
Source/iOSBlocksProtocol.h
renmoqiqi/iOSBlocks
fc3fea83e98478738a8052b96a742eb0b935e0ba
[ "MIT" ]
null
null
null
// // iOSBlocksProtocol.h // iOS Blocks // // Created by Ignacio Romero Zurbuchen on 2/12/13. // Copyright (c) 2011 DZN Labs. // Licence: MIT-Licence // /* Helper for casting weak objects to be used inside blocks or for assigning as delegates. */ static id weakObject(id object) { __block typeof(object) weakSelf = object; return weakSelf; } /* * Generic block constants for free usage over different classes. */ @protocol iOSBlocksProtocol <NSObject> typedef void (^VoidBlock)(); typedef void (^CompletionBlock)(BOOL completed); typedef void (^DismissBlock)(NSInteger buttonIndex, NSString *buttonTitle); typedef void (^PhotoPickedBlock)(UIImage *chosenImage); typedef void (^ComposeCreatedBlock)(UIViewController *controller); typedef void (^ComposeFinishedBlock)(UIViewController *controller, int result, NSError *error); typedef void (^ProgressBlock)(NSInteger connectionProgress); typedef void (^DataBlock)(NSData *data); typedef void (^SuccessBlock)(NSHTTPURLResponse *HTTPResponse); typedef void (^FailureBlock)(NSError *error); typedef void (^RowPickedBlock)(NSString *title); typedef void (^ListBlock)(NSArray *list); typedef void (^StatusBlock)(unsigned int status); @end
29.414634
95
0.757048
[ "object" ]
008c398dc892a475be5a8c84bf7064ee82552b4c
2,433
h
C
src/gfx/mg_mesh_internal.h
Magnutic/mg-engine
09862497bf99198281acc8227b135777491c58d3
[ "BSD-3-Clause" ]
null
null
null
src/gfx/mg_mesh_internal.h
Magnutic/mg-engine
09862497bf99198281acc8227b135777491c58d3
[ "BSD-3-Clause" ]
null
null
null
src/gfx/mg_mesh_internal.h
Magnutic/mg-engine
09862497bf99198281acc8227b135777491c58d3
[ "BSD-3-Clause" ]
null
null
null
//************************************************************************************************** // This file is part of Mg Engine. Copyright (c) 2020, Magnus Bergsten. // Mg Engine is made available under the terms of the 3-Clause BSD License. // See LICENSE.txt in the project's root directory. //************************************************************************************************** /** @file mg_mesh_internal.h * Internal mesh structure. @see MeshPool */ #pragma once #include "mg/containers/mg_small_vector.h" #include "mg/core/mg_identifier.h" #include "mg/gfx/mg_gfx_object_handles.h" #include "mg/gfx/mg_mesh_data.h" #include "mg/gfx/mg_mesh_handle.h" #include <glm/vec3.hpp> #include <cstdint> #include <cstring> namespace Mg::gfx { // Vertex and index buffers may be shared between multiple meshes. // This structure lets us keep track of how many meshes are using a given buffer, so that we can // know when it is safe to destroy. struct SharedBuffer { BufferHandle handle; int32_t num_users = 0; }; /** Internal mesh structure. @see MeshPool */ struct MeshInternal { /** Submeshes, defined as ranges in the index_buffer. */ small_vector<Mesh::SubmeshRange, 8> submeshes; /** Bounding sphere used for frustum culling. */ BoundingSphere bounding_sphere; /** Mesh identifier, for debugging purposes. */ Identifier name{ "" }; /** Identifier for the mesh buffers in the graphics API. */ VertexArrayHandle vertex_array; /** Vertex data buffer. */ SharedBuffer* vertex_buffer = nullptr; /** Index buffer, triangle list of indexes into vertex_buffer. */ SharedBuffer* index_buffer = nullptr; /** Buffer for per-vertex joint influences, for skeletal animation. May be nullptr. */ SharedBuffer* influences_buffer = nullptr; }; /** Convert pointer to public opaque handle. */ inline MeshHandle make_mesh_handle(const MeshInternal* p) noexcept { MeshHandle handle{}; static_assert(sizeof(handle) >= sizeof(p)); // NOLINT(bugprone-sizeof-expression) std::memcpy(&handle, &p, sizeof(p)); // NOLINT(bugprone-sizeof-expression) return handle; } /** Dereference mesh handle. */ inline MeshInternal& get_mesh(MeshHandle handle) noexcept { MeshInternal* p = nullptr; std::memcpy(&p, &handle, sizeof(p)); // NOLINT(bugprone-sizeof-expression) MG_ASSERT(p != nullptr); return *p; } } // namespace Mg::gfx
31.192308
100
0.650637
[ "mesh" ]
008cab229fda98f13e18e9eb2070fb8459a12155
2,398
h
C
qg/model/ObsVecQG.h
andreapiacentini/oops
48c923c210a75773e2457eea8b1a8eee29837bb5
[ "Apache-2.0" ]
2
2021-03-10T18:33:19.000Z
2022-01-05T08:37:31.000Z
qg/model/ObsVecQG.h
andreapiacentini/oops
48c923c210a75773e2457eea8b1a8eee29837bb5
[ "Apache-2.0" ]
3
2020-10-30T21:38:31.000Z
2020-11-02T18:14:29.000Z
qg/model/ObsVecQG.h
andreapiacentini/oops
48c923c210a75773e2457eea8b1a8eee29837bb5
[ "Apache-2.0" ]
6
2017-08-03T23:36:57.000Z
2017-09-15T15:14:17.000Z
/* * (C) Copyright 2009-2016 ECMWF. * (C) Copyright 2017-2019 UCAR. * * This software is licensed under the terms of the Apache Licence Version 2.0 * which can be obtained at http://www.apache.org/licenses/LICENSE-2.0. * In applying this licence, ECMWF does not waive the privileges and immunities * granted to it by virtue of its status as an intergovernmental organisation nor * does it submit to any jurisdiction. */ #ifndef QG_MODEL_OBSVECQG_H_ #define QG_MODEL_OBSVECQG_H_ #include <Eigen/Dense> #include <ostream> #include <string> #include "oops/util/ObjectCounter.h" #include "oops/util/Printable.h" #include "oops/qg/QgFortran.h" namespace qg { class ObsSpaceQG; template <typename DATATYPE> class ObsDataQG; // ----------------------------------------------------------------------------- /// ObsVecQG class to handle vectors in observation space for QG model. class ObsVecQG : public util::Printable, private util::ObjectCounter<ObsVecQG> { public: static const std::string classname() {return "qg::ObsVecQG";} ObsVecQG(const ObsSpaceQG &, const std::string & name = ""); ObsVecQG(const ObsVecQG &); ~ObsVecQG(); ObsVecQG & operator = (const ObsVecQG &); ObsVecQG & operator*= (const double &); ObsVecQG & operator+= (const ObsVecQG &); ObsVecQG & operator-= (const ObsVecQG &); ObsVecQG & operator*= (const ObsVecQG &); ObsVecQG & operator/= (const ObsVecQG &); Eigen::VectorXd packEigen(const ObsVecQG &) const; size_t packEigenSize(const ObsVecQG &) const; size_t size() const; /// set all values to zero void zero(); /// set \p i-th value to missing value void setToMissing(int i); /// set all values to one void ones(); void axpy(const double &, const ObsVecQG &); void invert(); void random(); double dot_product_with(const ObsVecQG &) const; double rms() const; void mask(const ObsDataQG<int> &); void mask(const ObsVecQG &); ObsVecQG & operator=(const ObsDataQG<float> &); unsigned int nobs() const; const int & toFortran() const {return keyOvec_;} // I/O void save(const std::string &) const; void read(const std::string &); private: void print(std::ostream &) const; const ObsSpaceQG & obsdb_; F90ovec keyOvec_; }; // ----------------------------------------------------------------------------- } // namespace qg #endif // QG_MODEL_OBSVECQG_H_
27.883721
81
0.648457
[ "model" ]
0091e4afbac869e0ab996aa6ffd707ceddbc9826
3,167
c
C
ext/mxnet/utils.c
cyrilleberger/mxnet.rb
edc85f60baa51cab0b9bcecd307e1fefaacbcbf4
[ "MIT" ]
54
2017-08-29T00:07:17.000Z
2021-01-18T07:02:37.000Z
ext/mxnet/utils.c
cyrilleberger/mxnet.rb
edc85f60baa51cab0b9bcecd307e1fefaacbcbf4
[ "MIT" ]
46
2017-10-22T10:04:06.000Z
2020-12-14T22:00:05.000Z
ext/mxnet/utils.c
cyrilleberger/mxnet.rb
edc85f60baa51cab0b9bcecd307e1fefaacbcbf4
[ "MIT" ]
10
2018-01-19T16:55:27.000Z
2020-12-22T13:07:01.000Z
#include "mxnet_internal.h" struct enumerator_head { VALUE obj; ID meth; VALUE args; }; static int obj_is_step_range(VALUE obj) { struct enumerator_head *eh; if (!RB_TYPE_P(obj, T_DATA)) { return 0; } if (!rb_obj_is_kind_of(obj, rb_cEnumerator)) { return 0; } eh = (struct enumerator_head *)DATA_PTR(obj); if (!rb_obj_is_kind_of(eh->obj, rb_cRange)) { return 0; } if (eh->meth == rb_intern("step")) { if (!RB_TYPE_P(eh->args, T_ARRAY)) { return 0; } return (RARRAY_LEN(eh->args) == 1); } return 0; } static int extract_range(VALUE obj, VALUE *pbegin, VALUE *pend, int *pexclude_end, VALUE *pstep) { ID id_begin, id_end, id_exclude_end; VALUE begin, end, exclude_end, step = Qnil; CONST_ID(id_begin, "begin"); CONST_ID(id_end, "end"); CONST_ID(id_exclude_end, "exclude_end?"); if (rb_obj_is_kind_of(obj, rb_cRange)) { begin = rb_funcallv(obj, id_begin, 0, 0); end = rb_funcallv(obj, id_end, 0, 0); exclude_end = rb_funcallv(obj, id_exclude_end, 0, 0); } else if (obj_is_step_range(obj)) { struct enumerator_head *eh = (struct enumerator_head *)DATA_PTR(obj); begin = rb_funcallv(eh->obj, id_begin, 0, 0); end = rb_funcallv(eh->obj, id_end, 0, 0); exclude_end = rb_funcallv(eh->obj, id_exclude_end, 0, 0); step = RARRAY_AREF(eh->args, 0); } else { return 0; } if (pbegin) *pbegin = begin; if (pend) *pend = end; if (pexclude_end) *pexclude_end = RTEST(exclude_end); if (pstep) *pstep = step; return 1; } /* Decompose start, stop, and step components from a slice-like object. * These components are interpreted as the components of Python's slice. */ static VALUE utils_m_decompose_slice(VALUE mod, VALUE slice_like) { VALUE begin, end, step = Qnil, components; int exclude_end; if (rb_obj_is_kind_of(slice_like, rb_cRange)) { extract_range(slice_like, &begin, &end, &exclude_end, NULL); } else if (obj_is_step_range(slice_like)) { extract_range(slice_like, &begin, &end, &exclude_end, &step); } else { rb_raise(rb_eTypeError, "unexpected argument type %s (expected Range or Enumerator generated by Range#step)", rb_class2name(CLASS_OF(slice_like))); } if (!NIL_P(step) && NUM2SSIZET(step) < 0) { if (!NIL_P(end)) { if (!exclude_end) { ssize_t end_i = NUM2SSIZET(end); if (end_i == 0) { end = Qnil; } else { end = SSIZET2NUM(end_i - 1); /* TODO: limit check */ } } } } else if (!NIL_P(end)) { if (!exclude_end) { ssize_t end_i = NUM2SSIZET(end); if (end_i == -1) { end = Qnil; } else { end = SSIZET2NUM(end_i + 1); /* TODO: limit check */ } } } components = rb_ary_new_capa(3); rb_ary_push(components, begin); rb_ary_push(components, end); rb_ary_push(components, step); return components; } void mxnet_init_utils(void) { VALUE mUtils; mUtils = rb_define_module_under(mxnet_mMXNet, "Utils"); rb_define_module_function(mUtils, "decompose_slice", utils_m_decompose_slice, 1); }
23.992424
113
0.629618
[ "object" ]
0092bc2401affc72a6afc1f1924cc5f156ec2a2d
34,075
h
C
Chapter5/Main/hgt-qfunc.v.0.5.2/deps/simdpp/simd/memory_load.h
dunarel/dunphd-thesis
7c6286b5134024a8a67f97c4bfba8d6b94dc21c9
[ "BSD-3-Clause" ]
null
null
null
Chapter5/Main/hgt-qfunc.v.0.5.2/deps/simdpp/simd/memory_load.h
dunarel/dunphd-thesis
7c6286b5134024a8a67f97c4bfba8d6b94dc21c9
[ "BSD-3-Clause" ]
null
null
null
Chapter5/Main/hgt-qfunc.v.0.5.2/deps/simdpp/simd/memory_load.h
dunarel/dunphd-thesis
7c6286b5134024a8a67f97c4bfba8d6b94dc21c9
[ "BSD-3-Clause" ]
null
null
null
/* libsimdpp Copyright (C) 2011-2012 Povilas Kanapickas tir5c3@yahoo.co.uk 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. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #ifndef LIBSIMDPP_SIMD_MEMORY_LOAD_H #define LIBSIMDPP_SIMD_MEMORY_LOAD_H #ifndef LIBSIMDPP_SIMD_H #error "This file must be included through simd.h" #endif #include <simdpp/simd/types.h> #include <simdpp/simd/transpose.h> #include <simdpp/simd/detail/align.h> #include <simdpp/simd/detail/mem_unpack.h> #include <simdpp/null/memory.h> namespace simdpp { #ifndef DOXYGEN_SHOULD_SKIP_THIS namespace SIMDPP_ARCH_NAMESPACE { #endif /// @defgroup simd_load Operations: load from memory to register /// @{ /// @{ /** Loads a 128-bit or 256-bit integer, 32-bit or 64-bit float vector from an aligned memory location. @par 128-bit version: @code a[0..127] = *(p) @endcode @a p must be aligned to 16 bytes. @par 256-bit version: @code a[0..255] = *(p) @endcode @a p must be aligned to 32 bytes. @icost{SSE2-SSE4.1, NEON, ALTIVEC, 2} @icost{AVX (integer vectors), 2} */ inline int128 load(int128& a, const void* p) { p = detail::assume_aligned(p, 16); #if SIMDPP_USE_NULL null::load(a, p); return a; #elif SIMDPP_USE_SSE2 a = _mm_load_si128(reinterpret_cast<const __m128i*>(p)); return a; #elif SIMDPP_USE_NEON a = vreinterpretq_u32_u64(vld1q_u64(reinterpret_cast<const uint64_t*>(p))); return a; #elif SIMDPP_USE_ALTIVEC a = vec_ldl(0, reinterpret_cast<const uint8_t*>(p)); return a; #endif } inline int256 load(int256& a, const void* p) { p = detail::assume_aligned(p, 32); #if SIMDPP_USE_AVX2 a = _mm256_load_si256(reinterpret_cast<const __m256i*>(p)); return a; #else const char* q = reinterpret_cast<const char*>(p); a = int256{load(a[0], q), load(a[1], q+16)}; return a; #endif } inline float32x4 load(float32x4& a, const float* p) { p = detail::assume_aligned(p, 16); #if SIMDPP_USE_NULL null::load(a, p); return a; #elif SIMDPP_USE_SSE2 a = _mm_load_ps(p); return a; #elif SIMDPP_USE_NEON a = vld1q_f32(p); return a; #elif SIMDPP_USE_ALTIVEC a = vec_ldl(0, p); return a; #endif } inline float32x8 load(float32x8& a, const float* p) { p = detail::assume_aligned(p, 32); #if SIMDPP_USE_AVX a = _mm256_load_ps(p); return a; #else a = float32x8{load(a[0], p), load(a[1], p+4)}; return a; #endif } inline float64x2 load(float64x2& a, const double* p) { p = detail::assume_aligned(p, 16); #if SIMDPP_USE_NULL || SIMDPP_USE_ALTIVEC || SIMDPP_USE_NEON null::load(a, p); return a; #elif SIMDPP_USE_SSE2 a = _mm_load_pd(p); return a; #endif } inline float64x4 load(float64x4& a, const double* p) { p = detail::assume_aligned(p, 32); #if SIMDPP_USE_AVX a = _mm256_load_pd(p); return a; #else a = float64x4{load(a[0], p), load(a[1], p+2)}; return a; #endif } /// @} /// @{ /** Loads a 128-bit or 256-bit integer, 32-bit or 64-bit float vector from an unaligned memory location. @par 128-bit version: @code a[0..127] = *(p) @endcode @a p must be aligned to the element size. If @a p is aligned to 16 bytes only the referenced 16 byte block is accessed. Otherwise, memory within the smallest 16-byte aligned 32-byte block may be accessed. @icost{ALTIVEC, 4} @par 256-bit version: @code a[0..255] = *(p) @endcode @a p must be aligned to 32 bytes. @icost{SSE2-SSE4.1, NEON, 2} @icost{ALTIVEC, 6} @a p must be aligned to the element size. If @a p is aligned to 32 bytes only the referenced 16 byte block is accessed. Otherwise, memory within the smallest 32-byte aligned 64-byte block may be accessed. */ // Each integer type is handled separately because higher aligment guarantees // offer better performance on e.g. ARM. Note, we don't use LDDQU on SSE, // because it has usage restrictions and offers improved performance only on // Pentium 4 era processors. inline basic_int8x16 load_u(basic_int8x16& a, const void* p) { #if SIMDPP_USE_NULL null::load(a, p); return a; #elif SIMDPP_USE_SSE2 a = _mm_loadu_si128(reinterpret_cast<const __m128i*>(p)); return a; #elif SIMDPP_USE_NEON a = vld1q_u8(reinterpret_cast<const uint8_t*>(p)); return a; #elif SIMDPP_USE_ALTIVEC const uint8_t* q = reinterpret_cast<const uint8_t*>(p); uint8x16 l1, l2, mask; l1 = vec_ldl(0, q); l2 = vec_ldl(16, q); mask = vec_lvsl(0, q); l1 = vec_perm((__vector uint8_t)l1, (__vector uint8_t)l2, (__vector uint8_t)mask); return l1; #endif } inline basic_int16x8 load_u(basic_int16x8& a, const void* p) { #if SIMDPP_USE_NULL || SIMDPP_USE_SSE2 || SIMDPP_USE_ALTIVEC uint8x16 b = load_u(b, p); a = b; return a; #elif SIMDPP_USE_NEON a = vld1q_u16(reinterpret_cast<const uint16_t*>(p)); return a; #endif } inline basic_int32x4 load_u(basic_int32x4& a, const void* p) { #if SIMDPP_USE_NULL || SIMDPP_USE_SSE2 || SIMDPP_USE_ALTIVEC uint8x16 b = load_u(b, p); a = b; return a; #elif SIMDPP_USE_NEON a = vld1q_u32(reinterpret_cast<const uint32_t*>(p)); return a; #endif } inline basic_int64x2 load_u(basic_int64x2& a, const void* p) { #if SIMDPP_USE_NULL || SIMDPP_USE_SSE2 || SIMDPP_USE_ALTIVEC uint8x16 b = load_u(b, p); a = b; return a; #elif SIMDPP_USE_NEON a = vld1q_u64(reinterpret_cast<const uint64_t*>(p)); return a; #endif } inline float32x4 load_u(float32x4& a, const float* p) { #if SIMDPP_USE_NULL null::load(a, p); return a; #elif SIMDPP_USE_SSE2 a = _mm_loadu_ps(p); return a; #elif SIMDPP_USE_NEON a = vld1q_f32(p); return a; #elif SIMDPP_USE_ALTIVEC uint32x4 b = load_u(b, reinterpret_cast<const uint32_t*>(p)); a = b; return a; #endif } inline float64x2 load_u(float64x2& a, const double* p) { #if SIMDPP_USE_NULL || SIMDPP_USE_ALTIVEC || SIMDPP_USE_NEON null::load(a, p); return a; #elif SIMDPP_USE_SSE2 a = _mm_loadu_pd(p); return a; #else return SIMDPP_NOT_IMPLEMENTED2(a, p); #endif } inline basic_int8x32 load_u(basic_int8x32& a, const void* p) { #if SIMDPP_USE_AVX2 a = _mm256_loadu_si256(reinterpret_cast<const __m256i*>(p)); return a; #elif SIMDPP_USE_ALTIVEC const uint8_t* q = reinterpret_cast<const uint8_t*>(p); uint8x16 l1, l2, l3, mask; l1 = vec_ldl(0, q); l2 = vec_ldl(16, q); l3 = vec_ldl(32, q); mask = vec_lvsl(0, q); l1 = vec_perm((__vector uint8_t)l1, (__vector uint8_t)l2, (__vector uint8_t)mask); l2 = vec_perm((__vector uint8_t)l2, (__vector uint8_t)l3, (__vector uint8_t)mask); return basic_int8x32(l1, l2); #else const char* q = reinterpret_cast<const char*>(p); load_u(a[0], q); load_u(a[1], q+16); return a; #endif } inline basic_int16x16 load_u(basic_int16x16& a, const void* p) { #if SIMDPP_USE_AVX2 a = _mm256_loadu_si256(reinterpret_cast<const __m256i*>(p)); return a; #elif SIMDPP_USE_ALTIVEC basic_int8x32 a0; load_u(a0, p); a = a0; return a; #else const char* q = reinterpret_cast<const char*>(p); load_u(a[0], q); load_u(a[1], q+16); return a; #endif } inline basic_int32x8 load_u(basic_int32x8& a, const void* p) { #if SIMDPP_USE_AVX2 a = _mm256_loadu_si256(reinterpret_cast<const __m256i*>(p)); return a; #elif SIMDPP_USE_ALTIVEC basic_int8x32 a0; load_u(a0, p); a = a0; return a; #else const char* q = reinterpret_cast<const char*>(p); load_u(a[0], q); load_u(a[1], q+16); return a; #endif } inline basic_int64x4 load_u(basic_int64x4& a, const void* p) { #if SIMDPP_USE_AVX2 a = _mm256_loadu_si256(reinterpret_cast<const __m256i*>(p)); return a; #elif SIMDPP_USE_ALTIVEC basic_int8x32 a0; load_u(a0, p); a = a0; return a; #else const char* q = reinterpret_cast<const char*>(p); load_u(a[0], q); load_u(a[1], q+16); return a; #endif } inline float32x8 load_u(float32x8& a, const float* p) { #if SIMDPP_USE_AVX a = _mm256_loadu_ps(p); return a; #elif SIMDPP_USE_ALTIVEC basic_int32x8 a0; load_u(a0, p); a = a0; return a; #else load_u(a[0], p); load_u(a[1], p+4); return a; #endif } inline float64x4 load_u(float64x4& a, const double* p) { #if SIMDPP_USE_AVX a = _mm256_loadu_pd(p); return a; #else load_u(a[0], p); load_u(a[1], p+2); return a; #endif } /// @} namespace detail { // the 256-bit versions are mostly boilerplate. Collect that stuff here. template<class V> void v256_load_i_packed2(V& a, V& b, const void* p) { p = detail::assume_aligned(p, 32); const char* q = reinterpret_cast<const char*>(p); #if SIMDPP_USE_AVX2 load(a, q); load(b, q + 32); detail::mem_unpack2(a, b); #else load_packed2(a[0], b[0], q); load_packed2(a[1], b[1], q + 32); #endif } template<class V> void v256_load_i_packed3(V& a, V& b, V& c, const void* p) { p = detail::assume_aligned(p, 32); const char* q = reinterpret_cast<const char*>(p); #if SIMDPP_USE_AVX2 load(a, q); load(b, q + 32); load(c, q + 64); detail::mem_unpack3(a, b, c); #else load_packed3(a[0], b[0], c[0], q); load_packed3(a[1], b[1], c[1], q + 48); #endif } template<class V> void v256_load_i_packed4(V& a, V& b, V& c, V& d, const void* p) { p = detail::assume_aligned(p, 32); const char* q = reinterpret_cast<const char*>(p); #if SIMDPP_USE_AVX2 load(a, q); load(b, q + 32); load(c, q + 64); load(d, q + 96); detail::mem_unpack4(a, b, c, d); #else load_packed4(a[0], b[0], c[0], d[0], q); load_packed4(a[1], b[1], c[1], d[1], q + 64); #endif } } // namespace detail /// @{ /** Loads 8-bit values packed in pairs, de-interleaves them and stores the result into two vectors. @par 128-bit version: @code a = [ *(p), *(p+2), *(p+4), ... , *(p+30) ] b = [ *(p+1), *(p+3), *(p+5), ... , *(p+31) ] @endcode @a p must be aligned to 16 bytes. @par 256-bit version: @code a = [ *(p), *(p+2), *(p+4), ... , *(p+62) ] b = [ *(p+1), *(p+3), *(p+5), ... , *(p+63) ] @endcode @a p must be aligned to 32 bytes. */ inline void load_packed2(basic_int8x16& a, basic_int8x16& b, const void* p) { p = detail::assume_aligned(p, 16); #if SIMDPP_USE_NULL null::load_packed2(a, b, p); #elif SIMDPP_USE_SSE2 || SIMDPP_USE_ALTIVEC const char* q = reinterpret_cast<const char*>(p); load(a, q); load(b, q+16); detail::mem_unpack2(a, b); #elif SIMDPP_USE_NEON auto r = vld2q_u8(reinterpret_cast<const uint8_t*>(p)); a = r.val[0]; b = r.val[1]; #endif } inline void load_packed2(basic_int8x32& a, basic_int8x32& b, const void* p) { detail::v256_load_i_packed2(a, b, p); } /// @} /// @{ /** Loads 16-bit values packed in pairs, de-interleaves them and stores the result into two vectors. @par 128-bit version: @code a = [ *(p), *(p+2), *(p+4), ... , *(p+14) ] b = [ *(p+1), *(p+3), *(p+5), ... , *(p+15) ] @endcode @a p must be aligned to 16 bytes. @par 256-bit version: @code a = [ *(p), *(p+2), *(p+4), ... , *(p+30) ] b = [ *(p+1), *(p+3), *(p+5), ... , *(p+31) ] @endcode @a p must be aligned to 32 bytes. */ inline void load_packed2(basic_int16x8& a, basic_int16x8& b, const void* p) { p = detail::assume_aligned(p, 16); #if SIMDPP_USE_NULL null::load_packed2(a, b, p); #elif SIMDPP_USE_SSE2 || SIMDPP_USE_ALTIVEC const char* q = reinterpret_cast<const char*>(p); load(a, q); load(b, q+16); detail::mem_unpack2(a, b); #elif SIMDPP_USE_NEON auto r = vld2q_u16(reinterpret_cast<const uint16_t*>(p)); a = r.val[0]; b = r.val[1]; #endif } inline void load_packed2(basic_int16x16& a, basic_int16x16& b, const void* p) { detail::v256_load_i_packed2(a, b, p); } /// @} /// @{ /** Loads 32-bit values packed in pairs, de-interleaves them and stores the result into two vectors. @par 128-bit version: @code a = [ *(p), *(p+2), *(p+4), *(p+6) ] b = [ *(p+1), *(p+3), *(p+5), *(p+7) ] @endcode @a p must be aligned to 16 bytes. @par 256-bit version: @code a = [ *(p), *(p+2), *(p+4), ... , *(p+14) ] b = [ *(p+1), *(p+3), *(p+5), ... , *(p+15) ] @endcode @a p must be aligned to 32 bytes. */ inline void load_packed2(basic_int32x4& a, basic_int32x4& b, const void* p) { p = detail::assume_aligned(p, 16); #if SIMDPP_USE_NULL null::load_packed2(a, b, p); #elif SIMDPP_USE_SSE2 || SIMDPP_USE_ALTIVEC const char* q = reinterpret_cast<const char*>(p); load(a, q); load(b, q+16); detail::mem_unpack2(a, b); #elif SIMDPP_USE_NEON auto r = vld2q_u32(reinterpret_cast<const uint32_t*>(p)); a = r.val[0]; b = r.val[1]; #endif } inline void load_packed2(basic_int32x8& a, basic_int32x8& b, const void* p) { detail::v256_load_i_packed2(a, b, p); } /// @} /// @{ /** Loads 64-bit values packed in pairs, de-interleaves them and stores the result into two vectors. @par 128-bit version: @code a = [ *(p), *(p+2) ] b = [ *(p+1), *(p+3) ] @endcode @a p must be aligned to 16 bytes. @par 256-bit version: @code a = [ *(p), *(p+2), *(p+4), *(p+14) ] b = [ *(p+1), *(p+3), *(p+5), *(p+15) ] @endcode @a p must be aligned to 32 bytes. */ inline void load_packed2(basic_int64x2& a, basic_int64x2& b, const void* p) { p = detail::assume_aligned(p, 16); const char* q = reinterpret_cast<const char*>(p); a = load(a, q); b = load(b, q+16); transpose2(a, b); } inline void load_packed2(basic_int64x4& a, basic_int64x4& b, const void* p) { detail::v256_load_i_packed2(a, b, p); } /// @} /// @} /** Loads 32-bit float values packed in pairs, de-interleaves them and stores the result into two vectors. @par 128-bit version: @code a = [ *(p), *(p+2), *(p+4), ... , *(p+6) ] b = [ *(p+1), *(p+3), *(p+5), ... , *(p+7) ] @endcode @a p must be aligned to 16 bytes. @par 256-bit version: @code a = [ *(p), *(p+2), *(p+4), ... , *(p+14) ] b = [ *(p+1), *(p+3), *(p+5), ... , *(p+15) ] @endcode @a p must be aligned to 32 bytes. */ inline void load_packed2(float32x4& a, float32x4& b, const float* p) { p = detail::assume_aligned(p, 16); #if SIMDPP_USE_NULL null::load_packed2(a, b, p); #elif SIMDPP_USE_SSE2 || SIMDPP_USE_ALTIVEC load(a, p); load(b, p+4); detail::mem_unpack2(a, b); #elif SIMDPP_USE_NEON auto r = vld2q_f32(p); a = r.val[0]; b = r.val[1]; #endif } inline void load_packed2(float32x8& a, float32x8& b, const float* p) { p = detail::assume_aligned(p, 32); #if SIMDPP_USE_AVX load(a, p); load(b, p + 8); detail::mem_unpack2(a, b); #else load_packed2(a[0], b[0], p); load_packed2(a[1], b[1], p + 8); #endif } /// @} /// @{ /** Loads 64-bit float values packed in pairs, de-interleaves them and stores the result into two vectors. @par 128-bit version: @code a = [ *(p), *(p+2) ] b = [ *(p+1), *(p+3) ] @endcode @a p must be aligned to 16 bytes. @par 256-bit version: @code a = [ *(p), *(p+2), *(p+4), *(p+14) ] b = [ *(p+1), *(p+3), *(p+5), *(p+15) ] @endcode @a p must be aligned to 32 bytes. */ inline void load_packed2(float64x2& a, float64x2& b, const double* p) { p = detail::assume_aligned(p, 16); a = load(a, p); b = load(b, p+2); transpose2(a, b); } inline void load_packed2(float64x4& a, float64x4& b, const double* p) { p = detail::assume_aligned(p, 32); #if SIMDPP_USE_AVX load(a, p); load(b, p + 4); detail::mem_unpack2(a, b); #else load_packed2(a[0], b[0], p); load_packed2(a[1], b[1], p + 4); #endif } /// @} /// @{ /** Loads 8-bit values packed in triplets, de-interleaves them and stores the result into three vectors. @par 128-bit version: @code a = [ *(p), *(p+3), *(p+6), ... , *(p+45) ] b = [ *(p+1), *(p+4), *(p+7), ... , *(p+46) ] c = [ *(p+2), *(p+5), *(p+8), ... , *(p+47) ] @endcode @a p must be aligned to 16 bytes. @par 256-bit version: @code a = [ *(p), *(p+3), *(p+6), ... , *(p+93) ] b = [ *(p+1), *(p+4), *(p+7), ... , *(p+94) ] c = [ *(p+2), *(p+5), *(p+8), ... , *(p+95) ] @endcode @a p must be aligned to 32 bytes. */ inline void load_packed3(basic_int8x16& a, basic_int8x16& b, basic_int8x16& c, const void* p) { p = detail::assume_aligned(p, 16); #if SIMDPP_USE_NULL null::load_packed3(a, b, c, p); #elif SIMDPP_USE_SSE2 || SIMDPP_USE_ALTIVEC const char* q = reinterpret_cast<const char*>(p); load(a, q); load(b, q+16); load(c, q+32); detail::mem_unpack3(a, b, c); #elif SIMDPP_USE_NEON auto r = vld3q_u8(reinterpret_cast<const uint8_t*>(p)); a = r.val[0]; b = r.val[1]; c = r.val[2]; #endif } inline void load_packed3(basic_int8x32& a, basic_int8x32& b, basic_int8x32& c, const void* p) { detail::v256_load_i_packed3(a, b, c, p); } /// @} /// @{ /** Loads 16-bit values packed in triplets, de-interleaves them and stores the result into three vectors. @par 128-bit version: @code a = [ *(p), *(p+3), *(p+6), ... , *(p+21) ] b = [ *(p+1), *(p+4), *(p+7), ... , *(p+22) ] c = [ *(p+2), *(p+5), *(p+8), ... , *(p+23) ] @endcode @a p must be aligned to 16 bytes. @par 256-bit version: @code a = [ *(p), *(p+3), *(p+6), ... , *(p+45) ] b = [ *(p+1), *(p+4), *(p+7), ... , *(p+46) ] c = [ *(p+2), *(p+5), *(p+8), ... , *(p+47) ] @endcode @a p must be aligned to 32 bytes. */ inline void load_packed3(basic_int16x8& a, basic_int16x8& b, basic_int16x8& c, const void* p) { p = detail::assume_aligned(p, 16); #if SIMDPP_USE_NULL null::load_packed3(a, b, c, p); #elif SIMDPP_USE_SSE2 || SIMDPP_USE_ALTIVEC const char* q = reinterpret_cast<const char*>(p); load(a, q); load(b, q+16); load(c, q+32); detail::mem_unpack3(a, b, c); #elif SIMDPP_USE_NEON auto r = vld3q_u16(reinterpret_cast<const uint16_t*>(p)); a = r.val[0]; b = r.val[1]; c = r.val[2]; #endif } inline void load_packed3(basic_int16x16& a, basic_int16x16& b, basic_int16x16& c, const void* p) { detail::v256_load_i_packed3(a, b, c, p); } /// @} /// @{ /** Loads 32-bit values packed in triplets, de-interleaves them and stores the result into three vectors. @par 128-bit version: @code a = [ *(p), *(p+3), *(p+6), *(p+9) ] b = [ *(p+1), *(p+4), *(p+7), *(p+10) ] c = [ *(p+2), *(p+5), *(p+8), *(p+11) ] @endcode @a p must be aligned to 16 bytes. @par 256-bit version: @code a = [ *(p), *(p+3), *(p+6), ... , *(p+21) ] b = [ *(p+1), *(p+4), *(p+7), ... , *(p+22) ] c = [ *(p+2), *(p+5), *(p+8), ... , *(p+23) ] @endcode @a p must be aligned to 32 bytes. */ inline void load_packed3(basic_int32x4& a, basic_int32x4& b, basic_int32x4&c, const void* p) { p = detail::assume_aligned(p, 16); #if SIMDPP_USE_NULL null::load_packed3(a, b, c, p); #elif SIMDPP_USE_SSE2 || SIMDPP_USE_ALTIVEC const char* q = reinterpret_cast<const char*>(p); load(a, q); load(b, q+16); load(c, q+32); detail::mem_unpack3(a, b, c); #elif SIMDPP_USE_NEON auto r = vld3q_u32(reinterpret_cast<const uint32_t*>(p)); a = r.val[0]; b = r.val[1]; c = r.val[2]; #endif } inline void load_packed3(basic_int32x8& a, basic_int32x8& b, basic_int32x8& c, const void* p) { detail::v256_load_i_packed3(a, b, c, p); } /// @} /// @{ /** Loads 64-bit values packed in triplets, de-interleaves them and stores the result into three vectors. @par 128-bit version: @code a = [ *(p), *(p+3) ] b = [ *(p+1), *(p+4) ] c = [ *(p+2), *(p+5) ] @endcode @a p must be aligned to 16 bytes. @par 256-bit version: @code a = [ *(p), *(p+3), *(p+6), *(p+9) ] b = [ *(p+1), *(p+4), *(p+7), *(p+10) ] c = [ *(p+2), *(p+5), *(p+8), *(p+11) ] @endcode @a p must be aligned to 32 bytes. */ inline void load_packed3(basic_int64x2& a, basic_int64x2& b, basic_int64x2& c, const void* p) { p = detail::assume_aligned(p, 16); #if SIMDPP_USE_NULL null::load_packed3(a, b, c, p); #elif SIMDPP_USE_SSE2 || SIMDPP_USE_ALTIVEC const char* q = reinterpret_cast<const char*>(p); load(a, q); load(b, q+16); load(c, q+32); detail::mem_unpack3(a, b, c); #elif SIMDPP_USE_NEON const char* q = reinterpret_cast<const char*>(p); uint64x2 a0, b0, c0; a0 = load(a0, q); b0 = load(b0, q+16); c0 = load(c0, q+32); int64x1_t al, bl, cl, ah, bh, ch; al = vget_low_u64(a0); ah = vget_high_u64(a0); bl = vget_low_u64(b0); bh = vget_high_u64(b0); cl = vget_low_u64(c0); ch = vget_high_u64(c0); a = vcombine_u64(al, bh); b = vcombine_u64(ah, cl); c = vcombine_u64(bl, ch); #endif } inline void load_packed3(basic_int64x4& a, basic_int64x4& b, basic_int64x4& c, const void* p) { detail::v256_load_i_packed3(a, b, c, p); } /// @} /// @{ /** Loads 32-bit floating point values packed in triplets, de-interleaves them and stores the result into three vectors. @par 128-bit version: @code a = [ *(p), *(p+3), *(p+6), *(p+9) ] b = [ *(p+1), *(p+4), *(p+7), *(p+10) ] c = [ *(p+2), *(p+5), *(p+8), *(p+11) ] @endcode @a p must be aligned to 16 bytes. @par 256-bit version: @code a = [ *(p), *(p+3), *(p+6), ... , *(p+21) ] b = [ *(p+1), *(p+4), *(p+7), ... , *(p+22) ] c = [ *(p+2), *(p+5), *(p+8), ... , *(p+23) ] @endcode @a p must be aligned to 32 bytes. */ inline void load_packed3(float32x4& a, float32x4& b, float32x4& c, const float* p) { p = detail::assume_aligned(p, 16); #if SIMDPP_USE_NULL null::load_packed3(a, b, c, p); #elif SIMDPP_USE_SSE2 || SIMDPP_USE_ALTIVEC load(a, p); load(b, p+4); load(c, p+8); detail::mem_unpack3(a, b, c); #elif SIMDPP_USE_NEON auto r = vld3q_f32(p); a = r.val[0]; b = r.val[1]; c = r.val[2]; #endif } inline void load_packed3(float32x8& a, float32x8& b, float32x8& c, const float* p) { p = detail::assume_aligned(p, 32); #if SIMDPP_USE_AVX load(a, p); load(b, p + 8); load(c, p + 16); detail::mem_unpack3(a, b, c); #else load_packed3(a[0], b[0], c[0], p); load_packed3(a[1], b[1], c[1], p + 12); #endif } /// @} /// @{ /** Loads 64-bit floating point values packed in triplets, de-interleaves them and stores the result into three vectors. @par 128-bit version: @code a = [ *(p), *(p+3) ] b = [ *(p+1), *(p+4) ] c = [ *(p+2), *(p+5) ] @endcode @a p must be aligned to 16 bytes. @par 256-bit version: @code a = [ *(p), *(p+3), *(p+6), *(p+9) ] b = [ *(p+1), *(p+4), *(p+7), *(p+10) ] c = [ *(p+2), *(p+5), *(p+8), *(p+11) ] @endcode @a p must be aligned to 32 bytes. */ inline void load_packed3(float64x2& a, float64x2& b, float64x2& c, const double* p) { p = detail::assume_aligned(p, 16); #if SIMDPP_USE_NULL || SIMDPP_USE_NEON || SIMDPP_USE_ALTIVEC null::load_packed3(a, b, c, p); #elif SIMDPP_USE_SSE2 load(a, p); load(b, p+2); load(c, p+4); detail::mem_unpack3(a, b, c); #endif } inline void load_packed3(float64x4& a, float64x4& b, float64x4& c, const double* p) { p = detail::assume_aligned(p, 32); #if SIMDPP_USE_AVX load(a, p); load(b, p + 4); load(c, p + 8); detail::mem_unpack3(a, b, c); #else load_packed3(a[0], b[0], c[0], p); load_packed3(a[1], b[1], c[1], p + 6); #endif } /// @} /// @{ /** Loads 8-bit values packed in quartets, de-interleaves them and stores the result into four vectors. @par 128-bit version: @code a = [ *(p), *(p+4), *(p+8), ... , *(p+60) ] b = [ *(p+1), *(p+5), *(p+9), ... , *(p+61) ] c = [ *(p+2), *(p+6), *(p+10), ... , *(p+62) ] d = [ *(p+3), *(p+7), *(p+11), ... , *(p+63) ] @endcode @a p must be aligned to 16 bytes. @par 256-bit version: @code a = [ *(p), *(p+4), *(p+8), ... , *(p+124) ] b = [ *(p+1), *(p+5), *(p+9), ... , *(p+125) ] c = [ *(p+2), *(p+6), *(p+10), ... , *(p+126) ] d = [ *(p+3), *(p+7), *(p+11), ... , *(p+127) ] @endcode @a p must be aligned to 32 bytes. */ inline void load_packed4(basic_int8x16& a, basic_int8x16& b, basic_int8x16& c, basic_int8x16& d, const void* p) { p = detail::assume_aligned(p, 16); #if SIMDPP_USE_NULL null::load_packed4(a, b, c, d, p); #elif SIMDPP_USE_SSE2 || SIMDPP_USE_ALTIVEC const char* q = reinterpret_cast<const char*>(p); load(a, q); load(b, q+16); load(c, q+32); load(d, q+48); detail::mem_unpack4(a, b, c, d); #elif SIMDPP_USE_NEON auto r = vld4q_u8(reinterpret_cast<const uint8_t*>(p)); a = r.val[0]; b = r.val[1]; c = r.val[2]; d = r.val[3]; #endif } inline void load_packed4(basic_int8x32& a, basic_int8x32& b, basic_int8x32& c, basic_int8x32& d, const void* p) { detail::v256_load_i_packed4(a, b, c, d, p); } /// @} /// @{ /** Loads 16-bit values packed in quartets, de-interleaves them and stores the result into four vectors. @par 128-bit version: @code a = [ *(p), *(p+4), *(p+8), ... , *(p+28) ] b = [ *(p+1), *(p+5), *(p+9), ... , *(p+29) ] c = [ *(p+2), *(p+6), *(p+10), ... , *(p+30) ] d = [ *(p+3), *(p+7), *(p+11), ... , *(p+31) ] @endcode @a p must be aligned to 16 bytes. @par 256-bit version: @code a = [ *(p), *(p+4), *(p+8), ... , *(p+60) ] b = [ *(p+1), *(p+5), *(p+9), ... , *(p+61) ] c = [ *(p+2), *(p+6), *(p+10), ... , *(p+62) ] d = [ *(p+3), *(p+7), *(p+11), ... , *(p+63) ] @endcode @a p must be aligned to 32 bytes. */ inline void load_packed4(basic_int16x8& a, basic_int16x8& b, basic_int16x8& c, basic_int16x8& d, const void* p) { p = detail::assume_aligned(p, 16); #if SIMDPP_USE_NULL null::load_packed4(a, b, c, d, p); #elif SIMDPP_USE_SSE2 || SIMDPP_USE_ALTIVEC const char* q = reinterpret_cast<const char*>(p); load(a, q); load(b, q+16); load(c, q+32); load(d, q+48); detail::mem_unpack4(a, b, c, d); #elif SIMDPP_USE_NEON auto r = vld4q_u16(reinterpret_cast<const uint16_t*>(p)); a = r.val[0]; b = r.val[1]; c = r.val[2]; d = r.val[3]; #endif } inline void load_packed4(basic_int16x16& a, basic_int16x16& b, basic_int16x16& c, basic_int16x16& d, const void* p) { detail::v256_load_i_packed4(a, b, c, d, p); } /// @} /// @{ /** Loads 32-bit values packed in quartets, de-interleaves them and stores the result into four vectors. @par 128-bit version: @code a = [ *(p), *(p+4), *(p+8), *(p+12) ] b = [ *(p+1), *(p+5), *(p+9), *(p+13) ] c = [ *(p+2), *(p+6), *(p+10), *(p+14) ] d = [ *(p+3), *(p+7), *(p+11), *(p+15) ] @endcode @a p must be aligned to 16 bytes. @par 256-bit version: @code a = [ *(p), *(p+4), *(p+8), ... , *(p+28) ] b = [ *(p+1), *(p+5), *(p+9), ... , *(p+29) ] c = [ *(p+2), *(p+6), *(p+10), ... , *(p+30) ] d = [ *(p+3), *(p+7), *(p+11), ... , *(p+31) ] @endcode @a p must be aligned to 32 bytes. */ inline void load_packed4(basic_int32x4& a, basic_int32x4& b, basic_int32x4& c, basic_int32x4& d, const void* p) { p = detail::assume_aligned(p, 16); #if SIMDPP_USE_NULL null::load_packed4(a, b, c, d, p); #elif SIMDPP_USE_SSE2 || SIMDPP_USE_ALTIVEC const char* q = reinterpret_cast<const char*>(p); load(a, q); load(b, q+16); load(c, q+32); load(d, q+48); detail::mem_unpack4(a, b, c, d); #elif SIMDPP_USE_NEON auto r = vld4q_u32(reinterpret_cast<const uint32_t*>(p)); a = r.val[0]; b = r.val[1]; c = r.val[2]; d = r.val[3]; #endif } inline void load_packed4(basic_int32x8& a, basic_int32x8& b, basic_int32x8& c, basic_int32x8& d, const void* p) { detail::v256_load_i_packed4(a, b, c, d, p); } /// @} /// @{ /** Loads 64-bit values packed in quartets, de-interleaves them and stores the result into four vectors. @par 128-bit version: @code a = [ *(p), *(p+4) ] b = [ *(p+1), *(p+5) ] c = [ *(p+2), *(p+6) ] d = [ *(p+3), *(p+7) ] @endcode @a p must be aligned to 16 bytes. @par 256-bit version: @code a = [ *(p), *(p+4), *(p+8), *(p+12) ] b = [ *(p+1), *(p+5), *(p+9), *(p+13) ] c = [ *(p+2), *(p+6), *(p+10), *(p+14) ] d = [ *(p+3), *(p+7), *(p+11), *(p+15) ] @endcode @a p must be aligned to 32 bytes. */ inline void load_packed4(basic_int64x2& a, basic_int64x2& b, basic_int64x2& c, basic_int64x2& d, const void* p) { p = detail::assume_aligned(p, 16); const char* q = reinterpret_cast<const char*>(p); a = load(a, q); c = load(c, q+16); b = load(b, q+32); d = load(d, q+48); transpose2(a, b); transpose2(c, d); } inline void load_packed4(basic_int64x4& a, basic_int64x4& b, basic_int64x4& c, basic_int64x4& d, const void* p) { detail::v256_load_i_packed4(a, b, c, d, p); } /// @} /// @{ /** Loads 32-bit floating-point values packed in quartets, de-interleaves them and stores the result into four vectors. @par 128-bit version: @code a = [ *(p), *(p+4), *(p+8), *(p+12) ] b = [ *(p+1), *(p+5), *(p+9), *(p+13) ] c = [ *(p+2), *(p+6), *(p+10), *(p+14) ] d = [ *(p+3), *(p+7), *(p+11), *(p+15) ] @endcode @a p must be aligned to 16 bytes. @par 256-bit version: @code a = [ *(p), *(p+4), *(p+8), ... , *(p+28) ] b = [ *(p+1), *(p+5), *(p+9), ... , *(p+29) ] c = [ *(p+2), *(p+6), *(p+10), ... , *(p+30) ] d = [ *(p+3), *(p+7), *(p+11), ... , *(p+31) ] @endcode @a p must be aligned to 32 bytes. */ inline void load_packed4(float32x4& a, float32x4& b, float32x4& c, float32x4& d, const float* p) { p = detail::assume_aligned(p, 16); #if SIMDPP_USE_NULL null::load_packed4(a, b, c, d, p); #elif SIMDPP_USE_SSE2 || SIMDPP_USE_ALTIVEC load(a, p); load(b, p+4); load(c, p+8); load(d, p+12); detail::mem_unpack4(a, b, c, d); #elif SIMDPP_USE_NEON auto r = vld4q_f32(p); a = r.val[0]; b = r.val[1]; c = r.val[2]; d = r.val[3]; #endif } inline void load_packed4(float32x8& a, float32x8& b, float32x8& c, float32x8& d, const float* p) { p = detail::assume_aligned(p, 32); #if SIMDPP_USE_AVX load(a, p); load(b, p + 8); load(c, p + 16); load(d, p + 24); detail::mem_unpack4(a, b, c, d); #else load_packed4(a[0], b[0], c[0], d[0], p); load_packed4(a[1], b[1], c[1], d[1], p + 16); #endif } /// @} /// @{ /** Loads 64-bit floating-point values packed in quartets, de-interleaves them and stores the result into four vectors. @par 128-bit version: @code a = [ *(p), *(p+4) ] b = [ *(p+1), *(p+5) ] c = [ *(p+2), *(p+6) ] d = [ *(p+3), *(p+7) ] @endcode @a p must be aligned to 16 bytes. @par 256-bit version: @code a = [ *(p), *(p+4), *(p+8), *(p+12) ] b = [ *(p+1), *(p+5), *(p+9), *(p+13) ] c = [ *(p+2), *(p+6), *(p+10), *(p+14) ] d = [ *(p+3), *(p+7), *(p+11), *(p+15) ] @endcode @a p must be aligned to 32 bytes. */ inline void load_packed4(float64x2& a, float64x2& b, float64x2& c, float64x2& d, const double* p) { p = detail::assume_aligned(p, 16); #if SIMDPP_USE_NULL || SIMDPP_USE_NEON || SIMDPP_USE_ALTIVEC null::load_packed4(a, b, c, d, p); #elif SIMDPP_USE_SSE2 load(a, p); load(b, p+2); load(c, p+4); load(d, p+6); detail::mem_unpack4(a, b, c, d); #endif } inline void load_packed4(float64x4& a, float64x4& b, float64x4& c, float64x4& d, const double* p) { p = detail::assume_aligned(p, 32); #if SIMDPP_USE_AVX load(a, p); load(b, p + 4); load(c, p + 8); load(d, p + 12); detail::mem_unpack4(a, b, c, d); #else load_packed4(a[0], b[0], c[0], d[0], p); load_packed4(a[1], b[1], c[1], d[1], p + 8); #endif } /// @} /// @} -- end defgroup #ifndef DOXYGEN_SHOULD_SKIP_THIS } // namespace SIMDPP_ARCH_NAMESPACE #endif } // namespace simdpp #endif
26.051223
83
0.569802
[ "vector" ]
00943bcfc08fe16256c79c62e9672273ed07af32
1,350
h
C
tri.h
zoenolan/Raytracer
bf2c209fd0898cd561d548b0179183cf2f86ad40
[ "MIT" ]
null
null
null
tri.h
zoenolan/Raytracer
bf2c209fd0898cd561d548b0179183cf2f86ad40
[ "MIT" ]
null
null
null
tri.h
zoenolan/Raytracer
bf2c209fd0898cd561d548b0179183cf2f86ad40
[ "MIT" ]
null
null
null
#ifndef triangle_h #define triangle_h /***************************************************************************** Simple Triangle classClass NAME:tri.h DATE:17/12/1996 AUTHOR: Z.A. Nolan *****************************************************************************/ // include vector class #include "vector.h" // and the colour class #include "colour.h" // and the line class #include "line.h" // and include the object class #include "object.h" // and include the plane class #include "plane.h" class TSimpleTriangle :public TObject { private: TVector _P1 ; // 1st point of the Triangle TVector _P2 ; // 2nd Point of the Triangle TVector _P3 ; // 3rd point of the Triangle TPlane _Plane ; // Plane the triangle is in // read and write functions istream &Read (istream &In) ; ostream &Write (ostream &Out) const ; public: // Constructors TSimpleTriangle () ; TSimpleTriangle (TVector P1,TVector P2,TVector P3, const TSurfaceProperties) ; // Intersection of a line and a plane double Intersection(TVector &Point,TVector &Normal,const TLine &Line) const; // streaming operators friend istream &operator>>(istream &In, TSimpleTriangle &SimpleTriangle); friend ostream &operator<<(ostream &Out,const TSimpleTriangle &SimpleTriangle) ; } ; #endif
24.545455
79
0.608148
[ "object", "vector" ]
0095d7735c822d76cd7dfcb75f8648fb2f4c172a
30,224
h
C
ref-impl/src/com-api/CAAFPCMDescriptor.h
Phygon/aaf
faef720e031f501190481e1d1fc1870a7dc8f98b
[ "Linux-OpenIB" ]
null
null
null
ref-impl/src/com-api/CAAFPCMDescriptor.h
Phygon/aaf
faef720e031f501190481e1d1fc1870a7dc8f98b
[ "Linux-OpenIB" ]
null
null
null
ref-impl/src/com-api/CAAFPCMDescriptor.h
Phygon/aaf
faef720e031f501190481e1d1fc1870a7dc8f98b
[ "Linux-OpenIB" ]
null
null
null
//@doc //@class AAFPCMDescriptor | Implementation class for AAFPCMDescriptor #ifndef __CAAFPCMDescriptor_h__ #define __CAAFPCMDescriptor_h__ //=---------------------------------------------------------------------= // // This file was GENERATED for the AAF SDK // // $Id$ $Name$ // // The contents of this file are subject to the AAF SDK Public Source // License Agreement Version 2.0 (the "License"); You may not use this // file except in compliance with the License. The License is available // in AAFSDKPSL.TXT, or you may obtain a copy of the License from the // Advanced Media Workflow Association, Inc., or its successor. // // Software distributed under the License is distributed on an "AS IS" // basis, WITHOUT WARRANTY OF ANY KIND, either express or implied. See // the License for the specific language governing rights and limitations // under the License. Refer to Section 3.3 of the License for proper use // of this Exhibit. // // WARNING: Please contact the Advanced Media Workflow Association, // Inc., for more information about any additional licenses to // intellectual property covering the AAF Standard that may be required // to create and distribute AAF compliant products. // (http://www.amwa.tv/policies). // // Copyright Notices: // The Original Code of this file is Copyright 1998-2012, licensor of the // Advanced Media Workflow Association. All rights reserved. // // The Initial Developer of the Original Code of this file and the // licensor of the Advanced Media Workflow Association is // Avid Technology. // All rights reserved. // //=---------------------------------------------------------------------= #ifndef __AAF_h__ #include "AAF.h" #endif #ifndef __CAAFSoundDescriptor_h__ #include "CAAFSoundDescriptor.h" #endif class CAAFPCMDescriptor : public IAAFPCMDescriptor, public CAAFSoundDescriptor { protected: //******** // // Constructor/destructor // CAAFPCMDescriptor (IUnknown * pControllingUnknown, aafBool doInit = kAAFTrue); virtual ~CAAFPCMDescriptor (); public: //*********************************************************** // // Initialize() // // Initializes a newly allocated, IAAFPCMDescriptor-supporting /// object. This method must be called after allocation, and before /// any other method can be called. /// /// Succeeds if: /// - Initialize() has not yet been called on this object. /// /// This method will return the following codes. If more than one of /// the listed errors is in effect, it will return the first one /// encountered in the order given below: /// /// AAFRESULT_SUCCESS /// - succeeded. (This is the only code indicating success.) /// /// AAFRESULT_ALREADY_INITIALIZED /// - Initialize() has already been called on this object. // STDMETHOD (Initialize) (); //*********************************************************** // // SetBlockAlign() // // Sets the number of bytes used to store one sample of all channels. /// This property is required. /// /// Succeeds if all of the following are true: /// - the object is initialized. /// /// If this method fails the BlockAlign property will not be /// changed. /// /// This method will return the following codes: /// /// AAFRESULT_SUCCESS /// - succeeded. (This is the only code indicating success.) /// /// AAFRESULT_NOT_INITIALIZED /// - the object is not initialized. // STDMETHOD (SetBlockAlign) ( // The number of bytes used to store one sample of all channels. /*[in]*/ aafUInt16 blockAlign); //*********************************************************** // // GetBlockAlign() // // Gets the number of bytes used to store one sample of all channels. /// This property is required. /// /// Succeeds if all of the following are true: /// - the object is initialized. /// - the pBlockAlign pointer is valid. /// /// If this method fails nothing will be written to *pBlockAlign. /// /// This method will return the following codes: /// /// AAFRESULT_SUCCESS /// - succeeded. (This is the only code indicating success.) /// /// AAFRESULT_NOT_INITIALIZED /// - the object is not initialized. /// /// AAFRESULT_NULL_PARAM /// - pBlockAlign arg is NULL. // STDMETHOD (GetBlockAlign) ( // The number of bytes used to store one sample of all channels. /*[out]*/ aafUInt16 * pBlockAlign); //*********************************************************** // // SetSequenceOffset() // // Sets the frame number of the beginning of the essence data /// within a five-frame sequence. This property is optional. /// /// Succeeds if all of the following are true: /// - the object is initialized. /// /// If this method fails the SequenceOffset property will not be /// changed. /// /// This method will return the following codes: /// /// AAFRESULT_SUCCESS /// - succeeded. (This is the only code indicating success.) /// /// AAFRESULT_NOT_INITIALIZED /// - the object is not initialized. // STDMETHOD (SetSequenceOffset) ( // Zero-based ordinal frame number of the beginning of /// the essence data within a five-frame sequence. /*[in]*/ aafUInt8 offset); //*********************************************************** // // GetSequenceOffset() // // Gets the frame number of the beginning of the essence data /// within a five-frame sequence. This property is optional. /// /// Succeeds if all of the following are true: /// - the object is initialized. /// - the pOffset pointer is valid. /// - the property is present. /// /// If this method fails nothing will be written to *pOffset. /// /// This method will return the following codes: /// /// AAFRESULT_SUCCESS /// - succeeded. (This is the only code indicating success.) /// /// AAFRESULT_NOT_INITIALIZED /// - the object is not initialized. /// /// AAFRESULT_NULL_PARAM /// - pOffset arg is NULL. /// /// AAFRESULT_PROP_NOT_PRESENT /// - the property is not present. // STDMETHOD (GetSequenceOffset) ( // Zero-based ordinal frame number of the beginning of /// the essence data within a five-frame sequence. /*[out]*/ aafUInt8 * pOffset); //*********************************************************** // // SetAverageBPS() // // Sets the average bytes per second of the essence stream. /// This property is required. /// /// Succeeds if all of the following are true: /// - the object is initialized. /// /// If this method fails the AverageBPS property will not be /// changed. /// /// This method will return the following codes: /// /// AAFRESULT_SUCCESS /// - succeeded. (This is the only code indicating success.) /// /// AAFRESULT_NOT_INITIALIZED /// - the object is not initialized. // STDMETHOD (SetAverageBPS) ( // Average bytes per second of the essence stream. /*[in]*/ aafUInt32 bps); //*********************************************************** // // GetAverageBPS() // // Gets the average bytes per second of the essence stream. /// This property is required. /// /// Succeeds if all of the following are true: /// - the object is initialized. /// - the pBps pointer is valid. /// /// If this method fails nothing will be written to *pBps. /// /// This method will return the following codes: /// /// AAFRESULT_SUCCESS /// - succeeded. (This is the only code indicating success.) /// /// AAFRESULT_NOT_INITIALIZED /// - the object is not initialized. /// /// AAFRESULT_NULL_PARAM /// - pBps arg is NULL. // STDMETHOD (GetAverageBPS) ( // Average bytes per second of the essence stream. /*[out]*/ aafUInt32 * pBps); //*********************************************************** // // SetChannelAssignment() // // Sets the channel assignment scheme. This property is optional. /// /// Succeeds if all of the following are true: /// - the object is initialized. /// /// If this method fails the ChannelAssignment property will not be /// changed. /// /// This method will return the following codes: /// /// AAFRESULT_SUCCESS /// - succeeded. (This is the only code indicating success.) /// /// AAFRESULT_NOT_INITIALIZED /// - the object is not initialized. // STDMETHOD (SetChannelAssignment) ( // The channel assignment to use. /*[in, ref]*/ aafUID_constref channelAssignment); //*********************************************************** // // GetChannelAssignment() // // Gets the channel assignment scheme. This property is optional. /// /// Succeeds if all of the following are true: /// - the object is initialized. /// - the pChannelAssignment pointer is valid. /// - the property is present. /// /// If this method fails nothing will be written to *pChannelAssignment. /// /// This method will return the following codes: /// /// AAFRESULT_SUCCESS /// - succeeded. (This is the only code indicating success.) /// /// AAFRESULT_NOT_INITIALIZED /// - the object is not initialized. /// /// AAFRESULT_NULL_PARAM /// - pChannelAssignment arg is NULL. /// /// AAFRESULT_PROP_NOT_PRESENT /// - the property is not present. // STDMETHOD (GetChannelAssignment) ( // The channel assignment in use. /*[out]*/ aafUID_t * pChannelAssignment); //*********************************************************** // // AreAllPeakEnvelopePropertiesPresent() // // Places TRUE into *pArePresent if the following optional /// properties are set on the descriptor: /// PeakEnvelopeVersion /// PeakEnvelopeFormat /// PointsPerPeakValue /// PeakEnvelopeBlockSize /// PeakChannels /// PeakFrames /// PeakOfPeaksPosition /// PeakEnvelopeTimestamp /// PeakEnvelopeData /// /// Succeeds if all of the following are true: /// - the pArePresent pointer is valid. /// /// If this method fails nothing will be written to *pIsPresent. /// /// This method will return the following codes. If more than one of /// the listed errors is in effect, it will return the first one /// encountered in the order given below: /// /// AAFRESULT_SUCCESS /// - succeeded. (This is the only code indicating success.) /// /// AAFRESULT_NULL_PARAM /// - pArePresent arg is NULL. // STDMETHOD (AreAllPeakEnvelopePropertiesPresent) ( // The flag indicating presence of the optional properties /// that form peak envelope. /*[out]*/ aafBoolean_t * pArePresent); //*********************************************************** // // SetPeakEnvelopeVersion() // // Sets the version of the peak envelope data. /// /// Succeeds if all of the following are true: /// - the object is initialized. /// /// If this method fails the version will not be changed. /// /// This method will return the following codes: /// /// AAFRESULT_SUCCESS /// - succeeded. (This is the only code indicating success.) /// /// AAFRESULT_NOT_INITIALIZED /// - the object is not initialized. // STDMETHOD (SetPeakEnvelopeVersion) ( // Version of the peak envelope data. /*[in]*/ aafUInt32 version); //*********************************************************** // // GetPeakEnvelopeVersion() // // Gets the version of the peak envelope data. /// This property is optional. /// /// Succeeds if all of the following are true: /// - the object is initialized. /// - the pVersion pointer is valid. /// - the property is present. /// /// If this method fails nothing will be written to *pVersion. /// /// This method will return the following codes: /// /// AAFRESULT_SUCCESS /// - succeeded. (This is the only code indicating success.) /// /// AAFRESULT_NOT_INITIALIZED /// - the object is not initialized. /// /// AAFRESULT_NULL_PARAM /// - pVersion arg is NULL. /// /// AAFRESULT_PROP_NOT_PRESENT /// - the property is not present. // STDMETHOD (GetPeakEnvelopeVersion) ( // Version of the peak envelope data. /*[out]*/ aafUInt32 * pVersion); //*********************************************************** // // SetPeakEnvelopeFormat() // // Sets the format of the peak point. /// /// Succeeds if all of the following are true: /// - the object is initialized. /// /// If this method fails the format will not be changed. /// /// This method will return the following codes: /// /// AAFRESULT_SUCCESS /// - succeeded. (This is the only code indicating success.) /// /// AAFRESULT_NOT_INITIALIZED /// - the object is not initialized. // STDMETHOD (SetPeakEnvelopeFormat) ( // Format of the peak point. /*[in]*/ aafUInt32 format); //*********************************************************** // // GetPeakEnvelopeFormat() // // Gets the format of the peak point. /// This property is optional. /// /// Succeeds if all of the following are true: /// - the object is initialized. /// - the pFormat pointer is valid. /// - the property is present. /// /// If this method fails nothing will be written to *pFormat. /// /// This method will return the following codes: /// /// AAFRESULT_SUCCESS /// - succeeded. (This is the only code indicating success.) /// /// AAFRESULT_NOT_INITIALIZED /// - the object is not initialized. /// /// AAFRESULT_NULL_PARAM /// - pFormat arg is NULL. /// /// AAFRESULT_PROP_NOT_PRESENT /// - the property is not present. // STDMETHOD (GetPeakEnvelopeFormat) ( // Format of the peak point. /*[out]*/ aafUInt32 * pFormat); //*********************************************************** // // SetPointsPerPeakValue() // // Sets the number of peak points per peak value. /// /// Succeeds if all of the following are true: /// - the object is initialized. /// /// If this method fails the PointsPerPeakValue property will /// not be changed. /// /// This method will return the following codes: /// /// AAFRESULT_SUCCESS /// - succeeded. (This is the only code indicating success.) /// /// AAFRESULT_NOT_INITIALIZED /// - the object is not initialized. // STDMETHOD (SetPointsPerPeakValue) ( // The number of peak points per peak value. /*[in]*/ aafUInt32 pointCount); //*********************************************************** // // GetPointsPerPeakValue() // // Gets the number of peak points per peak value. /// This property is optional. /// /// Succeeds if all of the following are true: /// - the object is initialized. /// - the pPointCount pointer is valid. /// - the property is present. /// /// If this method fails nothing will be written to *pPointCount. /// /// This method will return the following codes: /// /// AAFRESULT_SUCCESS /// - succeeded. (This is the only code indicating success.) /// /// AAFRESULT_NOT_INITIALIZED /// - the object is not initialized. /// /// AAFRESULT_NULL_PARAM /// - pPointCount arg is NULL. /// /// AAFRESULT_PROP_NOT_PRESENT /// - the property is not present. // STDMETHOD (GetPointsPerPeakValue) ( // The number of peak points per peak value. /*[out]*/ aafUInt32 * pPointCount); //*********************************************************** // // SetPeakEnvelopeBlockSize() // // Sets the number of audio samples used to generate each peak frame. /// /// Succeeds if all of the following are true: /// - the object is initialized. /// /// If this method fails the PeakEnvelopeBlockSize property will /// not be changed. /// /// This method will return the following codes: /// /// AAFRESULT_SUCCESS /// - succeeded. (This is the only code indicating success.) /// /// AAFRESULT_NOT_INITIALIZED /// - the object is not initialized. // STDMETHOD (SetPeakEnvelopeBlockSize) ( // The number of audio samples used to generate each peak frame. /*[in]*/ aafUInt32 blockSize); //*********************************************************** // // GetPeakEnvelopeBlockSize() // // Gets the number of audio samples used to generate each peak frame. /// This property is optional. /// /// Succeeds if all of the following are true: /// - the object is initialized. /// - the pBlockSize pointer is valid. /// - the property is present. /// /// If this method fails nothing will be written to *pBlockSize. /// /// This method will return the following codes: /// /// AAFRESULT_SUCCESS /// - succeeded. (This is the only code indicating success.) /// /// AAFRESULT_NOT_INITIALIZED /// - the object is not initialized. /// /// AAFRESULT_NULL_PARAM /// - pBlockSize arg is NULL. /// /// AAFRESULT_PROP_NOT_PRESENT /// - the property is not present. // STDMETHOD (GetPeakEnvelopeBlockSize) ( // The number of audio samples used to generate each peak frame. /*[out]*/ aafUInt32 * pBlockSize); //*********************************************************** // // SetPeakChannelCount() // // Sets the number of peak channels. /// /// Succeeds if all of the following are true: /// - the object is initialized. /// /// If this method fails the channel count will not be changed. /// /// This method will return the following codes: /// /// AAFRESULT_SUCCESS /// - succeeded. (This is the only code indicating success.) /// /// AAFRESULT_NOT_INITIALIZED /// - the object is not initialized. // STDMETHOD (SetPeakChannelCount) ( // The number of peak channels. /*[in]*/ aafUInt32 channelCount); //*********************************************************** // // GetPeakChannelCount() // // Gets the number of peak channels. /// This property is optional. /// /// Succeeds if all of the following are true: /// - the object is initialized. /// - the pChannelCount pointer is valid. /// - the property is present. /// /// If this method fails nothing will be written to *pChannelCount. /// /// This method will return the following codes: /// /// AAFRESULT_SUCCESS /// - succeeded. (This is the only code indicating success.) /// /// AAFRESULT_NOT_INITIALIZED /// - the object is not initialized. /// /// AAFRESULT_NULL_PARAM /// - pChannelCount arg is NULL. /// /// AAFRESULT_PROP_NOT_PRESENT /// - the property is not present. // STDMETHOD (GetPeakChannelCount) ( // The number of peak channels. /*[out]*/ aafUInt32 * pChannelCount); //*********************************************************** // // SetPeakFrameCount() // // Sets the number of peak frames. /// /// Succeeds if all of the following are true: /// - the object is initialized. /// /// If this method fails the frame count will not be changed. /// /// This method will return the following codes: /// /// AAFRESULT_SUCCESS /// - succeeded. (This is the only code indicating success.) /// /// AAFRESULT_NOT_INITIALIZED /// - the object is not initialized. // STDMETHOD (SetPeakFrameCount) ( // The number of peak frames. /*[in]*/ aafUInt32 frameCount); //*********************************************************** // // GetPeakFrameCount() // // Gets the number of peak frames. /// This property is optional. /// /// Succeeds if all of the following are true: /// - the object is initialized. /// - the pFrameCount pointer is valid. /// - the property is present. /// /// If this method fails nothing will be written to *pFrameCount. /// /// This method will return the following codes: /// /// AAFRESULT_SUCCESS /// - succeeded. (This is the only code indicating success.) /// /// AAFRESULT_NOT_INITIALIZED /// - the object is not initialized. /// /// AAFRESULT_NULL_PARAM /// - pFrameCount arg is NULL. /// /// AAFRESULT_PROP_NOT_PRESENT /// - the property is not present. // STDMETHOD (GetPeakFrameCount) ( // The number of peak frames. /*[out]*/ aafUInt32 * pFrameCount); //*********************************************************** // // SetPeakOfPeaksPosition() // // Sets the offset to the first audio sample whose absolute /// value is the maximum value of the entire audio file. /// /// Succeeds if all of the following are true: /// - the object is initialized. /// /// If this method fails the PeakOfPeaksPosition property will /// not be changed. /// /// This method will return the following codes: /// /// AAFRESULT_SUCCESS /// - succeeded. (This is the only code indicating success.) /// /// AAFRESULT_NOT_INITIALIZED /// - the object is not initialized. // STDMETHOD (SetPeakOfPeaksPosition) ( // The offset to peak of peaks /*[in]*/ aafPosition_t position); //*********************************************************** // // GetPeakOfPeaksPosition() // // Gets the offset to the first audio sample whose absolute /// value is the maximum value of the entire audio file. /// This property is optional. /// /// Succeeds if all of the following are true: /// - the object is initialized. /// - the pPosition pointer is valid. /// - the property is present. /// /// If this method fails nothing will be written to *pPosition. /// /// This method will return the following codes: /// /// AAFRESULT_SUCCESS /// - succeeded. (This is the only code indicating success.) /// /// AAFRESULT_NOT_INITIALIZED /// - the object is not initialized. /// /// AAFRESULT_NULL_PARAM /// - pPosition arg is NULL. /// /// AAFRESULT_PROP_NOT_PRESENT /// - the property is not present. // STDMETHOD (GetPeakOfPeaksPosition) ( // The offset to peak of peaks. /*[out]*/ aafPosition_t * pPosition); //*********************************************************** // // SetPeakEnvelopeTimestamp() // // Sets the time stamp of the creation of the peak data. /// /// Succeeds if all of the following are true: /// - the object is initialized. /// /// If this method fails the time stamp will not be changed. /// /// This method will return the following codes: /// /// AAFRESULT_SUCCESS /// - succeeded. (This is the only code indicating success.) /// /// AAFRESULT_NOT_INITIALIZED /// - the object is not initialized. // STDMETHOD (SetPeakEnvelopeTimestamp) ( // The time stamp of the creation of the peak data. /*[in]*/ aafTimeStamp_constref timeStamp); //*********************************************************** // // GetPeakEnvelopeTimestamp() // // Gets the time stamp of the creation of the peak data. /// This property is optional. /// /// Succeeds if all of the following are true: /// - the object is initialized. /// - the pTimeStamp pointer is valid. /// - the property is present. /// /// If this method fails nothing will be written to *pTimeStamp. /// /// This method will return the following codes: /// /// AAFRESULT_SUCCESS /// - succeeded. (This is the only code indicating success.) /// /// AAFRESULT_NOT_INITIALIZED /// - the object is not initialized. /// /// AAFRESULT_NULL_PARAM /// - pTimeStamp arg is NULL. /// /// AAFRESULT_PROP_NOT_PRESENT /// - the property is not present. // STDMETHOD (GetPeakEnvelopeTimestamp) ( // The time stamp of the creation of the peak data. /*[out]*/ aafTimeStamp_t * pTimeStamp); //*********************************************************** // // SetPeakEnvelopeDataPosition() // // Sets the offset from the beginning of peak envelope data. /// /// Succeeds if all of the following are true: /// - the object is initialized. /// - the object is persistent (attached to a file). /// /// If this method fails the position will not be changed. /// /// This method will return the following codes: /// /// AAFRESULT_SUCCESS /// - succeeded. (This is the only code indicating success.) /// /// AAFRESULT_NOT_INITIALIZED /// - the object is not initialized. /// /// AAFRESULT_OBJECT_NOT_PERSISTENT /// - the object is not persistent. // STDMETHOD (SetPeakEnvelopeDataPosition) ( // Offset from the beginning of peak envelope data. /*[in]*/ aafPosition_t position); //*********************************************************** // // GetPeakEnvelopeDataPosition() // // Gets the offset from the beginning of peak envelope data. /// /// Succeeds if all of the following are true: /// - the object is initialized. /// - the pPosition pointer is valid. /// - the object is persistent (attached to a file). /// /// If this method fails nothing will be written to *pPosition. /// /// This method will return the following codes: /// /// AAFRESULT_SUCCESS /// - succeeded. (This is the only code indicating success.) /// /// AAFRESULT_NOT_INITIALIZED /// - the object is not initialized. /// /// AAFRESULT_NULL_PARAM /// - pPosition arg is NULL. /// /// AAFRESULT_PROP_NOT_PRESENT /// - the PeakEnvelopeData property is not present. /// /// AAFRESULT_OBJECT_NOT_PERSISTENT /// - the object is not persistent. // STDMETHOD (GetPeakEnvelopeDataPosition) ( // Offset from the beginning of peak envelope data. /*[out]*/ aafPosition_t * pPosition); //*********************************************************** // // GetPeakEnvelopeDataSize() // // Gets the size of peak envelope data. /// PeakEnvelopeData is optional property. /// /// Succeeds if all of the following are true: /// - the object is initialized. /// - the pSize pointer is valid. /// - the PeakEnvelopeData property is present. /// - the object is persistent (attached to a file). /// /// If this method fails nothing will be written to *pSize. /// /// This method will return the following codes: /// /// AAFRESULT_SUCCESS /// - succeeded. (This is the only code indicating success.) /// /// AAFRESULT_NOT_INITIALIZED /// - the object is not initialized. /// /// AAFRESULT_NULL_PARAM /// - pSize arg is NULL. /// /// AAFRESULT_PROP_NOT_PRESENT /// - the PeakEnvelopeData property is not present. /// /// AAFRESULT_OBJECT_NOT_PERSISTENT /// - the object is not persistent. // STDMETHOD (GetPeakEnvelopeDataSize) ( // The size of peak envelope data. /*[out]*/ aafLength_t * pSize); //*********************************************************** // // WritePeakEnvelopeData() // // Write the specified bytes to the peak envelope data stream. /// /// Succeeds if all of the following are true: /// - the number of bytes to write is non-zero. /// - the buffer pointer is valid. /// - the pBytesWritten pointer is valid. /// - the object is initialized. /// - the object is persistent (attached to a file). /// /// If this method fails the PeakEnvelopeData property will /// not be changed. /// /// This method will return the following codes: /// /// AAFRESULT_SUCCESS /// - succeeded. (This is the only code indicating success.) /// /// AAFRESULT_INVALID_PARAM /// - bytes arg is larger than zero. /// /// AAFRESULT_NULL_PARAM /// - buffer arg is NULL. /// /// AAFRESULT_NULL_PARAM /// - pBytesWritten arg is NULL. /// /// AAFRESULT_NOT_INITIALIZED /// - the object is not initialized. /// /// AAFRESULT_OBJECT_NOT_PERSISTENT /// - the object is not persistent. /// /// AAFRESULT_CONTAINERWRITE /// - writing failed. // STDMETHOD (WritePeakEnvelopeData) ( // Write this many bytes /*[in]*/ aafUInt32 bytes, // Data to write /*[out, size_is(bytes)]*/ aafDataBuffer_t buffer, // Number of bytes actually written. /*[out,ref]*/ aafUInt32 * pBytesWritten); //*********************************************************** // // ReadPeakEnvelopeData() // // Read the specified number of bytes from the peak envelope data /// stream into buffer. /// /// Succeeds if all of the following are true: /// - the object is initialized. /// - the number of bytes to read is non-zero. /// - the buffer pointer is valid. /// - the pBytesRead pointer is valid. /// - the PeakEnvelopeData property is present. /// - the object is persistent (attached to a file). /// - not yet reached the end of the data stream. /// /// This method will return the following codes: /// /// AAFRESULT_SUCCESS /// - succeeded. (This is the only code indicating success.) /// /// AAFRESULT_END_OF_DATA /// - trying to read beyond the end of the data stream. /// /// AAFRESULT_NOT_INITIALIZED /// - the object is not initialized. /// /// AAFRESULT_INVALID_PARAM /// - bytes arg is larger than zero. /// /// AAFRESULT_NULL_PARAM /// - buffer arg is NULL. /// /// AAFRESULT_NULL_PARAM /// - pBytesRead arg is NULL. /// /// AAFRESULT_PROP_NOT_PRESENT /// - the PeakEnvelopeData property is not present. /// /// AAFRESULT_OBJECT_NOT_PERSISTENT /// - the object is not persistent. // STDMETHOD (ReadPeakEnvelopeData) ( // Read this many bytes /*[in]*/ aafUInt32 bytes, // Buffer to read the data to /*[out, size_is(bytes)]*/ aafDataBuffer_t buffer, // Number of bytes actually read. /*[out,ref]*/ aafUInt32 * pBytesRead); protected: // // Declare the QI that implements for the interfaces // for this module. This will be called by CAAFUnknown::QueryInterface(). // STDMETHOD(InternalQueryInterface)(REFIID riid, void **ppvObjOut); public: // // This class as concrete. All AAF objects can be constructed from // a CLSID. This will allow subclassing all "base-classes" by // aggreggation. // AAF_DECLARE_CONCRETE(); // //******** }; #endif // ! __CAAFPCMDescriptor_h__
28.839695
80
0.599292
[ "object" ]
009a0de658933310cf79dfdc44a91433540c6f7f
938
h
C
src/datatypes/List.h
dangleptr/nebula-common
8db3ac30a60822aeadc9dc4916183466396e8bc6
[ "Apache-2.0" ]
null
null
null
src/datatypes/List.h
dangleptr/nebula-common
8db3ac30a60822aeadc9dc4916183466396e8bc6
[ "Apache-2.0" ]
null
null
null
src/datatypes/List.h
dangleptr/nebula-common
8db3ac30a60822aeadc9dc4916183466396e8bc6
[ "Apache-2.0" ]
null
null
null
/* Copyright (c) 2020 vesoft inc. All rights reserved. * * This source code is licensed under Apache 2.0 License, * attached with Common Clause Condition 1.0, found in the LICENSES directory. */ #ifndef DATATYPES_LIST_H_ #define DATATYPES_LIST_H_ #include "base/Base.h" #include "datatypes/Value.h" namespace nebula { struct List { std::vector<Value> values; List() = default; List(const List&) = default; List(List&&) = default; void clear() { values.clear(); } List& operator=(const List& rhs) { if (this == &rhs) { return *this; } values = rhs.values; return *this; } List& operator=(List&& rhs) { if (this == &rhs) { return *this; } values = std::move(rhs.values); return *this; } bool operator==(const List& rhs) const { return values == rhs.values; } }; } // namespace nebula #endif // DATATYPES_LIST_H_
20.844444
78
0.603412
[ "vector" ]
00add27a05f78aac95cdd5268a8c94ea99a956cd
60,114
c
C
src/bin/e_int_client_menu.c
FlorentRevest/Enlightenment
0b614b8d66c1f1d71b83ea04ae5014c1f66bfc6e
[ "BSD-2-Clause" ]
null
null
null
src/bin/e_int_client_menu.c
FlorentRevest/Enlightenment
0b614b8d66c1f1d71b83ea04ae5014c1f66bfc6e
[ "BSD-2-Clause" ]
null
null
null
src/bin/e_int_client_menu.c
FlorentRevest/Enlightenment
0b614b8d66c1f1d71b83ea04ae5014c1f66bfc6e
[ "BSD-2-Clause" ]
null
null
null
#include "e.h" static void _e_client_cb_border_menu_end(void *data, E_Menu *m); static void _e_client_menu_cb_locks(void *data, E_Menu *m, E_Menu_Item *mi); static void _e_client_menu_cb_remember(void *data, E_Menu *m, E_Menu_Item *mi); static void _e_client_menu_cb_borderless(void *data, E_Menu *m, E_Menu_Item *mi); static void _e_client_menu_cb_border(void *data, E_Menu *m, E_Menu_Item *mi); static void _e_client_menu_cb_redirect_set(void *data, E_Menu *m EINA_UNUSED, E_Menu_Item *mi EINA_UNUSED); static void _e_client_menu_cb_close(void *data, E_Menu *m, E_Menu_Item *mi); static void _e_client_menu_cb_iconify(void *data, E_Menu *m, E_Menu_Item *mi); static void _e_client_menu_cb_kill(void *data, E_Menu *m, E_Menu_Item *mi); static void _e_client_menu_cb_move(void *data, E_Menu *m, E_Menu_Item *mi); static void _e_client_menu_cb_resize(void *data, E_Menu *m, E_Menu_Item *mi); static void _e_client_menu_cb_maximize_pre(void *data, E_Menu *m, E_Menu_Item *mi); static void _e_client_menu_cb_maximize(void *data, E_Menu *m, E_Menu_Item *mi); static void _e_client_menu_cb_maximize_vertically(void *data, E_Menu *m, E_Menu_Item *mi); static void _e_client_menu_cb_maximize_horizontally(void *data, E_Menu *m, E_Menu_Item *mi); static void _e_client_menu_cb_maximize_left(void *data, E_Menu *m, E_Menu_Item *mi); static void _e_client_menu_cb_maximize_right(void *data, E_Menu *m, E_Menu_Item *mi); static void _e_client_menu_cb_unmaximize(void *data, E_Menu *m, E_Menu_Item *mi); static void _e_client_menu_cb_shade(void *data, E_Menu *m, E_Menu_Item *mi); static void _e_client_menu_cb_resistance(void *data, E_Menu *m, E_Menu_Item *mi); static void _e_client_menu_cb_icon_edit(void *data, E_Menu *m, E_Menu_Item *mi); static void _e_client_menu_cb_application_pre(void *data, E_Menu *m, E_Menu_Item *mi); static void _e_client_menu_cb_window_pre(void *data, E_Menu *m EINA_UNUSED, E_Menu_Item *mi); static void _e_client_menu_cb_prop(void *data, E_Menu *m, E_Menu_Item *mi); static void _e_client_menu_cb_stick(void *data, E_Menu *m, E_Menu_Item *mi); static void _e_client_menu_cb_stacking_pre(void *data, E_Menu *m, E_Menu_Item *mi); static void _e_client_menu_cb_on_top(void *data, E_Menu *m, E_Menu_Item *mi); static void _e_client_menu_cb_normal(void *data, E_Menu *m, E_Menu_Item *mi); static void _e_client_menu_cb_below(void *data, E_Menu *m, E_Menu_Item *mi); static void _e_client_menu_cb_fullscreen(void *data, E_Menu *m, E_Menu_Item *mi); static void _e_client_menu_cb_skip_winlist(void *data, E_Menu *m, E_Menu_Item *mi); static void _e_client_menu_cb_skip_pager(void *data, E_Menu *m, E_Menu_Item *mi); static void _e_client_menu_cb_skip_taskbar(void *data, E_Menu *m, E_Menu_Item *mi); static void _e_client_menu_cb_sendto_pre(void *data, E_Menu *m, E_Menu_Item *mi); static void _e_client_menu_cb_align_pre(void *data, E_Menu *m, E_Menu_Item *mi); static void _e_client_menu_cb_sendto(void *data, E_Menu *m, E_Menu_Item *mi); static void _e_client_menu_cb_pin(void *data, E_Menu *m, E_Menu_Item *mi); static void _e_client_menu_cb_unpin(void *data, E_Menu *m, E_Menu_Item *mi); static void _e_client_menu_cb_raise(void *data, E_Menu *m, E_Menu_Item *mi); static void _e_client_menu_cb_lower(void *data, E_Menu *m, E_Menu_Item *mi); static void _e_client_menu_cb_skip_pre(void *data, E_Menu *m, E_Menu_Item *mi); static void _e_client_menu_cb_fav_add(void *data, E_Menu *m, E_Menu_Item *mi); static void _e_client_menu_cb_kbdshrtct_add(void *data, E_Menu *m, E_Menu_Item *mi); static void _e_client_menu_cb_ibar_add_pre(void *data, E_Menu *m, E_Menu_Item *mi); static void _e_client_menu_cb_ibar_add(void *data, E_Menu *m, E_Menu_Item *mi); static void _e_client_menu_cb_border_pre(void *data, E_Menu *m, E_Menu_Item *mi); static void _e_client_menu_cb_iconpref_e(void *data, E_Menu *m, E_Menu_Item *mi); static void _e_client_menu_cb_iconpref_netwm(void *data, E_Menu *m, E_Menu_Item *mi); static void _e_client_menu_cb_iconpref_user(void *data, E_Menu *m, E_Menu_Item *mi); static void _e_client_menu_cb_default_icon(void *data, E_Menu *m, E_Menu_Item *mi); static void _e_client_menu_cb_netwm_icon(void *data, E_Menu *m, E_Menu_Item *mi); static Eina_List *menu_hooks = NULL; E_API E_Client_Menu_Hook * e_int_client_menu_hook_add(E_Client_Menu_Hook_Cb cb, const void *data) { E_Client_Menu_Hook *h; if (!cb) return NULL; h = E_NEW(E_Client_Menu_Hook, 1); if (!h) return NULL; h->cb = cb; h->data = (void *)data; menu_hooks = eina_list_append(menu_hooks, h); return h; } E_API void e_int_client_menu_hook_del(E_Client_Menu_Hook *hook) { E_Client_Menu_Hook *h; Eina_List *l; if (!hook) return; EINA_LIST_FOREACH(menu_hooks, l, h) if (h == hook) { menu_hooks = eina_list_remove_list(menu_hooks, l); free(h); return; } } E_API void e_int_client_menu_hooks_clear(void) { E_Client_Menu_Hook *h; EINA_LIST_FREE(menu_hooks, h) free(h); } E_API void e_int_client_menu_create(E_Client *ec) { E_Menu *m; E_Menu_Item *mi; Eina_List *l; E_Client_Menu_Hook *h; char buf[128]; Eina_Bool borderless; if (ec->border_menu) return; m = e_menu_new(); e_menu_category_set(m, "border"); e_menu_category_data_set("border", ec); e_object_data_set(E_OBJECT(m), ec); ec->border_menu = m; e_menu_post_deactivate_callback_set(m, _e_client_cb_border_menu_end, NULL); if (!ec->internal) { if (ec->icccm.class) snprintf(buf, sizeof(buf), "%s", ec->icccm.class); else snprintf(buf, sizeof(buf), _("Application")); mi = e_menu_item_new(m); e_menu_item_label_set(mi, buf); e_menu_item_submenu_pre_callback_set(mi, _e_client_menu_cb_application_pre, ec); if (ec->desktop) e_util_desktop_menu_item_icon_add(ec->desktop, 16, mi); } borderless = e_client_util_borderless(ec); mi = e_menu_item_new(m); e_menu_item_label_set(mi, _("Window")); e_menu_item_submenu_pre_callback_set(mi, _e_client_menu_cb_window_pre, ec); e_menu_item_icon_edje_set(mi, e_theme_edje_file_get("base/theme/borders", "e/widgets/border/default/window"), "e/widgets/border/default/window"); mi = e_menu_item_new(m); e_menu_item_separator_set(mi, 1); if ((!ec->sticky) && ((eina_list_count(e_comp->zones) > 1) || (ec->zone->desk_x_count > 1) || (ec->zone->desk_y_count > 1))) { mi = e_menu_item_new(m); e_menu_item_label_set(mi, _("Move to")); e_menu_item_submenu_pre_callback_set(mi, _e_client_menu_cb_sendto_pre, ec); e_menu_item_icon_edje_set(mi, e_theme_edje_file_get("base/theme/borders", "e/widgets/border/default/sendto"), "e/widgets/border/default/sendto"); } if ((!ec->lock_user_location) && (!ec->iconic) && (!ec->maximized) && (!ec->fullscreen)) { mi = e_menu_item_new(m); e_menu_item_label_set(mi, _("Align")); e_menu_item_submenu_pre_callback_set(mi, _e_client_menu_cb_align_pre, ec); } mi = e_menu_item_new(m); e_menu_item_label_set(mi, _("Always on Top")); e_menu_item_check_set(mi, 1); e_menu_item_toggle_set(mi, (ec->layer == E_LAYER_CLIENT_ABOVE ? 1 : 0)); if (ec->layer == E_LAYER_CLIENT_ABOVE) e_menu_item_callback_set(mi, _e_client_menu_cb_normal, ec); else e_menu_item_callback_set(mi, _e_client_menu_cb_on_top, ec); e_menu_item_icon_edje_set(mi, e_theme_edje_file_get("base/theme/borders", "e/widgets/border/default/stack_on_top"), "e/widgets/border/default/stack_on_top"); if (!ec->lock_user_sticky) { mi = e_menu_item_new(m); e_menu_item_label_set(mi, _("Sticky")); e_menu_item_check_set(mi, 1); e_menu_item_toggle_set(mi, (ec->sticky ? 1 : 0)); e_menu_item_callback_set(mi, _e_client_menu_cb_stick, ec); e_menu_item_icon_edje_set(mi, e_theme_edje_file_get("base/theme/borders", "e/widgets/border/default/stick"), "e/widgets/border/default/stick"); } if ((!ec->lock_user_shade) && (!ec->fullscreen) && (!ec->maximized) && ((!ec->border.name) || (!borderless))) { mi = e_menu_item_new(m); e_menu_item_label_set(mi, _("Shade")); e_menu_item_check_set(mi, 1); e_menu_item_toggle_set(mi, (ec->shaded ? 1 : 0)); e_menu_item_callback_set(mi, _e_client_menu_cb_shade, ec); e_menu_item_icon_edje_set(mi, e_theme_edje_file_get("base/theme/borders", "e/widgets/border/default/shade"), "e/widgets/border/default/shade"); } if ((!ec->fullscreen) && (!ec->lock_border) && (!ec->shading) && (!ec->shaded) && (!ec->mwm.borderless)) { mi = e_menu_item_new(m); e_menu_item_label_set(mi, _("Borderless")); e_menu_item_check_set(mi, 1); e_menu_item_toggle_set(mi, borderless); e_menu_item_callback_set(mi, _e_client_menu_cb_borderless, ec); e_menu_item_icon_edje_set(mi, e_theme_edje_file_get("base/theme/borders", "e/widgets/border/default/borderless"), "e/widgets/border/default/borderless"); } if (e_comp_config_get()->enable_advanced_features) { E_Menu *subm; mi = e_menu_item_new(m); e_menu_item_label_set(mi, _("Composite")); e_util_menu_item_theme_icon_set(mi, "preferences-composite"); subm = e_menu_new(); e_menu_item_submenu_set(mi, subm); e_object_unref(E_OBJECT(subm)); e_object_data_set(E_OBJECT(subm), e_comp); if (e_pixmap_type_get(ec->pixmap) == E_PIXMAP_TYPE_X) { mi = e_menu_item_new(subm); e_menu_item_check_set(mi, 1); e_menu_item_label_set(mi, _("Unredirected")); e_menu_item_toggle_set(mi, !ec->redirected); e_menu_item_callback_set(mi, _e_client_menu_cb_redirect_set, ec); } } if (!ec->lock_close) { mi = e_menu_item_new(m); e_menu_item_separator_set(mi, 1); mi = e_menu_item_new(m); e_menu_item_label_set(mi, _("Close")); e_menu_item_callback_set(mi, _e_client_menu_cb_close, ec); e_menu_item_icon_edje_set(mi, e_theme_edje_file_get("base/theme/borders", "e/widgets/border/default/close"), "e/widgets/border/default/close"); } EINA_LIST_FOREACH(menu_hooks, l, h) h->cb(h->data, ec); } E_API void e_int_client_menu_show(E_Client *ec, Evas_Coord x, Evas_Coord y, int key, unsigned int timestamp) { e_int_client_menu_create(ec); if (key) e_menu_activate_key(ec->border_menu, ec->zone, x, y, 1, 1, E_MENU_POP_DIRECTION_DOWN); else e_menu_activate_mouse(ec->border_menu, ec->zone, x, y, 1, 1, E_MENU_POP_DIRECTION_DOWN, timestamp); } E_API void e_int_client_menu_del(E_Client *ec) { if (!ec->border_menu) return; e_menu_post_deactivate_callback_set(ec->border_menu, NULL, NULL); E_FREE_FUNC(ec->border_menu, e_object_del); } static void _e_client_cb_border_menu_end(void *data EINA_UNUSED, E_Menu *m) { E_Client *ec; ec = e_object_data_get(E_OBJECT(m)); if (ec) { /* If the client exists, delete all associated menus */ e_int_client_menu_del(ec); } else { /* Just delete this menu */ e_object_del(E_OBJECT(m)); } } static void _e_client_menu_cb_locks(void *data, E_Menu *m EINA_UNUSED, E_Menu_Item *mi EINA_UNUSED) { E_Client *ec; ec = data; if (ec->border_locks_dialog) e_client_activate(e_win_client_get(ec->border_locks_dialog->dia->win), 1); else e_int_client_locks(ec); } static void _e_client_menu_cb_remember(void *data, E_Menu *m EINA_UNUSED, E_Menu_Item *mi EINA_UNUSED) { E_Client *ec; ec = data; if (ec->border_remember_dialog) e_client_activate(e_win_client_get(ec->border_remember_dialog->dia->win), 1); else e_int_client_remember(ec); } static void _e_client_menu_cb_border(void *data, E_Menu *m EINA_UNUSED, E_Menu_Item *mi EINA_UNUSED) { E_Client *ec; char buf[256]; ec = data; if (ec->border_border_dialog) e_client_activate(e_win_client_get(ec->border_border_dialog->dia->win), 1); else { snprintf(buf, sizeof(buf), "%p", ec); e_configure_registry_call("internal/borders_border", NULL, buf); } } static void _e_client_menu_cb_borderless(void *data, E_Menu *m EINA_UNUSED, E_Menu_Item *mi) { E_Client *ec = data; EC_CHANGED(ec); ec->border.changed = 1; ec->borderless = mi->toggle; } static void _e_client_menu_cb_redirect_set(void *data, E_Menu *m EINA_UNUSED, E_Menu_Item *mi EINA_UNUSED) { e_comp_client_redirect_toggle(data); } static void _e_client_menu_cb_close(void *data, E_Menu *m EINA_UNUSED, E_Menu_Item *mi EINA_UNUSED) { E_Client *ec; ec = data; if (!ec->lock_close) e_client_act_close_begin(ec); } static void _e_client_menu_cb_iconify(void *data, E_Menu *m EINA_UNUSED, E_Menu_Item *mi EINA_UNUSED) { E_Client *ec; ec = data; if (!ec->lock_user_iconify) { if (ec->iconic) e_client_uniconify(ec); else e_client_iconify(ec); } } static void _e_client_menu_cb_kill(void *data, E_Menu *m EINA_UNUSED, E_Menu_Item *mi EINA_UNUSED) { E_Action *a; E_Client *ec; ec = data; if ((ec->lock_close) || (ec->internal)) return; a = e_action_find("window_kill"); if ((a) && (a->func.go)) a->func.go(E_OBJECT(ec), NULL); } static void _e_client_menu_cb_move(void *data, E_Menu *m EINA_UNUSED, E_Menu_Item *mi EINA_UNUSED) { E_Client *ec; ec = data; if (!ec->lock_user_location) e_client_act_move_keyboard(ec); } static void _e_client_menu_cb_resize(void *data, E_Menu *m EINA_UNUSED, E_Menu_Item *mi EINA_UNUSED) { E_Client *ec; ec = data; if (!ec->lock_user_size) e_client_act_resize_keyboard(ec); } static void _e_client_menu_cb_maximize_pre(void *data, E_Menu *m EINA_UNUSED, E_Menu_Item *mi) { E_Menu *subm; E_Menu_Item *submi; E_Client *ec; if (!(ec = data)) return; subm = e_menu_new(); e_object_data_set(E_OBJECT(subm), ec); e_menu_item_submenu_set(mi, subm); e_object_unref(E_OBJECT(subm)); if ((!ec->lock_user_fullscreen) && (!ec->shaded)) { submi = e_menu_item_new(subm); e_menu_item_label_set(submi, _("Fullscreen")); e_menu_item_check_set(submi, 1); e_menu_item_toggle_set(submi, ec->fullscreen); e_menu_item_callback_set(submi, _e_client_menu_cb_fullscreen, ec); e_menu_item_icon_edje_set(submi, e_theme_edje_file_get("base/theme/borders", "e/widgets/border/default/fullscreen"), "e/widgets/border/default/fullscreen"); } if (!ec->fullscreen) { submi = e_menu_item_new(subm); e_menu_item_label_set(submi, _("Maximize")); e_menu_item_radio_set(submi, 1); e_menu_item_radio_group_set(submi, 3); e_menu_item_toggle_set(submi, (ec->maximized & E_MAXIMIZE_DIRECTION) == E_MAXIMIZE_BOTH); e_menu_item_callback_set(submi, _e_client_menu_cb_maximize, ec); e_menu_item_icon_edje_set(submi, e_theme_edje_file_get("base/theme/borders", "e/widgets/border/default/maximize"), "e/widgets/border/default/maximize"); submi = e_menu_item_new(subm); e_menu_item_label_set(submi, _("Maximize Vertically")); e_menu_item_radio_set(submi, 1); e_menu_item_radio_group_set(submi, 3); e_menu_item_toggle_set(submi, (ec->maximized & E_MAXIMIZE_DIRECTION) == E_MAXIMIZE_VERTICAL); e_menu_item_callback_set(submi, _e_client_menu_cb_maximize_vertically, ec); e_menu_item_icon_edje_set(submi, e_theme_edje_file_get("base/theme/borders", "e/widgets/border/default/maximize"), "e/widgets/border/default/maximize"); submi = e_menu_item_new(subm); e_menu_item_label_set(submi, _("Maximize Horizontally")); e_menu_item_radio_set(submi, 1); e_menu_item_radio_group_set(submi, 3); e_menu_item_toggle_set(submi, (ec->maximized & E_MAXIMIZE_DIRECTION) == E_MAXIMIZE_HORIZONTAL); e_menu_item_callback_set(submi, _e_client_menu_cb_maximize_horizontally, ec); e_menu_item_icon_edje_set(submi, e_theme_edje_file_get("base/theme/borders", "e/widgets/border/default/maximize"), "e/widgets/border/default/maximize"); submi = e_menu_item_new(subm); e_menu_item_label_set(submi, _("Maximize Left")); e_menu_item_radio_set(submi, 1); e_menu_item_radio_group_set(submi, 3); e_menu_item_toggle_set(submi, (ec->maximized & E_MAXIMIZE_DIRECTION) == E_MAXIMIZE_LEFT); e_menu_item_callback_set(submi, _e_client_menu_cb_maximize_left, ec); e_menu_item_icon_edje_set(submi, e_theme_edje_file_get("base/theme/borders", "e/widgets/border/default/maximize"), "e/widgets/border/default/maximize"); submi = e_menu_item_new(subm); e_menu_item_label_set(submi, _("Maximize Right")); e_menu_item_radio_set(submi, 1); e_menu_item_radio_group_set(submi, 3); e_menu_item_toggle_set(submi, (ec->maximized & E_MAXIMIZE_DIRECTION) == E_MAXIMIZE_RIGHT); e_menu_item_callback_set(submi, _e_client_menu_cb_maximize_right, ec); e_menu_item_icon_edje_set(submi, e_theme_edje_file_get("base/theme/borders", "e/widgets/border/default/maximize"), "e/widgets/border/default/maximize"); submi = e_menu_item_new(subm); e_menu_item_label_set(submi, _("Unmaximize")); e_menu_item_radio_set(submi, 1); e_menu_item_radio_group_set(submi, 3); e_menu_item_toggle_set(submi, (ec->maximized & E_MAXIMIZE_DIRECTION) == E_MAXIMIZE_NONE); e_menu_item_callback_set(submi, _e_client_menu_cb_unmaximize, ec); e_menu_item_icon_edje_set(submi, e_theme_edje_file_get("base/theme/borders", "e/widgets/border/default/maximize"), "e/widgets/border/default/maximize"); } } static void _e_client_menu_cb_maximize(void *data, E_Menu *m EINA_UNUSED, E_Menu_Item *mi EINA_UNUSED) { E_Client *ec; ec = data; if (!ec->lock_user_maximize) e_client_maximize(ec, (e_config->maximize_policy & E_MAXIMIZE_TYPE) | E_MAXIMIZE_BOTH); } static void _e_client_menu_cb_maximize_vertically(void *data, E_Menu *m EINA_UNUSED, E_Menu_Item *mi EINA_UNUSED) { E_Client *ec; ec = data; if (!ec->lock_user_maximize) { if ((ec->maximized & E_MAXIMIZE_HORIZONTAL)) e_client_unmaximize(ec, E_MAXIMIZE_HORIZONTAL); e_client_maximize(ec, (e_config->maximize_policy & E_MAXIMIZE_TYPE) | E_MAXIMIZE_VERTICAL); } } static void _e_client_menu_cb_maximize_horizontally(void *data, E_Menu *m EINA_UNUSED, E_Menu_Item *mi EINA_UNUSED) { E_Client *ec; ec = data; if (!ec->lock_user_maximize) { if ((ec->maximized & E_MAXIMIZE_VERTICAL)) e_client_unmaximize(ec, E_MAXIMIZE_VERTICAL); e_client_maximize(ec, (e_config->maximize_policy & E_MAXIMIZE_TYPE) | E_MAXIMIZE_HORIZONTAL); } } static void _e_client_menu_cb_maximize_left(void *data, E_Menu *m EINA_UNUSED, E_Menu_Item *mi EINA_UNUSED) { E_Client *ec; ec = data; if (!ec->lock_user_maximize) { if ((ec->maximized & E_MAXIMIZE_DIRECTION)) e_client_unmaximize(ec, ec->maximized & E_MAXIMIZE_DIRECTION); e_client_maximize(ec, (e_config->maximize_policy & E_MAXIMIZE_TYPE) | E_MAXIMIZE_LEFT); } } static void _e_client_menu_cb_maximize_right(void *data, E_Menu *m EINA_UNUSED, E_Menu_Item *mi EINA_UNUSED) { E_Client *ec; ec = data; if (!ec->lock_user_maximize) { if ((ec->maximized & E_MAXIMIZE_DIRECTION)) e_client_unmaximize(ec, ec->maximized & E_MAXIMIZE_DIRECTION); e_client_maximize(ec, (e_config->maximize_policy & E_MAXIMIZE_TYPE) | E_MAXIMIZE_RIGHT); } } static void _e_client_menu_cb_unmaximize(void *data, E_Menu *m EINA_UNUSED, E_Menu_Item *mi EINA_UNUSED) { E_Client *ec; ec = data; e_client_unmaximize(ec, E_MAXIMIZE_BOTH); } static void _e_client_menu_cb_shade(void *data, E_Menu *m EINA_UNUSED, E_Menu_Item *mi EINA_UNUSED) { E_Client *ec; ec = data; if (!ec->lock_user_shade) { if (ec->shaded) e_client_unshade(ec, ec->shade_dir); else e_client_shade(ec, E_DIRECTION_UP); } } static void _e_client_menu_cb_resistance(void *data, E_Menu *m EINA_UNUSED, E_Menu_Item *mi EINA_UNUSED) { E_Client *ec; ec = data; ec->offer_resistance = !ec->offer_resistance; } static void _e_client_menu_cb_icon_edit(void *data, E_Menu *m EINA_UNUSED, E_Menu_Item *mi EINA_UNUSED) { E_Client *ec; ec = data; e_desktop_client_edit(ec); } static void _e_client_menu_cb_colors_edit_moveresize(E_Client *ec, ...) { evas_object_geometry_set(ec->color_editor, ec->client.x, ec->client.y, ec->client.w, ec->client.h); e_comp_shape_queue(); } static void _e_client_menu_cb_colors_edit_del(void *data, ...) { E_Client *ec = data; E_FREE_FUNC(ec->color_editor, evas_object_del); evas_object_event_callback_del_full(ec->frame, EVAS_CALLBACK_MOVE, (Evas_Object_Event_Cb)_e_client_menu_cb_colors_edit_moveresize, ec); evas_object_event_callback_del_full(ec->frame, EVAS_CALLBACK_RESIZE, (Evas_Object_Event_Cb)_e_client_menu_cb_colors_edit_moveresize, ec); e_client_comp_hidden_set(ec, 0); e_comp_ungrab_input(1, 1); e_comp_shape_queue(); } static void _e_client_menu_cb_colors_edit(void *data, E_Menu *m EINA_UNUSED, E_Menu_Item *mi EINA_UNUSED) { Evas_Object *o; E_Client *ec = data; ec->color_editor = o = elm_color_class_editor_add(e_comp->elm, e_client_util_win_get(data)); if (!o) return; e_comp_shape_queue(); evas_object_geometry_set(o, ec->client.x, ec->client.y, ec->client.w, ec->client.h); evas_object_layer_set(o, E_LAYER_POPUP); evas_object_show(o); e_client_comp_hidden_set(ec, 1); e_comp_grab_input(1, 1); evas_object_smart_callback_add(o, "application_closed", (Evas_Smart_Cb)_e_client_menu_cb_colors_edit_del, ec); evas_object_smart_callback_add(o, "dismissed", (Evas_Smart_Cb)_e_client_menu_cb_colors_edit_del, ec); evas_object_event_callback_add(o, EVAS_CALLBACK_DEL, (Evas_Object_Event_Cb)_e_client_menu_cb_colors_edit_del, ec); evas_object_event_callback_add(ec->frame, EVAS_CALLBACK_MOVE, (Evas_Object_Event_Cb)_e_client_menu_cb_colors_edit_moveresize, ec); evas_object_event_callback_add(ec->frame, EVAS_CALLBACK_RESIZE, (Evas_Object_Event_Cb)_e_client_menu_cb_colors_edit_moveresize, ec); } static void _e_client_menu_cb_application_pre(void *data, E_Menu *m EINA_UNUSED, E_Menu_Item *mi) { E_Menu *subm; E_Menu_Item *submi; E_Client *ec; if (!(ec = data)) return; subm = e_menu_new(); e_object_data_set(E_OBJECT(subm), ec); e_menu_item_submenu_set(mi, subm); e_object_unref(E_OBJECT(subm)); if (ec->desktop) { submi = e_menu_item_new(subm); e_menu_item_label_set(submi, _("Edit Icon")); e_menu_item_callback_set(submi, _e_client_menu_cb_icon_edit, ec); e_util_desktop_menu_item_icon_add(ec->desktop, 16, submi); } else if (ec->icccm.class) { /* icons with no class useless to borders */ submi = e_menu_item_new(subm); e_menu_item_label_set(submi, _("Create Icon")); e_menu_item_callback_set(submi, _e_client_menu_cb_icon_edit, ec); } submi = e_menu_item_new(subm); e_menu_item_separator_set(submi, 1); submi = e_menu_item_new(subm); e_menu_item_label_set(submi, _("Add to Favorites Menu")); e_menu_item_callback_set(submi, _e_client_menu_cb_fav_add, ec); e_util_menu_item_theme_icon_set(submi, "user-bookmarks"); submi = e_menu_item_new(subm); e_menu_item_label_set(submi, _("Add to IBar")); e_menu_item_submenu_pre_callback_set(submi, _e_client_menu_cb_ibar_add_pre, ec); e_util_menu_item_theme_icon_set(submi, "preferences-applications-ibar"); if (e_configure_registry_exists("keyboard_and_mouse/key_bindings")) { submi = e_menu_item_new(subm); e_menu_item_label_set(submi, _("Create Keyboard Shortcut")); e_menu_item_callback_set(submi, _e_client_menu_cb_kbdshrtct_add, ec); e_util_menu_item_theme_icon_set(submi, "preferences-desktop-keyboard"); } if (ec->color_editor || (!e_pixmap_is_x(ec->pixmap))) return; submi = e_menu_item_new(subm); e_menu_item_label_set(submi, _("Edit Color Scheme")); e_menu_item_callback_set(submi, _e_client_menu_cb_colors_edit, ec); e_util_menu_item_theme_icon_set(submi, "preferences-desktop-color"); } static void _e_client_menu_cb_window_pre(void *data, E_Menu *m EINA_UNUSED, E_Menu_Item *mi) { E_Menu *subm; E_Menu_Item *submi; E_Client *ec; Eina_Bool resize = EINA_FALSE; if (!(ec = data)) return; subm = e_menu_new(); e_object_data_set(E_OBJECT(subm), ec); e_menu_item_submenu_set(mi, subm); e_object_unref(E_OBJECT(subm)); /* internal dialog which is resizable */ if (ec->internal && (ec->netwm.type == E_WINDOW_TYPE_DIALOG)) resize = (ec->icccm.max_w != ec->icccm.min_w); if (resize || (ec->netwm.type == E_WINDOW_TYPE_NORMAL) || (ec->netwm.type == E_WINDOW_TYPE_UNKNOWN)) { if (!(((ec->icccm.min_w == ec->icccm.max_w) && (ec->icccm.min_h == ec->icccm.max_h)) || (ec->lock_user_maximize))) { if ((!ec->lock_user_maximize) && (!ec->shaded)) { submi = e_menu_item_new(subm); e_menu_item_label_set(submi, _("Maximize")); e_menu_item_submenu_pre_callback_set(submi, _e_client_menu_cb_maximize_pre, ec); e_menu_item_icon_edje_set(submi, e_theme_edje_file_get("base/theme/borders", "e/widgets/border/default/maximize"), "e/widgets/border/default/maximize"); } } if ((!ec->lock_user_iconify) && (!ec->fullscreen)) { submi = e_menu_item_new(subm); e_menu_item_label_set(submi, _("Iconify")); e_menu_item_callback_set(submi, _e_client_menu_cb_iconify, ec); e_menu_item_icon_edje_set(submi, e_theme_edje_file_get("base/theme/borders", "e/widgets/border/default/minimize"), "e/widgets/border/default/minimize"); } } if ((!ec->lock_user_location) && (!ec->fullscreen) && (((ec->maximized & E_MAXIMIZE_DIRECTION) != E_MAXIMIZE_BOTH) || e_config->allow_manip)) { submi = e_menu_item_new(subm); e_menu_item_label_set(submi, _("Move with keyboard")); e_menu_item_callback_set(submi, _e_client_menu_cb_move, ec); e_menu_item_icon_edje_set(submi, e_theme_edje_file_get("base/theme/borders", "e/widgets/border/default/move_icon"), "e/widgets/border/default/move_icon"); } if (((!ec->lock_user_size) && (!ec->fullscreen) && (((ec->maximized & E_MAXIMIZE_DIRECTION) != E_MAXIMIZE_BOTH) || e_config->allow_manip)) && ((ec->netwm.type == E_WINDOW_TYPE_NORMAL) || (ec->netwm.type == E_WINDOW_TYPE_UNKNOWN))) { submi = e_menu_item_new(subm); e_menu_item_label_set(submi, _("Resize with keyboard")); e_menu_item_callback_set(submi, _e_client_menu_cb_resize, ec); e_menu_item_icon_edje_set(submi, e_theme_edje_file_get("base/theme/borders", "e/widgets/border/default/resize_icon"), "e/widgets/border/default/resize_icon"); } submi = e_menu_item_new(subm); e_menu_item_separator_set(submi, 1); if ((!ec->lock_user_stacking) && (!ec->fullscreen)) { submi = e_menu_item_new(subm); e_menu_item_label_set(submi, _("Stacking")); e_menu_item_submenu_pre_callback_set(submi, _e_client_menu_cb_stacking_pre, ec); e_menu_item_icon_edje_set(submi, e_theme_edje_file_get("base/theme/borders", "e/widgets/border/default/stacking"), "e/widgets/border/default/stacking"); } submi = e_menu_item_new(subm); e_menu_item_label_set(submi, _("Skip")); e_menu_item_submenu_pre_callback_set(submi, _e_client_menu_cb_skip_pre, ec); e_menu_item_icon_edje_set(submi, e_theme_edje_file_get("base/theme/borders", "e/widgets/border/default/skip"), "e/widgets/border/default/skip"); if ((!ec->lock_border) && (!ec->mwm.borderless)) { submi = e_menu_item_new(subm); e_menu_item_label_set(submi, _("Border")); e_menu_item_submenu_pre_callback_set(submi, _e_client_menu_cb_border_pre, ec); e_menu_item_icon_edje_set(submi, e_theme_edje_file_get("base/theme/borders", "e/widgets/border/default/borderless"), "e/widgets/border/default/borderless"); } submi = e_menu_item_new(subm); e_menu_item_separator_set(submi, 1); submi = e_menu_item_new(subm); e_menu_item_label_set(submi, _("Locks")); e_menu_item_callback_set(submi, _e_client_menu_cb_locks, ec); e_menu_item_icon_edje_set(submi, e_theme_edje_file_get("base/theme/borders", "e/widgets/border/default/locks"), "e/widgets/border/default/locks"); submi = e_menu_item_new(subm); e_menu_item_label_set(submi, _("Remember")); e_menu_item_callback_set(submi, _e_client_menu_cb_remember, ec); e_menu_item_icon_edje_set(submi, e_theme_edje_file_get("base/theme/borders", "e/widgets/border/default/remember"), "e/widgets/border/default/remember"); submi = e_menu_item_new(subm); e_menu_item_separator_set(submi, 1); if ((!ec->internal) && (!ec->lock_close)) { submi = e_menu_item_new(subm); e_menu_item_label_set(submi, _("Kill")); e_menu_item_callback_set(submi, _e_client_menu_cb_kill, ec); e_menu_item_icon_edje_set(submi, e_theme_edje_file_get("base/theme/borders", "e/widgets/border/default/kill"), "e/widgets/border/default/kill"); } submi = e_menu_item_new(subm); e_menu_item_label_set(submi, _("ICCCM/NetWM")); e_menu_item_callback_set(submi, _e_client_menu_cb_prop, ec); e_menu_item_icon_edje_set(submi, e_theme_edje_file_get("base/theme/borders", "e/widgets/border/default/properties"), "e/widgets/border/default/properties"); } static void _e_client_menu_cb_prop(void *data, E_Menu *m EINA_UNUSED, E_Menu_Item *mi EINA_UNUSED) { E_Client *ec; ec = data; e_int_client_prop(ec); } static void _e_client_menu_cb_stick(void *data, E_Menu *m EINA_UNUSED, E_Menu_Item *mi EINA_UNUSED) { E_Client *ec; ec = data; if (!ec->lock_user_sticky) { if (ec->sticky) e_client_unstick(ec); else e_client_stick(ec); } } static void _e_client_menu_cb_on_top(void *data, E_Menu *m EINA_UNUSED, E_Menu_Item *mi EINA_UNUSED) { E_Client *ec; ec = data; if (ec->layer != E_LAYER_CLIENT_ABOVE) evas_object_layer_set(ec->frame, E_LAYER_CLIENT_ABOVE); } static void _e_client_menu_cb_below(void *data, E_Menu *m EINA_UNUSED, E_Menu_Item *mi EINA_UNUSED) { E_Client *ec; ec = data; if (ec->layer != E_LAYER_CLIENT_BELOW) evas_object_layer_set(ec->frame, E_LAYER_CLIENT_BELOW); } static void _e_client_menu_cb_normal(void *data, E_Menu *m EINA_UNUSED, E_Menu_Item *mi EINA_UNUSED) { E_Client *ec; ec = data; if (ec->layer != E_LAYER_CLIENT_NORMAL) evas_object_layer_set(ec->frame, E_LAYER_CLIENT_NORMAL); } static void _e_client_menu_cb_fullscreen(void *data, E_Menu *m EINA_UNUSED, E_Menu_Item *mi) { E_Client *ec; int toggle; if (!(ec = data)) return; if (!ec->lock_user_fullscreen) { toggle = e_menu_item_toggle_get(mi); if (toggle) e_client_fullscreen(ec, e_config->fullscreen_policy); else e_client_unfullscreen(ec); } } static void _e_client_menu_cb_skip_winlist(void *data, E_Menu *m EINA_UNUSED, E_Menu_Item *mi) { E_Client *ec; if (!(ec = data)) return; if (((ec->icccm.accepts_focus) || (ec->icccm.take_focus)) && (!ec->netwm.state.skip_taskbar)) ec->user_skip_winlist = e_menu_item_toggle_get(mi); else ec->user_skip_winlist = 0; ec->changed = 1; e_remember_update(ec); } static void _e_client_menu_cb_skip_pager(void *data, E_Menu *m EINA_UNUSED, E_Menu_Item *mi) { E_Client *ec; if (!(ec = data)) return; if ((ec->icccm.accepts_focus) || (ec->icccm.take_focus)) ec->netwm.state.skip_pager = e_menu_item_toggle_get(mi); else ec->netwm.state.skip_pager = 0; ec->changed = 1; e_remember_update(ec); } static void _e_client_menu_cb_skip_taskbar(void *data, E_Menu *m EINA_UNUSED, E_Menu_Item *mi) { E_Client *ec; if (!(ec = data)) return; if ((ec->icccm.accepts_focus) || (ec->icccm.take_focus)) ec->netwm.state.skip_taskbar = e_menu_item_toggle_get(mi); else ec->netwm.state.skip_taskbar = 0; ec->changed = 1; e_remember_update(ec); } #ifndef DESKMIRROR_TEST static void _e_client_menu_cb_sendto_icon_pre(void *data, E_Menu *m, E_Menu_Item *mi) { E_Desk *desk = NULL; Evas_Object *o = NULL; const char *bgfile = NULL; int tw = 0, th = 0; desk = data; E_OBJECT_CHECK(desk); tw = 50; th = (tw * desk->zone->h) / desk->zone->w; bgfile = e_bg_file_get(desk->zone->num, desk->x, desk->y); o = e_thumb_icon_add(m->evas); e_thumb_icon_file_set(o, bgfile, "e/desktop/background"); eina_stringshare_del(bgfile); e_thumb_icon_size_set(o, tw, th); e_thumb_icon_begin(o); mi->icon_object = o; } #endif static void _e_client_menu_cb_align_setup(E_Client *ec, Evas_Object_Event_Cb cb) { E_Notification_Notify n; Evas_Object *o; memset(&n, 0, sizeof(E_Notification_Notify)); n.timeout = 3000; n.summary = _("Alignment"); n.body = _("Click an object to align with."); n.urgency = E_NOTIFICATION_NOTIFY_URGENCY_NORMAL; e_notification_client_send(&n, NULL, NULL); o = evas_object_rectangle_add(e_comp->evas); evas_object_resize(o, e_comp->w, e_comp->h); evas_object_color_set(o, 0, 0, 0, 0); evas_object_layer_set(o, E_LAYER_POPUP); evas_object_show(o); evas_object_event_callback_add(o, EVAS_CALLBACK_MOUSE_DOWN, cb, ec); e_comp_shape_queue(); } static Evas_Object * _e_client_menu_cb_align_cb(Evas *e, Evas_Object *obj, Evas_Event_Mouse_Down *ev) { evas_object_hide(obj); evas_object_del(obj); e_comp_shape_queue(); return evas_object_top_at_xy_get(e, ev->output.x, ev->output.y, 0, 0); } static void _e_client_menu_cb_align_on_center(E_Client *ec, Evas *e, Evas_Object *obj, Evas_Event_Mouse_Down *ev) { Evas_Object *o; o = _e_client_menu_cb_align_cb(e, obj, ev); e_comp_object_util_center_on(ec->frame, o); } static void _e_client_menu_cb_align_center(void *data, E_Menu *m, E_Menu_Item *mi EINA_UNUSED) { E_Client *ec = e_object_data_get(E_OBJECT(m)); if (data) _e_client_menu_cb_align_setup(ec, (Evas_Object_Event_Cb)_e_client_menu_cb_align_on_center); else e_comp_object_util_center(ec->frame); } static void _e_client_menu_cb_align_on_top(E_Client *ec, Evas *e, Evas_Object *obj, Evas_Event_Mouse_Down *ev) { Evas_Object *o; int y; o = _e_client_menu_cb_align_cb(e, obj, ev); evas_object_geometry_get(o, NULL, &y, NULL, NULL); evas_object_move(ec->frame, ec->x, y); } static void _e_client_menu_cb_align_top(void *data, E_Menu *m, E_Menu_Item *mi EINA_UNUSED) { E_Client *ec = e_object_data_get(E_OBJECT(m)); if (data) _e_client_menu_cb_align_setup(ec, (Evas_Object_Event_Cb)_e_client_menu_cb_align_on_top); else { int y; e_zone_useful_geometry_get(ec->zone, NULL, &y, NULL, NULL); evas_object_move(ec->frame, ec->x, y); } } static void _e_client_menu_cb_align_on_left(E_Client *ec, Evas *e, Evas_Object *obj, Evas_Event_Mouse_Down *ev) { Evas_Object *o; int x; o = _e_client_menu_cb_align_cb(e, obj, ev); evas_object_geometry_get(o, &x, NULL, NULL, NULL); evas_object_move(ec->frame, x, ec->y); } static void _e_client_menu_cb_align_left(void *data, E_Menu *m, E_Menu_Item *mi EINA_UNUSED) { E_Client *ec = e_object_data_get(E_OBJECT(m)); if (data) _e_client_menu_cb_align_setup(ec, (Evas_Object_Event_Cb)_e_client_menu_cb_align_on_left); else { int x; e_zone_useful_geometry_get(ec->zone, &x, NULL, NULL, NULL); evas_object_move(ec->frame, x, ec->y); } } static void _e_client_menu_cb_align_on_right(E_Client *ec, Evas *e, Evas_Object *obj, Evas_Event_Mouse_Down *ev) { Evas_Object *o; int x, w; o = _e_client_menu_cb_align_cb(e, obj, ev); evas_object_geometry_get(o, &x, NULL, &w, NULL); evas_object_move(ec->frame, x + w - ec->w, ec->y); } static void _e_client_menu_cb_align_right(void *data, E_Menu *m, E_Menu_Item *mi EINA_UNUSED) { E_Client *ec = e_object_data_get(E_OBJECT(m)); if (data) _e_client_menu_cb_align_setup(ec, (Evas_Object_Event_Cb)_e_client_menu_cb_align_on_right); else { int x, w; e_zone_useful_geometry_get(ec->zone, &x, NULL, &w, NULL); evas_object_move(ec->frame, x + w - ec->w, ec->y); } } static void _e_client_menu_cb_align_on_bottom(E_Client *ec, Evas *e, Evas_Object *obj, Evas_Event_Mouse_Down *ev) { Evas_Object *o; int y, h; o = _e_client_menu_cb_align_cb(e, obj, ev); evas_object_geometry_get(o, NULL, &y, NULL, &h); evas_object_move(ec->frame, ec->x, y + h - ec->h); } static void _e_client_menu_cb_align_bottom(void *data, E_Menu *m, E_Menu_Item *mi EINA_UNUSED) { E_Client *ec = e_object_data_get(E_OBJECT(m)); if (data) _e_client_menu_cb_align_setup(ec, (Evas_Object_Event_Cb)_e_client_menu_cb_align_on_bottom); else { int y, h; e_zone_useful_geometry_get(ec->zone, NULL, &y, NULL, &h); evas_object_move(ec->frame, ec->x, y + h - ec->h); } } static void _e_client_menu_cb_align_pre(void *data, E_Menu *m EINA_UNUSED, E_Menu_Item *mi) { E_Menu *subm, *mm; E_Menu_Item *submi; E_Client *ec = data; subm = e_menu_new(); e_menu_title_set(subm, _("Alignment")); e_object_data_set(E_OBJECT(subm), ec); e_menu_item_submenu_set(mi, subm); e_object_unref(E_OBJECT(subm)); submi = e_menu_item_new(subm); e_menu_item_label_set(submi, _("Center")); e_menu_item_callback_set(submi, _e_client_menu_cb_align_center, NULL); mm = e_menu_new(); e_object_data_set(E_OBJECT(mm), ec); e_menu_item_submenu_set(submi, mm); e_object_unref(E_OBJECT(mm)); submi = e_menu_item_new(mm); e_menu_item_label_set(submi, _("On window...")); e_menu_item_callback_set(submi, _e_client_menu_cb_align_center, (void*)1); submi = e_menu_item_new(subm); e_menu_item_label_set(submi, _("Top")); e_menu_item_callback_set(submi, _e_client_menu_cb_align_top, NULL); mm = e_menu_new(); e_object_data_set(E_OBJECT(mm), ec); e_menu_item_submenu_set(submi, mm); e_object_unref(E_OBJECT(mm)); submi = e_menu_item_new(mm); e_menu_item_label_set(submi, _("Of window...")); e_menu_item_callback_set(submi, _e_client_menu_cb_align_top, (void*)1); submi = e_menu_item_new(subm); e_menu_item_label_set(submi, _("Left")); e_menu_item_callback_set(submi, _e_client_menu_cb_align_left, NULL); mm = e_menu_new(); e_object_data_set(E_OBJECT(mm), ec); e_menu_item_submenu_set(submi, mm); e_object_unref(E_OBJECT(mm)); submi = e_menu_item_new(mm); e_menu_item_label_set(submi, _("Of window...")); e_menu_item_callback_set(submi, _e_client_menu_cb_align_left, (void*)1); submi = e_menu_item_new(subm); e_menu_item_label_set(submi, _("Right")); e_menu_item_callback_set(submi, _e_client_menu_cb_align_right, NULL); mm = e_menu_new(); e_object_data_set(E_OBJECT(mm), ec); e_menu_item_submenu_set(submi, mm); e_object_unref(E_OBJECT(mm)); submi = e_menu_item_new(mm); e_menu_item_label_set(submi, _("Of window...")); e_menu_item_callback_set(submi, _e_client_menu_cb_align_right, (void*)1); submi = e_menu_item_new(subm); e_menu_item_label_set(submi, _("Bottom")); e_menu_item_callback_set(submi, _e_client_menu_cb_align_bottom, NULL); mm = e_menu_new(); e_object_data_set(E_OBJECT(mm), ec); e_menu_item_submenu_set(submi, mm); e_object_unref(E_OBJECT(mm)); submi = e_menu_item_new(mm); e_menu_item_label_set(submi, _("Of window...")); e_menu_item_callback_set(submi, _e_client_menu_cb_align_bottom, (void*)1); } static void _e_client_menu_cb_sendto_pre(void *data, E_Menu *m EINA_UNUSED, E_Menu_Item *mi) { E_Menu *subm; E_Menu_Item *submi; E_Client *ec; E_Zone *zone; Eina_List *l = NULL; char buf[128]; int zones, i; ec = data; zones = eina_list_count(e_comp->zones); subm = e_menu_new(); e_object_data_set(E_OBJECT(subm), ec); e_menu_item_submenu_set(mi, subm); e_object_unref(E_OBJECT(subm)); EINA_LIST_FOREACH(e_comp->zones, l, zone) { if (zones > 1) { snprintf(buf, sizeof(buf), _("Screen %d"), zone->num); submi = e_menu_item_new(subm); e_menu_item_label_set(submi, buf); e_menu_item_disabled_set(submi, EINA_TRUE); } for (i = 0; i < zone->desk_x_count * zone->desk_y_count; i++) { E_Desk *desk; #ifdef DESKMIRROR_TEST int tw = 50, th; #endif desk = zone->desks[i]; #ifdef DESKMIRROR_TEST th = (tw * desk->zone->h) / desk->zone->w; #endif submi = e_menu_item_new(subm); e_menu_item_label_set(submi, desk->name); e_menu_item_radio_set(submi, 1); e_menu_item_radio_group_set(submi, 2); #ifdef DESKMIRROR_TEST e_menu_item_icon_file_set(submi, "sup"); #endif if ((ec->zone == zone) && (!ec->iconic) && (ec->desk == desk)) e_menu_item_toggle_set(submi, 1); else e_menu_item_callback_set(submi, _e_client_menu_cb_sendto, desk); #ifdef DESKMIRROR_TEST submi->icon_object = e_deskmirror_add(desk, 0, 0); evas_object_size_hint_min_set(submi->icon_object, tw, th); evas_object_show(submi->icon_object); #else e_menu_item_realize_callback_set(submi, _e_client_menu_cb_sendto_icon_pre, desk); #endif } } } static void _e_client_menu_cb_sendto(void *data, E_Menu *m, E_Menu_Item *mi EINA_UNUSED) { E_Desk *desk; E_Client *ec; desk = data; ec = e_object_data_get(E_OBJECT(m)); if ((ec) && (desk)) { ec->hidden = 0; e_client_desk_set(ec, desk); } } static void _e_client_menu_cb_pin(void *data EINA_UNUSED, E_Menu *m, E_Menu_Item *mi EINA_UNUSED) { E_Client *ec; ec = e_object_data_get(E_OBJECT(m)); if (ec) e_client_pinned_set(ec, 1); } static void _e_client_menu_cb_unpin(void *data EINA_UNUSED, E_Menu *m, E_Menu_Item *mi EINA_UNUSED) { E_Client *ec; ec = e_object_data_get(E_OBJECT(m)); if (ec) e_client_pinned_set(ec, 0); } static void _e_client_menu_cb_stacking_pre(void *data, E_Menu *m EINA_UNUSED, E_Menu_Item *mi) { E_Menu *subm; E_Menu_Item *submi; E_Client *ec; if (!(ec = data)) return; subm = e_menu_new(); e_object_data_set(E_OBJECT(subm), ec); e_menu_item_submenu_set(mi, subm); e_object_unref(E_OBJECT(subm)); /* Only allow to change layer for windows in "normal" layers */ e_menu_category_set(subm, "border/stacking"); e_menu_category_data_set("border/stacking", ec); submi = e_menu_item_new(subm); e_menu_item_label_set(submi, _("Always on Top")); e_menu_item_radio_set(submi, 1); e_menu_item_radio_group_set(submi, 2); e_menu_item_toggle_set(submi, (ec->layer == E_LAYER_CLIENT_ABOVE ? 1 : 0)); e_menu_item_callback_set(submi, _e_client_menu_cb_on_top, ec); e_menu_item_icon_edje_set(submi, e_theme_edje_file_get("base/theme/borders", "e/widgets/border/default/stack_on_top"), "e/widgets/border/default/stack_on_top"); submi = e_menu_item_new(subm); e_menu_item_label_set(submi, _("Normal")); e_menu_item_radio_set(submi, 1); e_menu_item_radio_group_set(submi, 2); e_menu_item_toggle_set(submi, (ec->layer == E_LAYER_CLIENT_NORMAL ? 1 : 0)); e_menu_item_callback_set(submi, _e_client_menu_cb_normal, ec); e_menu_item_icon_edje_set(submi, e_theme_edje_file_get("base/theme/borders", "e/widgets/border/default/stack_normal"), "e/widgets/border/default/stack_normal"); submi = e_menu_item_new(subm); e_menu_item_label_set(submi, _("Always Below")); e_menu_item_radio_set(submi, 1); e_menu_item_radio_group_set(submi, 2); e_menu_item_toggle_set(submi, (ec->layer == E_LAYER_CLIENT_BELOW ? 1 : 0)); e_menu_item_callback_set(submi, _e_client_menu_cb_below, ec); e_menu_item_icon_edje_set(submi, e_theme_edje_file_get("base/theme/borders", "e/widgets/border/default/stack_below"), "e/widgets/border/default/stack_below"); submi = e_menu_item_new(subm); e_menu_item_separator_set(submi, 1); // Only allow to change layer for windows in "normal" layers if ((!ec->lock_user_stacking) && ((ec->layer == 50) || (ec->layer == 100) || (ec->layer == 150))) { submi = e_menu_item_new(subm); e_menu_item_label_set(submi, _("Raise")); e_menu_item_callback_set(submi, _e_client_menu_cb_raise, ec); e_menu_item_icon_edje_set(submi, e_theme_edje_file_get("base/theme/borders", "e/widgets/border/default/stack_on_top"), "e/widgets/border/default/stack_on_top"); submi = e_menu_item_new(subm); e_menu_item_label_set(submi, _("Lower")); e_menu_item_callback_set(submi, _e_client_menu_cb_lower, ec); e_menu_item_icon_edje_set(submi, e_theme_edje_file_get("base/theme/borders", "e/widgets/border/default/stack_below"), "e/widgets/border/default/stack_below"); } submi = e_menu_item_new(subm); e_menu_item_separator_set(submi, 1); if ((ec->netwm.type == E_WINDOW_TYPE_NORMAL) || (ec->netwm.type == E_WINDOW_TYPE_UNKNOWN)) { if ((ec->netwm.state.stacking != E_STACKING_BELOW) || (!ec->user_skip_winlist) || (!ec->borderless)) { submi = e_menu_item_new(subm); e_menu_item_label_set(submi, _("Pin to Desktop")); e_menu_item_callback_set(submi, _e_client_menu_cb_pin, ec); e_menu_item_icon_edje_set(submi, e_theme_edje_file_get("base/theme/borders", "e/widgets/border/default/stick"), "e/widgets/border/default/stick"); } if ((ec->netwm.state.stacking == E_STACKING_BELOW) && (ec->user_skip_winlist) && (ec->borderless)) { submi = e_menu_item_new(subm); e_menu_item_label_set(submi, _("Unpin from Desktop")); e_menu_item_callback_set(submi, _e_client_menu_cb_unpin, ec); e_menu_item_icon_edje_set(submi, e_theme_edje_file_get("base/theme/borders", "e/widgets/border/default/stick"), "e/widgets/border/default/stick"); } } } static void _e_client_menu_cb_raise(void *data, E_Menu *m EINA_UNUSED, E_Menu_Item *mi EINA_UNUSED) { E_Client *ec = data; if ((!ec->lock_user_stacking) && (!ec->internal) && ((ec->layer >= E_LAYER_CLIENT_DESKTOP) && (ec->layer <= E_LAYER_CLIENT_NORMAL))) { evas_object_raise(ec->frame); } } static void _e_client_menu_cb_lower(void *data, E_Menu *m EINA_UNUSED, E_Menu_Item *mi EINA_UNUSED) { E_Client *ec = data; if ((!ec->lock_user_stacking) && (!ec->internal) && ((ec->layer >= E_LAYER_CLIENT_DESKTOP) && (ec->layer <= E_LAYER_CLIENT_NORMAL))) { evas_object_lower(ec->frame); } } static void _e_client_menu_cb_default_icon(void *data, E_Menu *m, E_Menu_Item *mi) { E_Client *ec; Evas_Object *o; unsigned char prev_icon_pref; ec = data; E_OBJECT_CHECK(ec); prev_icon_pref = ec->icon_preference; ec->icon_preference = E_ICON_PREF_E_DEFAULT; o = e_client_icon_add(ec, m->evas); ec->icon_preference = prev_icon_pref; mi->icon_object = o; } static void _e_client_menu_cb_netwm_icon(void *data, E_Menu *m, E_Menu_Item *mi) { E_Client *ec; Evas_Object *o; ec = data; E_OBJECT_CHECK(ec); if (ec->netwm.icons) { o = e_icon_add(m->evas); e_icon_data_set(o, ec->netwm.icons[0].data, ec->netwm.icons[0].width, ec->netwm.icons[0].height); e_icon_alpha_set(o, 1); mi->icon_object = o; } } static void _e_client_menu_cb_border_pre(void *data, E_Menu *m EINA_UNUSED, E_Menu_Item *mi) { E_Menu *subm; E_Menu_Item *submi; E_Client *ec; if (!(ec = data)) return; subm = e_menu_new(); e_object_data_set(E_OBJECT(subm), ec); e_menu_item_submenu_set(mi, subm); e_object_unref(E_OBJECT(subm)); if (e_configure_registry_exists("internal/borders_border")) { submi = e_menu_item_new(subm); e_menu_item_label_set(submi, _("Select Border Style")); e_menu_item_callback_set(submi, _e_client_menu_cb_border, ec); e_menu_item_icon_edje_set(submi, e_theme_edje_file_get("base/theme/borders", "e/widgets/border/default/borderless"), "e/widgets/border/default/borderless"); submi = e_menu_item_new(subm); e_menu_item_separator_set(submi, 1); } submi = e_menu_item_new(subm); e_menu_item_label_set(submi, _("Use Enlightenment Default Icon Preference")); e_menu_item_radio_set(submi, 1); e_menu_item_radio_group_set(submi, 2); e_menu_item_toggle_set(submi, (ec->icon_preference == E_ICON_PREF_E_DEFAULT ? 1 : 0)); e_menu_item_realize_callback_set(submi, _e_client_menu_cb_default_icon, ec); e_menu_item_callback_set(submi, _e_client_menu_cb_iconpref_e, ec); submi = e_menu_item_new(subm); e_menu_item_label_set(submi, _("Use Application Provided Icon")); e_menu_item_radio_set(submi, 1); e_menu_item_radio_group_set(submi, 2); e_menu_item_toggle_set(submi, (ec->icon_preference == E_ICON_PREF_NETWM ? 1 : 0)); e_menu_item_realize_callback_set(submi, _e_client_menu_cb_netwm_icon, ec); e_menu_item_callback_set(submi, _e_client_menu_cb_iconpref_netwm, ec); submi = e_menu_item_new(subm); e_menu_item_label_set(submi, _("Use User Defined Icon")); e_menu_item_radio_set(submi, 1); e_menu_item_radio_group_set(submi, 2); e_menu_item_toggle_set(submi, (ec->icon_preference == E_ICON_PREF_USER ? 1 : 0)); e_util_desktop_menu_item_icon_add(ec->desktop, 16, submi); e_menu_item_callback_set(submi, _e_client_menu_cb_iconpref_user, ec); e_menu_item_separator_set(submi, 1); submi = e_menu_item_new(subm); e_menu_item_label_set(submi, _("Offer Resistance")); e_menu_item_check_set(submi, 1); e_menu_item_toggle_set(submi, (ec->offer_resistance ? 1 : 0)); e_menu_item_callback_set(submi, _e_client_menu_cb_resistance, ec); e_menu_item_icon_edje_set(submi, e_theme_edje_file_get("base/theme/borders", "e/widgets/border/default/borderless"), "e/widgets/border/default/borderless"); } static void _e_client_menu_cb_iconpref_e(void *data, E_Menu *m EINA_UNUSED, E_Menu_Item *mi EINA_UNUSED) { E_Client *ec; if (!(ec = data)) return; ec->icon_preference = E_ICON_PREF_E_DEFAULT; ec->changes.icon = 1; ec->changed = 1; } static void _e_client_menu_cb_iconpref_user(void *data, E_Menu *m EINA_UNUSED, E_Menu_Item *mi EINA_UNUSED) { E_Client *ec; if (!(ec = data)) return; ec->icon_preference = E_ICON_PREF_USER; ec->changes.icon = 1; ec->changed = 1; } static void _e_client_menu_cb_iconpref_netwm(void *data, E_Menu *m EINA_UNUSED, E_Menu_Item *mi EINA_UNUSED) { E_Client *ec; if (!(ec = data)) return; ec->icon_preference = E_ICON_PREF_NETWM; ec->changes.icon = 1; ec->changed = 1; } static void _e_client_menu_cb_skip_pre(void *data, E_Menu *m EINA_UNUSED, E_Menu_Item *mi) { E_Client *ec; E_Menu *subm; E_Menu_Item *submi; if (!(ec = data)) return; subm = e_menu_new(); e_object_data_set(E_OBJECT(subm), ec); e_menu_item_submenu_set(mi, subm); e_object_unref(E_OBJECT(subm)); submi = e_menu_item_new(subm); e_menu_item_label_set(submi, _("Window List")); e_menu_item_check_set(submi, 1); e_menu_item_toggle_set(submi, ec->user_skip_winlist); e_menu_item_callback_set(submi, _e_client_menu_cb_skip_winlist, ec); e_menu_item_icon_edje_set(submi, e_theme_edje_file_get("base/theme/borders", "e/widgets/border/default/skip_winlist"), "e/widgets/border/default/skip_winlist"); submi = e_menu_item_new(subm); e_menu_item_label_set(submi, _("Pager")); e_menu_item_check_set(submi, 1); e_menu_item_toggle_set(submi, ec->netwm.state.skip_pager); e_menu_item_callback_set(submi, _e_client_menu_cb_skip_pager, ec); e_menu_item_icon_edje_set(submi, e_theme_edje_file_get("base/theme/borders", "e/widgets/border/default/skip_pager"), "e/widgets/border/default/skip_pager"); submi = e_menu_item_new(subm); e_menu_item_label_set(submi, _("Taskbar")); e_menu_item_check_set(submi, 1); e_menu_item_toggle_set(submi, ec->netwm.state.skip_taskbar); e_menu_item_callback_set(submi, _e_client_menu_cb_skip_taskbar, ec); e_menu_item_icon_edje_set(submi, e_theme_edje_file_get("base/theme/borders", "e/widgets/border/default/skip_taskbar"), "e/widgets/border/default/skip_taskbar"); } static void _e_client_menu_cb_fav_add(void *data, E_Menu *m EINA_UNUSED, E_Menu_Item *mi EINA_UNUSED) { E_Client *ec; Efreet_Menu *menu; char buf[PATH_MAX]; if (!(ec = data)) return; e_user_dir_concat_static(buf, "applications/menu/favorite.menu"); menu = efreet_menu_parse(buf); if (!menu) menu = efreet_menu_new("Favorites"); if (!menu) return; efreet_menu_desktop_insert(menu, ec->desktop, -1); efreet_menu_save(menu, buf); efreet_menu_free(menu); } static void _e_client_menu_cb_kbdshrtct_add(void *data, E_Menu *m EINA_UNUSED, E_Menu_Item *mi EINA_UNUSED) { E_Client *ec; E_Zone *zone; if (!(ec = data)) return; zone = e_zone_current_get(); if (!zone) return; e_configure_registry_call("keyboard_and_mouse/key_bindings", NULL, ec->desktop->exec); } static void _e_client_menu_cb_ibar_add_pre(void *data, E_Menu *m EINA_UNUSED, E_Menu_Item *mi) { E_Menu *sm; E_Client *ec; Eina_List *dirs; Eina_List *l; char buf[PATH_MAX], *file; size_t len; if (!(ec = data)) return; len = e_user_dir_concat_static(buf, "applications/bar"); if (len + 1 >= sizeof(buf)) return; dirs = ecore_file_ls(buf); if (!dirs) return; buf[len] = '/'; len++; sm = e_menu_new(); EINA_LIST_FOREACH(dirs, l, file) { E_Menu_Item *smi; if (file[0] == '.') continue; eina_strlcpy(buf + len, file, sizeof(buf) - len); if (ecore_file_is_dir(buf)) { smi = e_menu_item_new(sm); e_menu_item_label_set(smi, file); e_menu_item_callback_set(smi, _e_client_menu_cb_ibar_add, file); } } e_object_data_set(E_OBJECT(sm), ec); e_menu_item_submenu_set(mi, sm); e_object_unref(E_OBJECT(sm)); } static void _e_client_menu_cb_ibar_add(void *data, E_Menu *m, E_Menu_Item *mi EINA_UNUSED) { E_Order *od; E_Client *ec; char buf[PATH_MAX]; ec = e_object_data_get(E_OBJECT(m)); if ((!ec) || (!ec->desktop)) return; e_user_dir_snprintf(buf, sizeof(buf), "applications/bar/%s/.order", (const char *)data); od = e_order_new(buf); if (!od) return; e_order_append(od, ec->desktop); e_object_del(E_OBJECT(od)); } /*vim:ts=8 sw=3 sts=3 expandtab cino=>5n-3f0^-2{2(0W1st0*/
34.768074
140
0.649799
[ "object" ]
00b0eb0e31684c06176f7d3a631b2eef1fbe5fad
1,478
h
C
frs/include/huaweicloud/frs/v2/model/ActionsList.h
huaweicloud/huaweicloud-sdk-cpp-v3
d3b5e07b0ee8367d1c7f6dad17be0212166d959c
[ "Apache-2.0" ]
5
2021-03-03T08:23:43.000Z
2022-02-16T02:16:39.000Z
frs/include/huaweicloud/frs/v2/model/ActionsList.h
ChenwxJay/huaweicloud-sdk-cpp-v3
f821ec6d269b50203e0c1638571ee1349c503c41
[ "Apache-2.0" ]
null
null
null
frs/include/huaweicloud/frs/v2/model/ActionsList.h
ChenwxJay/huaweicloud-sdk-cpp-v3
f821ec6d269b50203e0c1638571ee1349c503c41
[ "Apache-2.0" ]
7
2021-02-26T13:53:35.000Z
2022-03-18T02:36:43.000Z
#ifndef HUAWEICLOUD_SDK_FRS_V2_MODEL_ActionsList_H_ #define HUAWEICLOUD_SDK_FRS_V2_MODEL_ActionsList_H_ #include <huaweicloud/frs/v2/FrsExport.h> #include <huaweicloud/core/utils/ModelBase.h> #include <huaweicloud/core/http/HttpResponse.h> namespace HuaweiCloud { namespace Sdk { namespace Frs { namespace V2 { namespace Model { using namespace HuaweiCloud::Sdk::Core::Utils; using namespace HuaweiCloud::Sdk::Core::Http; /// <summary> /// /// </summary> class HUAWEICLOUD_FRS_V2_EXPORT ActionsList : public ModelBase { public: ActionsList(); virtual ~ActionsList(); ///////////////////////////////////////////// /// ModelBase overrides void validate() override; web::json::value toJson() const override; bool fromJson(const web::json::value& json) override; ///////////////////////////////////////////// /// ActionsList members /// <summary> /// 置信度,取值范围0~1。 /// </summary> double getConfidence() const; bool confidenceIsSet() const; void unsetconfidence(); void setConfidence(double value); /// <summary> /// 动作编号,取值范围:[1,2,3,4],其中: • 1:左摇头 • 2:右摇头 • 3:点头 • 4:嘴部动作 /// </summary> int32_t getAction() const; bool actionIsSet() const; void unsetaction(); void setAction(int32_t value); protected: double confidence_; bool confidenceIsSet_; int32_t action_; bool actionIsSet_; }; } } } } } #endif // HUAWEICLOUD_SDK_FRS_V2_MODEL_ActionsList_H_
19.447368
63
0.642084
[ "model" ]
00b67019d81e86cb4f1647c8bbdbe81d3919d641
27,409
c
C
src/attic/schema_keyval.c
nklabs/libnklabs
51641ae5249b1274a895328b1d4e676a9613e04d
[ "MIT" ]
5
2021-12-10T17:29:38.000Z
2022-03-04T18:49:08.000Z
src/attic/schema_keyval.c
nklabs/libnklabs
51641ae5249b1274a895328b1d4e676a9613e04d
[ "MIT" ]
null
null
null
src/attic/schema_keyval.c
nklabs/libnklabs
51641ae5249b1274a895328b1d4e676a9613e04d
[ "MIT" ]
null
null
null
// Copyright 2020 NK Labs, LLC // 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 "lib.h" // Schema checked serializer / deserializer // Standard primitive types const struct type tyINT = { .what = tINT, .size = sizeof(int), .members = NULL, .subtype = NULL }; const struct type tyBOOL = { .what = tBOOL, .size = sizeof(int), .members = NULL, .subtype = NULL }; const struct type tyDOUBLE = { .what = tDOUBLE, .size = sizeof(double), .members = NULL, .subtype = NULL }; const struct type tyFLOAT = { .what = tFLOAT, .size = sizeof(float), .members = NULL, .subtype = NULL }; void indent(int x) { while (x--) printf(" "); } void print_val(const struct type *type, void *location, int ind, char *ed) { char sbuf[32]; switch (type->what) { case tSTRUCT: { const struct member *m; const char *o_name = 0; const struct type *o_type = 0; ptrdiff_t o_offset = 0; printf("{\n"); for (m = type->members; m->name; ++m) { if (o_name) { if (o_type->what == tTABLE) { indent(ind + 2); printf("%s:\n", o_name); indent(ind + 4); print_val(o_type, (char *)location + o_offset, ind + 4, ",\n"); } else { indent(ind + 2); printf("%s: ", o_name); print_val(o_type, (char *)location + o_offset, ind + 2, ",\n"); } } o_name = m->name; o_type = m->type; o_offset = m->offset; } if (o_name) { if (o_type->what == tTABLE) { indent(ind + 2); printf("%s:\n", o_name); indent(ind + 4); print_val(o_type, (char *)location + o_offset, ind + 4, "\n"); } else { indent(ind + 2); printf("%s: ", o_name); print_val(o_type, (char *)location + o_offset, ind + 2, "\n"); } } indent(ind); printf("}%s", ed); break; } case tTABLE: { int y; const struct type *subtype = type->subtype; const struct member *m; int nrows = ((union len *)location)->len; location = (char *)location + sizeof(union len); printf("("); for (m = subtype->members; m->name; ++m) { printf("\t%s", m->name); } printf("\n"); for (y = 0; y != nrows; ++y) { indent(ind); printf(":"); for (m = subtype->members; m->name; ++m) { printf("\t"); print_val(m->type, (char *)location + m->offset, 0, ""); } printf("\n"); location = (char *)location + subtype->size; } indent(ind); printf(")%s", ed); break; } case tARRAY: { int x; int len = ((union len *)location)->len; location = (char *)location + sizeof(union len); printf("[\n"); for (x = 0; x != len; ++x) { indent(ind + 2); if (x + 1 == len) print_val(type->subtype, location, ind + 2, "\n"); else print_val(type->subtype, location, ind + 2, ",\n"); location = (char *)location + type->subtype->size; } indent(ind); printf("]%s", ed); break; /* } case tVOID: { printf("null%s", ed); break; */ } case tDOUBLE: { int x; // Print double as decimal with enough precision to // recover the original double on read in. // (should be %.17g, but uses too much space) sprintf(sbuf, "%g", *(double *)location); // %g will omit the decimal point if it can. But we // always want it.. so add it back. // FIXME: handle nan and inf for (x = 0; sbuf[x]; ++x) if (sbuf[x] == '.' || sbuf[x] == 'e') break; if (!sbuf[x]) { sbuf[x++] = '.'; sbuf[x++] = '0'; sbuf[x] = 0; } printf("%s%s", sbuf, ed); break; } case tFLOAT: { int x; // Print double as decimal with enough precision to // recover the original double on read in. // (should be %.17g, but uses too much space) sprintf(sbuf, "%g", *(float *)location); // %g will omit the decimal point if it can. But we // always want it.. so add it back. // FIXME: handle nan and inf for (x = 0; sbuf[x]; ++x) if (sbuf[x] == '.' || sbuf[x] == 'e') break; if (!sbuf[x]) { sbuf[x++] = '.'; sbuf[x++] = '0'; sbuf[x] = 0; } printf("%s%s", sbuf, ed); break; } case tINT: { printf("%d%s", *(int *)location, ed); break; } case tBOOL: { if (*(int *)location) printf("true%s", ed); else printf("false%s", ed); break; } case tSTRING: { char *s = (char *)location; int x; printf("\""); for (x = 0; s[x]; ++x) { if (s[x] == '\"') printf("\\\""); else if (s[x] == '\\') printf("\\\\"); else if (s[x] == '\n') printf("\\n"); else if (s[x] == '\r') printf("\\r"); else if (s[x] < 32 || s[x] > 126) printf("\\x%2.2x", (0xFF & s[x])); else printf("%c", s[x]); } printf("\"%s", ed); break; } default: { printf("unknown%s", ed); break; } } } // Serialize a database with a given schema int serialize_val(char *org, const struct type *type, void *location) { char *buf = org; switch (type->what) { case tSTRUCT: { const struct member *m; *buf++ = '{'; m = type->members; while (m->name) { sprintf(buf, "%s:", m->name); buf += strlen(buf); buf += serialize_val(buf, m->type, (char *)location + m->offset); ++m; if (m->name) { sprintf(buf, ", "); buf += strlen(buf); } } *buf++ = '}'; break; } case tARRAY: { *buf++ = '['; int count = ((union len *)location)->len; location = (char *)location + sizeof(union len); while (count--) { buf += serialize_val(buf, type->subtype, location); location = (char *)location + type->subtype->size; if (count) { sprintf(buf, ", "); buf += strlen(buf); } } *buf++ = ']'; break; } case tTABLE: { const struct member *m; *buf++ = '('; int count = ((union len *)location)->len; location = (char *)location + sizeof(union len); m = type->subtype->members; while (m->name) { sprintf(buf, "%s", m->name); buf += strlen(buf); ++m; *buf++ = ' '; } while (count--) { *buf++ = ':'; m = type->subtype->members; while (m->name) { buf += serialize_val(buf, m->type, (char *)location + m->offset); ++m; if (m->name) *buf++ = ' '; } location = (char *)location + type->subtype->size; } *buf++ = ')'; break; } case tBOOL: { if (*(int *)location) sprintf(buf, "true"); else sprintf(buf, "false"); buf += strlen(buf); break; } case tINT: { sprintf(buf, "%d", *(int *)location); buf += strlen(buf); break; } case tDOUBLE: { sprintf(buf, "%g", *(double *)location); buf += strlen(buf); break; } case tFLOAT: { sprintf(buf, "%g", *(float *)location); buf += strlen(buf); break; } case tSTRING: { char *s = (char *)location; *buf++ = '"'; while (*s) { if (*s == '"') { *buf++ = '\\'; *buf++ = '"'; } else if (*s == '\\') { *buf++ = '\\'; *buf++ = '\\'; } else if (*s == '\n') { *buf++ = '\\'; *buf++ = 'n'; } else if (*s == '\r') { *buf++ = '\\'; *buf++ = 'r'; } else if (*s < 32 || *s > 126) { *buf++ = '\\'; *buf++ = 'x'; sprintf(buf, "%2.2x", *(unsigned char *)s); buf += strlen(buf); } else { *buf++ = *s; } ++s; } *buf++ = '"'; } } return buf - org; } // Xpath traversal // It would be nice if this worked for tables... const struct type *xpath(char *key, const struct type *type, void **location_loc) { char buf[80]; char *p = key; void *location = *location_loc; int idx; while (*p) { if (nk_scan(&p, "[ %d ]", &idx)) { int count; if (type->what == tARRAY || type->what == tTABLE) { count = ((union len *)location)->len; location = (char *)location + sizeof(union len); if (idx >= count || idx < 0) { printf("Array index out of bounds in key %s\n", key); return 0; } location = (char *)location + idx * type->subtype->size; type = type->subtype; } else { printf("Attempt to index a non-array in key %s\n", key); return 0; } if (*p == '.') ++p; else if (*p == '[') ; else break; } else if (nk_scan(&p, "%i", buf, sizeof(buf))) { const struct member *m; if (type->what != tSTRUCT) { printf("Attempt to index a non-struct in key %s\n", key); return 0; } for (m = type->members; m->name; ++m) if (!strcmp(m->name, buf)) break; if (!m->name) { printf("Item does not exist %s\n", buf); return 0; } type = m->type; location = (char *)location + m->offset; if (*p == '.') ++p; else if (*p == '[') ; else break; } else { printf("Syntax error in key %s\n", key); return 0; } } if (*p) { printf("Syntax error in key %s\n", key); return 0; } *location_loc = location; return type; } // Database management char keyval_cal_rev; char keyval_config_rev; char keyval_model_rev; char bigbuf[65536]; void keyval_cal_clear() { cal = cal_defaults; } void keyval_config_clear() { config = config_defaults; } void keyval_model_clear() { model = model_defaults; } int keyval_cal_flush() { int size = serialize_val(bigbuf, &tyCAL, &cal); unsigned int cr; bigbuf[size++] = 0; bigbuf[size++] = ++keyval_cal_rev; printf("saving: %s\n", bigbuf); printf("size = %d\n", size); printf("rev = %d\n", keyval_cal_rev); cr = crc_check((unsigned char *)bigbuf, size); bigbuf[size++] = (cr >> 24); bigbuf[size++] = (cr >> 16); bigbuf[size++] = (cr >> 8); bigbuf[size++] = (cr); if (keyval_cal_rev & 1) { // It goes in bank 2 printf("Erasing...\n"); flash_erase(FLASH_CAL_KEYVAL_ADDR_2); printf("Writing...\n"); flash_write(FLASH_CAL_KEYVAL_ADDR_2, (unsigned char *)bigbuf, size); printf("done.\n"); } else { // It goes in bank 1 printf("Erasing...\n"); flash_erase(FLASH_CAL_KEYVAL_ADDR_1); printf("Writing...\n"); flash_write(FLASH_CAL_KEYVAL_ADDR_1, (unsigned char *)bigbuf, size); printf("done.\n"); } return 0; } int keyval_config_flush() { int size = serialize_val(bigbuf, &tyCONFIG, &config); unsigned int cr; bigbuf[size++] = 0; bigbuf[size++] = ++keyval_config_rev; printf("saving: %s\n", bigbuf); printf("size = %d\n", size); printf("rev = %d\n", keyval_config_rev); cr = crc_check((unsigned char *)bigbuf, size); bigbuf[size++] = (cr >> 24); bigbuf[size++] = (cr >> 16); bigbuf[size++] = (cr >> 8); bigbuf[size++] = (cr); if (keyval_config_rev & 1) { // It goes in bank 2 printf("Erasing...\n"); flash_erase(FLASH_CONFIG_KEYVAL_ADDR_2); printf("Writing...\n"); flash_write(FLASH_CONFIG_KEYVAL_ADDR_2, (unsigned char *)bigbuf, size); printf("done.\n"); } else { // It goes in bank 1 printf("Erasing...\n"); flash_erase(FLASH_CONFIG_KEYVAL_ADDR_1); printf("Writing...\n"); flash_write(FLASH_CONFIG_KEYVAL_ADDR_1, (unsigned char *)bigbuf, size); printf("done.\n"); } return 0; } int keyval_model_flush() { int size = serialize_val(bigbuf, &tyMODEL, &model); unsigned int cr; bigbuf[size++] = 0; bigbuf[size++] = ++keyval_model_rev; printf("saving: %s\n", bigbuf); printf("size = %d\n", size); printf("rev = %d\n", keyval_model_rev); cr = crc_check((unsigned char *)bigbuf, size); bigbuf[size++] = (cr >> 24); bigbuf[size++] = (cr >> 16); bigbuf[size++] = (cr >> 8); bigbuf[size++] = (cr); if (keyval_config_rev & 1) { // It goes in bank 2 printf("Erasing...\n"); flash_erase(FLASH_MODEL_KEYVAL_ADDR_2); printf("Writing...\n"); flash_write(FLASH_MODEL_KEYVAL_ADDR_2, (unsigned char *)bigbuf, size); printf("done.\n"); } else { // It goes in bank 1 printf("Erasing...\n"); flash_erase(FLASH_MODEL_KEYVAL_ADDR_1); printf("Writing...\n"); flash_write(FLASH_MODEL_KEYVAL_ADDR_1, (unsigned char *)bigbuf, size); printf("done.\n"); } return 0; } int keyval_cal_get(int n) { int x; if (n) flash_read(FLASH_CAL_KEYVAL_ADDR_2, (unsigned char *)bigbuf, sizeof(bigbuf)); else flash_read(FLASH_CAL_KEYVAL_ADDR_1, (unsigned char *)bigbuf, sizeof(bigbuf)); for (x = 0; x != sizeof(bigbuf) && bigbuf[x]; ++x); if (x == sizeof(bigbuf)) { printf("size is bad\n"); return -1; } ++x; keyval_cal_rev = bigbuf[x++]; printf("size = %d\n", x); printf("rev = %d\n", keyval_cal_rev); x += 4; if (crc_check((unsigned char *)bigbuf, x)) { printf("crc is bad\n"); return -1; } // printf("data = %s\n", bigbuf); return 0; } int keyval_config_get(int n) { int x; if (n) flash_read(FLASH_CONFIG_KEYVAL_ADDR_2, (unsigned char *)bigbuf, sizeof(bigbuf)); else flash_read(FLASH_CONFIG_KEYVAL_ADDR_1, (unsigned char *)bigbuf, sizeof(bigbuf)); for (x = 0; x != sizeof(bigbuf) && bigbuf[x]; ++x); if (x == sizeof(bigbuf)) { printf("size is bad\n"); return -1; } ++x; keyval_config_rev = bigbuf[x++]; printf("size = %d\n", x); printf("rev = %d\n", keyval_config_rev); x += 4; if (crc_check((unsigned char *)bigbuf, x)) { printf("crc is bad\n"); return -1; } // printf("data = %s\n", bigbuf); return 0; } int keyval_model_get(int n) { int x; if (n) flash_read(FLASH_MODEL_KEYVAL_ADDR_2, (unsigned char *)bigbuf, sizeof(bigbuf)); else flash_read(FLASH_MODEL_KEYVAL_ADDR_1, (unsigned char *)bigbuf, sizeof(bigbuf)); for (x = 0; x != sizeof(bigbuf) && bigbuf[x]; ++x); if (x == sizeof(bigbuf)) { printf("size is bad\n"); return -1; } ++x; keyval_model_rev = bigbuf[x++]; printf("size = %d\n", x); printf("rev = %d\n", keyval_model_rev); x += 4; if (crc_check((unsigned char *)bigbuf, x)) { printf("crc is bad\n"); return -1; } // printf("data = %s\n", bigbuf); return 0; } int keyval_cal_load() { int first_good = !keyval_cal_get(0); int first_rev = keyval_cal_rev; int second_good = !keyval_cal_get(1); int second_rev = keyval_cal_rev; cal = cal_defaults; if (second_good && first_good) { if (first_rev - second_rev >= 0) goto get_first; else goto do_parse; } else if (second_good) { goto do_parse; } else if (first_good) { char *p; get_first: keyval_cal_get(0); do_parse: p = bigbuf; if (nk_scan(&p, " %v", &tyCAL, &cal)) { printf("Calibration store loaded OK\n"); return 0; } else { printf("CRC good, but calibration store failed to parse on load?\n"); cal = cal_defaults; return -1; } } else { printf("No good CRCs\n"); return -1; } } int keyval_config_load() { int first_good = !keyval_config_get(0); int first_rev = keyval_config_rev; int second_good = !keyval_config_get(1); int second_rev = keyval_config_rev; config = config_defaults; if (second_good && first_good) { if (first_rev - second_rev >= 0) goto get_first; else goto do_parse; } else if (second_good) { goto do_parse; } else if (first_good) { char *p; get_first: keyval_config_get(0); do_parse: p = bigbuf; if (nk_scan(&p, " %v", &tyCONFIG, &config)) { printf("Configuration store loaded OK\n"); return 0; } else { config = config_defaults; printf("CRC good, but configuration store failed to parse on load?\n"); return -1; } } else { printf("No good CRCs\n"); return -1; } } int keyval_model_load() { int first_good = !keyval_model_get(0); int first_rev = keyval_model_rev; int second_good = !keyval_model_get(1); int second_rev = keyval_model_rev; model = model_defaults; if (second_good && first_good) { if (first_rev - second_rev >= 0) goto get_first; else goto do_parse; } else if (second_good) { goto do_parse; } else if (first_good) { char *p; get_first: keyval_model_get(0); do_parse: p = bigbuf; if (nk_scan(&p, " %v", &tyMODEL, &model)) { printf("Model store loaded OK\n"); return 0; } else { model = model_defaults; printf("CRC good, but model store failed to parse on load?\n"); return -1; } } else { printf("No good CRCs\n"); return -1; } } void keyval_init() { startup("Key/Value store"); show_heap(); if (keyval_cal_load()) { printf("Creating empty calibration store\n"); } show_heap(); if (keyval_config_load()) { printf("Creating empty configuration store\n"); } show_heap(); if (keyval_model_load()) { printf("Creating empty model store\n"); } show_heap(); } // Read in a long string char *multi_gets() { bigbuf[0] = 0; int idx = 0; int state = 0; printf("Type BEGIN to start the input\n"); for (;;) { char *s = prompt("-", 1); if (state == 1) { if (!stricmp(s, "END")) break; else { strcpy(bigbuf + idx, s); idx += strlen(s); bigbuf[idx++] = ' '; bigbuf[idx] = 0; } } else { if (!stricmp(s, "BEGIN")) { printf("Input started. Type END to end the input\n"); state = 1; } else if (!stricmp(s, "END")) break; } } return bigbuf; } int cmd_cal(char *args) { char key[80]; if (facmode && nk_scan(&args, "clear %e")) { printf("Clearing calibration store\n"); keyval_cal_clear(); keyval_cal_flush(); keyval_cal_flush(); printf("done.\n"); cmd_reboot(""); } else if (facmode && nk_scan(&args, "flush %e")) { keyval_cal_flush(); } else if (facmode && nk_scan(&args, "load %e")) { keyval_cal_load(); } else if (facmode && nk_scan(&args, "show %e")) { printf("BEGIN\n"); print_val(&tyCAL, &cal, 0, "\n"); printf("END\n"); } else if (facmode && nk_scan(&args, "replace %e")) { char *l = multi_gets(); cal = cal_defaults; if (nk_scan(&l, " %v %e", &tyCAL, &cal)) { printf("Replacing keyval store with "); print_val(&tyCAL, &cal, 0, "\n"); } else { cal = cal_defaults; printf("Syntax error\n"); } } else if (facmode && nk_scan(&args, "get %w %e", key, sizeof(key))) { void *loc = &cal; const struct type *t = xpath(key, &tyCAL, &loc); if (!t) { printf("Not found.\n"); } else { printf("BEGIN\n"); print_val(t, loc, 0, "\n"); printf("END\n"); } } else if (facmode && nk_scan(&args, "set %w ", key, sizeof(key))) { void *loc = &cal; const struct type *t = xpath(key, &tyCAL, &loc); if (!t) { printf("Not found.\n"); } else { if (nk_scan(&args, "%v %e", t, (void *)loc)) { printf("Setting %s to ", key); print_val(t, loc, 0, "\n"); } else if (nk_scan(&args, " %e")) { char *l = multi_gets(); if (nk_scan(&l, " %v %e", t, (void *)loc)) { printf("Setting %s to ", key); print_val(t, loc, 0, "\n"); } else { printf("Syntax error\n"); } } else { printf("Syntax error\n"); } } } else { printf("Syntax error\n"); } return 0; } int cmd_model(char *args) { char key[80]; if (facmode && nk_scan(&args, "clear %e")) { printf("Clearing model store\n"); keyval_model_clear(); keyval_model_flush(); keyval_model_flush(); printf("done.\n"); cmd_reboot(""); } else if (facmode && nk_scan(&args, "flush %e")) { keyval_model_flush(); } else if (facmode && nk_scan(&args, "load %e")) { keyval_model_load(); } else if (facmode && nk_scan(&args, "show %e")) { printf("BEGIN\n"); print_val(&tyMODEL, &model, 0, "\n"); printf("END\n"); } else if (facmode && nk_scan(&args, "replace %e")) { char *l = multi_gets(); model = model_defaults; if (nk_scan(&l, " %v %e", &tyMODEL, &model)) { printf("Replacing model store with "); print_val(&tyMODEL, &model, 0, "\n"); } else { model = model_defaults; printf("Syntax error\n"); } } else if (facmode && nk_scan(&args, "get %w %e", key, sizeof(key))) { void *loc = &model; const struct type *t = xpath(key, &tyMODEL, &loc); if (!t) { printf("Not found.\n"); } else { printf("BEGIN\n"); print_val(t, loc, 0, "\n"); printf("END\n"); } } else if (facmode && nk_scan(&args, "set %w ", key, sizeof(key))) { void *loc = &model; const struct type *t = xpath(key, &tyMODEL, &loc); if (!t) { printf("Not found.\n"); } else { if (nk_scan(&args, "%v %e", t, (void *)loc)) { printf("Setting %s to ", key); print_val(t, loc, 0, "\n"); } else if (nk_scan(&args, " %e")) { char *l = multi_gets(); if (nk_scan(&l, " %v %e", t, (void *)loc)) { printf("Setting %s to ", key); print_val(t, loc, 0, "\n"); } else { printf("Syntax error\n"); } } else { printf("Syntax error\n"); } } } else { printf("Syntax error\n"); } return 0; } int cmd_config(char *args) { char key[80]; if (nk_scan(&args, "clear %e")) { printf("Clearing configuration store\n"); keyval_config_clear(); keyval_config_flush(); keyval_config_flush(); printf("done.\n"); cmd_reboot(""); } else if (nk_scan(&args, "flush %e")) { keyval_config_flush(); } else if (nk_scan(&args, "load %e")) { keyval_config_load(); } else if (nk_scan(&args, "show %e")) { printf("BEGIN\n"); print_val(&tyCONFIG, &config, 0, "\n"); printf("END\n"); } else if (nk_scan(&args, "replace %e")) { char *l = multi_gets(); config = config_defaults; if (nk_scan(&l, " %v %e", &tyCONFIG, &config)) { printf("Replacing keyval store with "); print_val(&tyCONFIG, &config, 0, "\n"); } else { config = config_defaults; printf("Syntax error\n"); } } else if (facmode && nk_scan(&args, "get %w %e", key, sizeof(key))) { void *loc = &config; const struct type *t = xpath(key, &tyCONFIG, &loc); if (!t) { printf("Not found.\n"); } else { printf("BEGIN\n"); print_val(t, loc, 0, "\n"); printf("END\n"); } } else if (facmode && nk_scan(&args, "set %w ", key, sizeof(key))) { void *loc = &config; const struct type *t = xpath(key, &tyCONFIG, &loc); if (!t) { printf("Not found.\n"); } else { if (nk_scan(&args, "%v %e", t, (void *)loc)) { printf("Setting %s to ", key); print_val(t, loc, 0, "\n"); } else if (nk_scan(&args, " %e")) { char *l = multi_gets(); if (nk_scan(&l, " %v %e", t, (void *)loc)) { printf("Setting %s to ", key); print_val(t, loc, 0, "\n"); } else { printf("Syntax error\n"); } } else { printf("Syntax error\n"); } } } else { printf("Syntax error\n"); } return 0; }
29.567422
104
0.478894
[ "model" ]
00bf966d7d0f2b1c5e6b894e7e686062df5f13df
2,742
h
C
include/ft/trader/gateway.h
liutongwei/ft
c75c1ea6b4e53128248113f9810b997d2f7ff236
[ "MIT" ]
null
null
null
include/ft/trader/gateway.h
liutongwei/ft
c75c1ea6b4e53128248113f9810b997d2f7ff236
[ "MIT" ]
null
null
null
include/ft/trader/gateway.h
liutongwei/ft
c75c1ea6b4e53128248113f9810b997d2f7ff236
[ "MIT" ]
null
null
null
// Copyright [2020] <Copyright Kevin, kevin.lau.gd@gmail.com> #ifndef FT_INCLUDE_FT_TRADER_GATEWAY_H_ #define FT_INCLUDE_FT_TRADER_GATEWAY_H_ #include <string> #include <vector> #include "ft/base/config.h" #include "ft/base/market_data.h" #include "ft/base/trade_msg.h" #include "ft/trader/base_oms.h" namespace ft { /* * Gateway是所有交易网关的基类,目前行情、查询、交易类的接口都 * 集成在了Gateway中,后续会把行情及交易无关的查询剥离到其他接 * 口中。Gateway会被OMS创建并使用,OMS会在登录、登出、查询时保 * 证Gateway线程安全,对于这几个函数,Gateway无需另外实现一套线 * 程安全的机制,而对于发单及撤单函数,OMS并没有保证线程安全,同 * 一时刻可能存在着多个调用,所以Gateway实现时要注意发单及撤单 * 函数的线程安全性 * * Gateway应该实现成一个简单的订单路由类,任务是把订单转发到相应 * 的broker或交易所,并把订单回报以相应的规则传回给OMS,内部应该 * 尽可能地做到无锁实现。 * * 接口说明 * 1. 查询接口都应该实现成同步的接口 * 2. 交易及行情都应该实现成异步的接口 * 3. 收到回报时应该回调相应的OMS函数,以告知OMS * * 在gateway.cpp中注册你的Gateway */ class Gateway { public: virtual ~Gateway() {} /* * 登录函数。在登录函数中,gateway应当保存oms指针,以供后续回调 * 使用。同时,login函数成功执行后,gateway即进入到了可交易的状 * 态(如果配置了交易服务器的话),或是进入到了可订阅行情数据的 * 状态(如果配置了行情服务器的话) * * login最好实现成可被多次调用,即和logout配合使用,可反复地主动 * 登录登出 */ virtual bool Login(BaseOrderManagementSystem* oms, const Config& config) { return false; } /* * 登出函数。从服务器登出,以达到禁止交易或中断行情的目的。外部 * 可通过logout来暂停交易。 */ virtual void Logout() {} /* * 发送订单,privdata_ptr是外部传入的指针,gateway可以把该订单 * 相关的私有数据,交由外部保存,撤单时外部会将privdata传回给 * gateway */ virtual bool SendOrder(const OrderRequest& order, uint64_t* privdata_ptr) { return false; } virtual bool CancelOrder(uint64_t order_id, uint64_t privdata) { return false; } virtual bool Subscribe(const std::vector<std::string>& sub_list) { return true; } virtual bool QueryContract(const std::string& ticker, const std::string& exchange, Contract* result) { return true; } virtual bool QueryContractList(std::vector<Contract>* result) { return true; } virtual bool QueryPosition(const std::string& ticker, Position* result) { return true; } virtual bool QueryPositionList(std::vector<Position>* result) { return true; } virtual bool QueryAccount(Account* result) { return true; } virtual bool QueryTradeList(std::vector<Trade>* result) { return true; } virtual bool QueryMarginRate(const std::string& ticker) { return true; } virtual bool QueryCommisionRate(const std::string& ticker) { return true; } // 扩展接口,用于向Gateway发送自定义消息 virtual void OnNotify(uint64_t signal) {} }; using GatewayCreateFunc = Gateway* (*)(); using GatewayDestroyFunc = void (*)(Gateway*); #define REGISTER_GATEWAY(type) \ extern "C" ::ft::Gateway* CreateGateway() { return new type(); } \ extern "C" void DestroyGateway(::ft::Gateway* p) { delete p; } } // namespace ft #endif // FT_INCLUDE_FT_TRADER_GATEWAY_H_
27.148515
93
0.713348
[ "vector" ]
00c9cd31a017e7520b6181d54b9ba72529674853
9,588
c
C
pow_accel_soc/software/u-boot-socfpga/fs/ubifs/sb.c
ajblane/iota_fpga
2ec78e89bf263a84905aba92437da5ec091ab621
[ "MIT" ]
13
2018-05-24T07:02:26.000Z
2021-04-13T12:48:24.000Z
uboot/u-boot-2011.12/fs/ubifs/sb.c
spartan263/vizio_oss
74270002d874391148119b48882db6816e7deedc
[ "Linux-OpenIB" ]
1
2021-02-24T05:16:58.000Z
2021-02-24T05:16:58.000Z
uboot/u-boot-2011.12/fs/ubifs/sb.c
spartan263/vizio_oss
74270002d874391148119b48882db6816e7deedc
[ "Linux-OpenIB" ]
14
2018-05-08T23:40:47.000Z
2022-02-12T00:12:06.000Z
/* * This file is part of UBIFS. * * Copyright (C) 2006-2008 Nokia Corporation. * * This program is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 as published by * the Free Software Foundation. * * This program is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for * more details. * * You should have received a copy of the GNU General Public License along with * this program; if not, write to the Free Software Foundation, Inc., 51 * Franklin St, Fifth Floor, Boston, MA 02110-1301 USA * * Authors: Artem Bityutskiy (Битюцкий Артём) * Adrian Hunter */ /* * This file implements UBIFS superblock. The superblock is stored at the first * LEB of the volume and is never changed by UBIFS. Only user-space tools may * change it. The superblock node mostly contains geometry information. */ #include "ubifs.h" /* * Default journal size in logical eraseblocks as a percent of total * flash size. */ #define DEFAULT_JNL_PERCENT 5 /* Default maximum journal size in bytes */ #define DEFAULT_MAX_JNL (32*1024*1024) /* Default indexing tree fanout */ #define DEFAULT_FANOUT 8 /* Default number of data journal heads */ #define DEFAULT_JHEADS_CNT 1 /* Default positions of different LEBs in the main area */ #define DEFAULT_IDX_LEB 0 #define DEFAULT_DATA_LEB 1 #define DEFAULT_GC_LEB 2 /* Default number of LEB numbers in LPT's save table */ #define DEFAULT_LSAVE_CNT 256 /* Default reserved pool size as a percent of maximum free space */ #define DEFAULT_RP_PERCENT 5 /* The default maximum size of reserved pool in bytes */ #define DEFAULT_MAX_RP_SIZE (5*1024*1024) /* Default time granularity in nanoseconds */ #define DEFAULT_TIME_GRAN 1000000000 /** * validate_sb - validate superblock node. * @c: UBIFS file-system description object * @sup: superblock node * * This function validates superblock node @sup. Since most of data was read * from the superblock and stored in @c, the function validates fields in @c * instead. Returns zero in case of success and %-EINVAL in case of validation * failure. */ static int validate_sb(struct ubifs_info *c, struct ubifs_sb_node *sup) { long long max_bytes; int err = 1, min_leb_cnt; if (!c->key_hash) { err = 2; goto failed; } if (sup->key_fmt != UBIFS_SIMPLE_KEY_FMT) { err = 3; goto failed; } if (le32_to_cpu(sup->min_io_size) != c->min_io_size) { ubifs_err("min. I/O unit mismatch: %d in superblock, %d real", le32_to_cpu(sup->min_io_size), c->min_io_size); goto failed; } if (le32_to_cpu(sup->leb_size) != c->leb_size) { ubifs_err("LEB size mismatch: %d in superblock, %d real", le32_to_cpu(sup->leb_size), c->leb_size); goto failed; } if (c->log_lebs < UBIFS_MIN_LOG_LEBS || c->lpt_lebs < UBIFS_MIN_LPT_LEBS || c->orph_lebs < UBIFS_MIN_ORPH_LEBS || c->main_lebs < UBIFS_MIN_MAIN_LEBS) { err = 4; goto failed; } /* * Calculate minimum allowed amount of main area LEBs. This is very * similar to %UBIFS_MIN_LEB_CNT, but we take into account real what we * have just read from the superblock. */ min_leb_cnt = UBIFS_SB_LEBS + UBIFS_MST_LEBS + c->log_lebs; min_leb_cnt += c->lpt_lebs + c->orph_lebs + c->jhead_cnt + 6; if (c->leb_cnt < min_leb_cnt || c->leb_cnt > c->vi.size) { ubifs_err("bad LEB count: %d in superblock, %d on UBI volume, " "%d minimum required", c->leb_cnt, c->vi.size, min_leb_cnt); goto failed; } if (c->max_leb_cnt < c->leb_cnt) { ubifs_err("max. LEB count %d less than LEB count %d", c->max_leb_cnt, c->leb_cnt); goto failed; } if (c->main_lebs < UBIFS_MIN_MAIN_LEBS) { err = 7; goto failed; } if (c->max_bud_bytes < (long long)c->leb_size * UBIFS_MIN_BUD_LEBS || c->max_bud_bytes > (long long)c->leb_size * c->main_lebs) { err = 8; goto failed; } if (c->jhead_cnt < NONDATA_JHEADS_CNT + 1 || c->jhead_cnt > NONDATA_JHEADS_CNT + UBIFS_MAX_JHEADS) { err = 9; goto failed; } if (c->fanout < UBIFS_MIN_FANOUT || ubifs_idx_node_sz(c, c->fanout) > c->leb_size) { err = 10; goto failed; } if (c->lsave_cnt < 0 || (c->lsave_cnt > DEFAULT_LSAVE_CNT && c->lsave_cnt > c->max_leb_cnt - UBIFS_SB_LEBS - UBIFS_MST_LEBS - c->log_lebs - c->lpt_lebs - c->orph_lebs)) { err = 11; goto failed; } if (UBIFS_SB_LEBS + UBIFS_MST_LEBS + c->log_lebs + c->lpt_lebs + c->orph_lebs + c->main_lebs != c->leb_cnt) { err = 12; goto failed; } if (c->default_compr < 0 || c->default_compr >= UBIFS_COMPR_TYPES_CNT) { err = 13; goto failed; } max_bytes = c->main_lebs * (long long)c->leb_size; if (c->rp_size < 0 || max_bytes < c->rp_size) { err = 14; goto failed; } if (le32_to_cpu(sup->time_gran) > 1000000000 || le32_to_cpu(sup->time_gran) < 1) { err = 15; goto failed; } return 0; failed: ubifs_err("bad superblock, error %d", err); dbg_dump_node(c, sup); return -EINVAL; } /** * ubifs_read_sb_node - read superblock node. * @c: UBIFS file-system description object * * This function returns a pointer to the superblock node or a negative error * code. */ struct ubifs_sb_node *ubifs_read_sb_node(struct ubifs_info *c) { struct ubifs_sb_node *sup; int err; sup = kmalloc(ALIGN(UBIFS_SB_NODE_SZ, c->min_io_size), GFP_NOFS); if (!sup) return ERR_PTR(-ENOMEM); err = ubifs_read_node(c, sup, UBIFS_SB_NODE, UBIFS_SB_NODE_SZ, UBIFS_SB_LNUM, 0); if (err) { kfree(sup); return ERR_PTR(err); } return sup; } /** * ubifs_read_superblock - read superblock. * @c: UBIFS file-system description object * * This function finds, reads and checks the superblock. If an empty UBI volume * is being mounted, this function creates default superblock. Returns zero in * case of success, and a negative error code in case of failure. */ int ubifs_read_superblock(struct ubifs_info *c) { int err, sup_flags; struct ubifs_sb_node *sup; if (c->empty) { printf("No UBIFS filesystem found!\n"); return -1; } sup = ubifs_read_sb_node(c); if (IS_ERR(sup)) return PTR_ERR(sup); c->fmt_version = le32_to_cpu(sup->fmt_version); c->ro_compat_version = le32_to_cpu(sup->ro_compat_version); /* * The software supports all previous versions but not future versions, * due to the unavailability of time-travelling equipment. */ if (c->fmt_version > UBIFS_FORMAT_VERSION) { struct super_block *sb = c->vfs_sb; int mounting_ro = sb->s_flags & MS_RDONLY; ubifs_assert(!c->ro_media || mounting_ro); if (!mounting_ro || c->ro_compat_version > UBIFS_RO_COMPAT_VERSION) { ubifs_err("on-flash format version is w%d/r%d, but " "software only supports up to version " "w%d/r%d", c->fmt_version, c->ro_compat_version, UBIFS_FORMAT_VERSION, UBIFS_RO_COMPAT_VERSION); if (c->ro_compat_version <= UBIFS_RO_COMPAT_VERSION) { ubifs_msg("only R/O mounting is possible"); err = -EROFS; } else err = -EINVAL; goto out; } /* * The FS is mounted R/O, and the media format is * R/O-compatible with the UBIFS implementation, so we can * mount. */ c->rw_incompat = 1; } if (c->fmt_version < 3) { ubifs_err("on-flash format version %d is not supported", c->fmt_version); err = -EINVAL; goto out; } switch (sup->key_hash) { case UBIFS_KEY_HASH_R5: c->key_hash = key_r5_hash; c->key_hash_type = UBIFS_KEY_HASH_R5; break; case UBIFS_KEY_HASH_TEST: c->key_hash = key_test_hash; c->key_hash_type = UBIFS_KEY_HASH_TEST; break; }; c->key_fmt = sup->key_fmt; switch (c->key_fmt) { case UBIFS_SIMPLE_KEY_FMT: c->key_len = UBIFS_SK_LEN; break; default: ubifs_err("unsupported key format"); err = -EINVAL; goto out; } c->leb_cnt = le32_to_cpu(sup->leb_cnt); c->max_leb_cnt = le32_to_cpu(sup->max_leb_cnt); c->max_bud_bytes = le64_to_cpu(sup->max_bud_bytes); c->log_lebs = le32_to_cpu(sup->log_lebs); c->lpt_lebs = le32_to_cpu(sup->lpt_lebs); c->orph_lebs = le32_to_cpu(sup->orph_lebs); c->jhead_cnt = le32_to_cpu(sup->jhead_cnt) + NONDATA_JHEADS_CNT; c->fanout = le32_to_cpu(sup->fanout); c->lsave_cnt = le32_to_cpu(sup->lsave_cnt); c->default_compr = le16_to_cpu(sup->default_compr); c->rp_size = le64_to_cpu(sup->rp_size); c->rp_uid = le32_to_cpu(sup->rp_uid); c->rp_gid = le32_to_cpu(sup->rp_gid); sup_flags = le32_to_cpu(sup->flags); c->vfs_sb->s_time_gran = le32_to_cpu(sup->time_gran); memcpy(&c->uuid, &sup->uuid, 16); c->big_lpt = !!(sup_flags & UBIFS_FLG_BIGLPT); /* Automatically increase file system size to the maximum size */ c->old_leb_cnt = c->leb_cnt; if (c->leb_cnt < c->vi.size && c->leb_cnt < c->max_leb_cnt) { c->leb_cnt = min_t(int, c->max_leb_cnt, c->vi.size); dbg_mnt("Auto resizing (ro) from %d LEBs to %d LEBs", c->old_leb_cnt, c->leb_cnt); } c->log_bytes = (long long)c->log_lebs * c->leb_size; c->log_last = UBIFS_LOG_LNUM + c->log_lebs - 1; c->lpt_first = UBIFS_LOG_LNUM + c->log_lebs; c->lpt_last = c->lpt_first + c->lpt_lebs - 1; c->orph_first = c->lpt_last + 1; c->orph_last = c->orph_first + c->orph_lebs - 1; c->main_lebs = c->leb_cnt - UBIFS_SB_LEBS - UBIFS_MST_LEBS; c->main_lebs -= c->log_lebs + c->lpt_lebs + c->orph_lebs; c->main_first = c->leb_cnt - c->main_lebs; c->report_rp_size = ubifs_reported_space(c, c->rp_size); err = validate_sb(c, sup); out: kfree(sup); return err; }
27.631124
79
0.686587
[ "geometry", "object" ]
00cbe20fd4f77e9dfad5108a923059b9da928050
3,523
h
C
cruby-ext/xni.h
headius/xni
b12e53623fc662256116fa10e6e8b059a33a143b
[ "Apache-2.0" ]
2
2019-09-24T13:09:33.000Z
2021-03-30T04:39:13.000Z
cruby-ext/xni.h
headius/xni
b12e53623fc662256116fa10e6e8b059a33a143b
[ "Apache-2.0" ]
null
null
null
cruby-ext/xni.h
headius/xni
b12e53623fc662256116fa10e6e8b059a33a143b
[ "Apache-2.0" ]
null
null
null
/* * Copyright (C) 2013 Wayne Meissner * * This file is part of the XNI project. * * 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. */ #ifndef CRUBY_XNI_H #define CRUBY_XNI_H #include <ruby.h> #include <tr1/memory> #include <stdexcept> #ifdef __GNUC__ # pragma GCC visibility push(hidden) #endif extern VALUE xni_cType; namespace xni { using std::tr1::shared_ptr; void data_object_init(VALUE xniModule); void dynamic_library_init(VALUE xniModule); void extension_init(VALUE xniModule); void extension_data_init(VALUE xniModule); void function_init(VALUE xniModule); void pointer_init(VALUE xniModule); void type_init(VALUE xniModule); void method_stub_init(VALUE module); void closure_pool_init(VALUE module); void auto_release_pool_init(VALUE module); void platform_init(VALUE module); class Object { private: int refcnt; public: Object(): refcnt(1) { } virtual ~Object() {} virtual void mark() {}; inline int decref() { return --refcnt; } struct Deleter { void operator()(Object* obj) { if (obj->decref() == 0) delete obj; } }; template <class T> struct Mark { void operator()(shared_ptr<T>& obj) { obj->mark(); } }; template <class T> static shared_ptr<T> lock(T *obj) { obj->refcnt++; return shared_ptr<T>(obj, Deleter()); } }; class RaiseException : public std::exception { protected: VALUE m_exc; RaiseException() {} public: ~RaiseException() throw() {} inline VALUE exc() { return m_exc; } const char* what() throw(); }; class RubyException : public RaiseException { public: RubyException(VALUE etype, const char* fmt, ...); ~RubyException() throw() {} }; void check_type(VALUE obj, VALUE t); void check_typeddata(VALUE obj, const rb_data_type_t* data_type); template <class T> T* object_from_value(VALUE obj, const rb_data_type_t* data_type) { check_typeddata(obj, data_type); return reinterpret_cast<T *>(DATA_PTR(obj)); } void object_mark(void *); void object_free(void *); extern const rb_data_type_t object_data_type; } #define TRY(block) do { \ VALUE rbexc__ = Qnil; \ try { \ do { block; } while(0); \ } catch (RaiseException& ex) { \ rbexc__ = ex.exc(); \ } catch (std::exception& ex) { \ rbexc__ = rb_exc_new2(rb_eRuntimeError, ex.what()); \ } \ if (unlikely(rbexc__ != Qnil)) { rb_exc_raise(rbexc__); }\ } while (0); #ifdef __GNUC__ # define likely(x) __builtin_expect((x), 1) # define unlikely(x) __builtin_expect((x), 0) #else # define likely(x) (x) # define unlikely(x) (x) #endif #ifdef __GNUC__ # pragma GCC visibility pop #endif #endif /* CRUBY_XNI_H */
26.096296
80
0.618507
[ "object" ]
00e4c81b38f5a212cb0c8f88558704291c405a9e
904
h
C
GUI/header/factory_addedit_view.h
M9k/Progetto-P2
bd92bf278939ea59f8d41d8e9fd69f4172b3b6ac
[ "BSD-3-Clause" ]
1
2021-12-02T10:56:00.000Z
2021-12-02T10:56:00.000Z
GUI/header/factory_addedit_view.h
M9k/Progetto-P2
bd92bf278939ea59f8d41d8e9fd69f4172b3b6ac
[ "BSD-3-Clause" ]
null
null
null
GUI/header/factory_addedit_view.h
M9k/Progetto-P2
bd92bf278939ea59f8d41d8e9fd69f4172b3b6ac
[ "BSD-3-Clause" ]
null
null
null
#ifndef FACTORY_ADDEDIT_VIEW_H #define FACTORY_ADDEDIT_VIEW_H #include <string> #include <QString> #include "../../MODEL/header/file_base.h" #include "../../MODEL/header/file_raw.h" #include "../../MODEL/header/file_video.h" #include "../../MODEL/header/file_audio.h" #include "../../MODEL/header/file_audiovideo.h" #include "../../MODEL/header/file_text.h" #include "../../MODEL/header/file_plain_text.h" #include "../../MODEL/header/file_epub.h" #include "view_file_base.h" #include "view_file_raw.h" #include "view_file_text.h" #include "view_file_plain_text.h" #include "view_file_epub.h" #include "view_file_audio.h" #include "view_file_video.h" #include "view_file_audiovideo.h" class FactoryAddEdit_View { public: static view_file_base* build(file_base*); virtual ~FactoryAddEdit_View() = 0; //per forzare l'astrazione }; #endif // FACTORY_ADDEDIT_VIEW_H
29.16129
67
0.716814
[ "model" ]
00e9195a990788edca967f0cdbc6e8e721d0919d
20,371
c
C
extern/gtk/gtk/gtkcolorswatch.c
PableteProgramming/download
013e35bb5c085e5dfdb57a3a0a39cdf2fd3064b8
[ "MIT" ]
null
null
null
extern/gtk/gtk/gtkcolorswatch.c
PableteProgramming/download
013e35bb5c085e5dfdb57a3a0a39cdf2fd3064b8
[ "MIT" ]
null
null
null
extern/gtk/gtk/gtkcolorswatch.c
PableteProgramming/download
013e35bb5c085e5dfdb57a3a0a39cdf2fd3064b8
[ "MIT" ]
null
null
null
/* GTK - The GIMP Toolkit * Copyright (C) 2012 Red Hat, Inc. * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library. If not, see <http://www.gnu.org/licenses/>. */ #include "config.h" #include "gtkcolorswatchprivate.h" #include "gtkbox.h" #include "gtkcolorchooserprivate.h" #include "gtkdragsource.h" #include "gtkdroptarget.h" #include "gtkgesturelongpress.h" #include "gtkgestureclick.h" #include "gtkgesturesingle.h" #include "gtkicontheme.h" #include "gtkimage.h" #include "gtkintl.h" #include "gtkmain.h" #include "gtkmodelbuttonprivate.h" #include "gtkpopovermenu.h" #include "gtkprivate.h" #include "gtksnapshot.h" #include "gtkwidgetprivate.h" #include "gtkeventcontrollerkey.h" #include "gtknative.h" /* * GtkColorSwatch has two CSS nodes, the main one named colorswatch * and a subnode named overlay. The main node gets the .light or .dark * style classes added depending on the brightness of the color that * the swatch is showing. * * The color swatch has the .activatable style class by default. It can * be removed for non-activatable swatches. */ typedef struct _GtkColorSwatchClass GtkColorSwatchClass; struct _GtkColorSwatch { GtkWidget parent_instance; GdkRGBA color; char *icon; guint has_color : 1; guint use_alpha : 1; guint selectable : 1; guint has_menu : 1; GtkWidget *overlay_widget; GtkWidget *popover; GtkDropTarget *dest; }; struct _GtkColorSwatchClass { GtkWidgetClass parent_class; void ( * activate) (GtkColorSwatch *swatch); void ( * customize) (GtkColorSwatch *swatch); }; enum { PROP_ZERO, PROP_RGBA, PROP_SELECTABLE, PROP_HAS_MENU, PROP_CAN_DROP }; G_DEFINE_TYPE (GtkColorSwatch, gtk_color_swatch, GTK_TYPE_WIDGET) #define INTENSITY(r, g, b) ((r) * 0.30 + (g) * 0.59 + (b) * 0.11) static void swatch_snapshot (GtkWidget *widget, GtkSnapshot *snapshot) { GtkColorSwatch *swatch = GTK_COLOR_SWATCH (widget); const int width = gtk_widget_get_width (widget); const int height = gtk_widget_get_height (widget); const GdkRGBA *color; color = &swatch->color; if (swatch->dest) { const GValue *value = gtk_drop_target_get_value (swatch->dest); if (value) color = g_value_get_boxed (value); } if (swatch->has_color) { if (swatch->use_alpha && !gdk_rgba_is_opaque (color)) { _gtk_color_chooser_snapshot_checkered_pattern (snapshot, width, height); gtk_snapshot_append_color (snapshot, color, &GRAPHENE_RECT_INIT (0, 0, width, height)); } else { GdkRGBA opaque = *color; opaque.alpha = 1.0; gtk_snapshot_append_color (snapshot, &opaque, &GRAPHENE_RECT_INIT (0, 0, width, height)); } } gtk_widget_snapshot_child (widget, swatch->overlay_widget, snapshot); } static gboolean swatch_drag_drop (GtkDropTarget *dest, const GValue *value, double x, double y, GtkColorSwatch *swatch) { gtk_color_swatch_set_rgba (swatch, g_value_get_boxed (value)); return TRUE; } void gtk_color_swatch_activate (GtkColorSwatch *swatch) { double red, green, blue, alpha; red = swatch->color.red; green = swatch->color.green; blue = swatch->color.blue; alpha = swatch->color.alpha; gtk_widget_activate_action (GTK_WIDGET (swatch), "color.select", "(dddd)", red, green, blue, alpha); } void gtk_color_swatch_customize (GtkColorSwatch *swatch) { double red, green, blue, alpha; red = swatch->color.red; green = swatch->color.green; blue = swatch->color.blue; alpha = swatch->color.alpha; gtk_widget_activate_action (GTK_WIDGET (swatch), "color.customize", "(dddd)", red, green, blue, alpha); } void gtk_color_swatch_select (GtkColorSwatch *swatch) { gtk_widget_set_state_flags (GTK_WIDGET (swatch), GTK_STATE_FLAG_SELECTED, FALSE); } static gboolean gtk_color_swatch_is_selected (GtkColorSwatch *swatch) { return (gtk_widget_get_state_flags (GTK_WIDGET (swatch)) & GTK_STATE_FLAG_SELECTED) != 0; } static gboolean key_controller_key_pressed (GtkEventControllerKey *controller, guint keyval, guint keycode, GdkModifierType state, GtkWidget *widget) { GtkColorSwatch *swatch = GTK_COLOR_SWATCH (widget); if (keyval == GDK_KEY_space || keyval == GDK_KEY_Return || keyval == GDK_KEY_ISO_Enter|| keyval == GDK_KEY_KP_Enter || keyval == GDK_KEY_KP_Space) { if (swatch->has_color && swatch->selectable && !gtk_color_swatch_is_selected (swatch)) gtk_color_swatch_select (swatch); else gtk_color_swatch_customize (swatch); return TRUE; } return FALSE; } static GMenuModel * gtk_color_swatch_get_menu_model (GtkColorSwatch *swatch) { GMenu *menu, *section; GMenuItem *item; double red, green, blue, alpha; menu = g_menu_new (); red = swatch->color.red; green = swatch->color.green; blue = swatch->color.blue; alpha = swatch->color.alpha; section = g_menu_new (); item = g_menu_item_new (_("Customize"), NULL); g_menu_item_set_action_and_target_value (item, "color.customize", g_variant_new ("(dddd)", red, green, blue, alpha)); g_menu_append_item (section, item); g_menu_append_section (menu, NULL, G_MENU_MODEL (section)); g_object_unref (item); g_object_unref (section); return G_MENU_MODEL (menu); } static void do_popup (GtkColorSwatch *swatch) { GMenuModel *model; g_clear_pointer (&swatch->popover, gtk_widget_unparent); model = gtk_color_swatch_get_menu_model (swatch); swatch->popover = gtk_popover_menu_new_from_model (model); gtk_widget_set_parent (swatch->popover, GTK_WIDGET (swatch)); g_object_unref (model); gtk_popover_popup (GTK_POPOVER (swatch->popover)); } static gboolean swatch_primary_action (GtkColorSwatch *swatch) { if (!swatch->has_color) { gtk_color_swatch_customize (swatch); return TRUE; } else if (swatch->selectable && !gtk_color_swatch_is_selected (swatch)) { gtk_color_swatch_select (swatch); return TRUE; } return FALSE; } static void hold_action (GtkGestureLongPress *gesture, double x, double y, GtkColorSwatch *swatch) { do_popup (swatch); gtk_gesture_set_state (GTK_GESTURE (gesture), GTK_EVENT_SEQUENCE_CLAIMED); } static void tap_action (GtkGestureClick *gesture, int n_press, double x, double y, GtkColorSwatch *swatch) { guint button; button = gtk_gesture_single_get_current_button (GTK_GESTURE_SINGLE (gesture)); if (button == GDK_BUTTON_PRIMARY) { if (n_press == 1) swatch_primary_action (swatch); else if (n_press > 1) gtk_color_swatch_activate (swatch); } else if (button == GDK_BUTTON_SECONDARY) { if (swatch->has_color && swatch->has_menu) do_popup (swatch); } } static void swatch_size_allocate (GtkWidget *widget, int width, int height, int baseline) { GtkColorSwatch *swatch = GTK_COLOR_SWATCH (widget); gtk_widget_size_allocate (swatch->overlay_widget, &(GtkAllocation) { 0, 0, width, height }, -1); if (swatch->popover) gtk_popover_present (GTK_POPOVER (swatch->popover)); } static void gtk_color_swatch_measure (GtkWidget *widget, GtkOrientation orientation, int for_size, int *minimum, int *natural, int *minimum_baseline, int *natural_baseline) { GtkColorSwatch *swatch = GTK_COLOR_SWATCH (widget); int w, h, min; gtk_widget_measure (swatch->overlay_widget, orientation, -1, minimum, natural, NULL, NULL); gtk_widget_get_size_request (widget, &w, &h); if (orientation == GTK_ORIENTATION_HORIZONTAL) min = w < 0 ? 48 : w; else min = h < 0 ? 32 : h; *minimum = MAX (*minimum, min); *natural = MAX (*natural, min); } static void swatch_popup_menu (GtkWidget *widget, const char *action_name, GVariant *parameters) { do_popup (GTK_COLOR_SWATCH (widget)); } static void update_icon (GtkColorSwatch *swatch) { GtkImage *image = GTK_IMAGE (swatch->overlay_widget); if (swatch->icon) gtk_image_set_from_icon_name (image, swatch->icon); else if (gtk_color_swatch_is_selected (swatch)) gtk_image_set_from_icon_name (image, "object-select-symbolic"); else gtk_image_clear (image); } static void update_accessible_properties (GtkColorSwatch *swatch) { if (swatch->selectable) { gboolean selected = gtk_color_swatch_is_selected (swatch); gtk_accessible_update_state (GTK_ACCESSIBLE (swatch), GTK_ACCESSIBLE_STATE_CHECKED, selected, -1); } else { gtk_accessible_reset_state (GTK_ACCESSIBLE (swatch), GTK_ACCESSIBLE_STATE_CHECKED); } } static void swatch_state_flags_changed (GtkWidget *widget, GtkStateFlags previous_state) { GtkColorSwatch *swatch = GTK_COLOR_SWATCH (widget); update_icon (swatch); update_accessible_properties (swatch); GTK_WIDGET_CLASS (gtk_color_swatch_parent_class)->state_flags_changed (widget, previous_state); } /* GObject implementation {{{1 */ static void swatch_get_property (GObject *object, guint prop_id, GValue *value, GParamSpec *pspec) { GtkColorSwatch *swatch = GTK_COLOR_SWATCH (object); GdkRGBA color; switch (prop_id) { case PROP_RGBA: gtk_color_swatch_get_rgba (swatch, &color); g_value_set_boxed (value, &color); break; case PROP_SELECTABLE: g_value_set_boolean (value, gtk_color_swatch_get_selectable (swatch)); break; case PROP_HAS_MENU: g_value_set_boolean (value, swatch->has_menu); break; case PROP_CAN_DROP: g_value_set_boolean (value, swatch->dest != NULL); break; default: G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec); break; } } static void swatch_set_property (GObject *object, guint prop_id, const GValue *value, GParamSpec *pspec) { GtkColorSwatch *swatch = GTK_COLOR_SWATCH (object); switch (prop_id) { case PROP_RGBA: gtk_color_swatch_set_rgba (swatch, g_value_get_boxed (value)); break; case PROP_SELECTABLE: gtk_color_swatch_set_selectable (swatch, g_value_get_boolean (value)); break; case PROP_HAS_MENU: swatch->has_menu = g_value_get_boolean (value); break; case PROP_CAN_DROP: gtk_color_swatch_set_can_drop (swatch, g_value_get_boolean (value)); break; default: G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec); break; } } static void swatch_finalize (GObject *object) { GtkColorSwatch *swatch = GTK_COLOR_SWATCH (object); g_free (swatch->icon); gtk_widget_unparent (swatch->overlay_widget); G_OBJECT_CLASS (gtk_color_swatch_parent_class)->finalize (object); } static void swatch_dispose (GObject *object) { GtkColorSwatch *swatch = GTK_COLOR_SWATCH (object); g_clear_pointer (&swatch->popover, gtk_widget_unparent); G_OBJECT_CLASS (gtk_color_swatch_parent_class)->dispose (object); } static void gtk_color_swatch_class_init (GtkColorSwatchClass *class) { GtkWidgetClass *widget_class = (GtkWidgetClass *)class; GObjectClass *object_class = (GObjectClass *)class; object_class->get_property = swatch_get_property; object_class->set_property = swatch_set_property; object_class->finalize = swatch_finalize; object_class->dispose = swatch_dispose; widget_class->measure = gtk_color_swatch_measure; widget_class->snapshot = swatch_snapshot; widget_class->size_allocate = swatch_size_allocate; widget_class->state_flags_changed = swatch_state_flags_changed; g_object_class_install_property (object_class, PROP_RGBA, g_param_spec_boxed ("rgba", P_("RGBA Color"), P_("Color as RGBA"), GDK_TYPE_RGBA, GTK_PARAM_READWRITE)); g_object_class_install_property (object_class, PROP_SELECTABLE, g_param_spec_boolean ("selectable", P_("Selectable"), P_("Whether the swatch is selectable"), TRUE, GTK_PARAM_READWRITE)); g_object_class_install_property (object_class, PROP_HAS_MENU, g_param_spec_boolean ("has-menu", P_("Has Menu"), P_("Whether the swatch should offer customization"), TRUE, GTK_PARAM_READWRITE)); g_object_class_install_property (object_class, PROP_CAN_DROP, g_param_spec_boolean ("can-drop", P_("Can Drop"), P_("Whether the swatch should accept drops"), FALSE, GTK_PARAM_READWRITE)); /** * GtkColorSwatch|menu.popup: * * Opens the context menu. */ gtk_widget_class_install_action (widget_class, "menu.popup", NULL, swatch_popup_menu); gtk_widget_class_add_binding_action (widget_class, GDK_KEY_F10, GDK_SHIFT_MASK, "menu.popup", NULL); gtk_widget_class_add_binding_action (widget_class, GDK_KEY_Menu, 0, "menu.popup", NULL); gtk_widget_class_set_css_name (widget_class, I_("colorswatch")); gtk_widget_class_set_accessible_role (widget_class, GTK_ACCESSIBLE_ROLE_RADIO); } static void gtk_color_swatch_init (GtkColorSwatch *swatch) { GtkEventController *controller; GtkGesture *gesture; swatch->use_alpha = TRUE; swatch->selectable = TRUE; swatch->has_menu = TRUE; swatch->color.red = 0.75; swatch->color.green = 0.25; swatch->color.blue = 0.25; swatch->color.alpha = 1.0; gtk_widget_set_focusable (GTK_WIDGET (swatch), TRUE); gtk_widget_set_overflow (GTK_WIDGET (swatch), GTK_OVERFLOW_HIDDEN); gesture = gtk_gesture_long_press_new (); gtk_gesture_single_set_touch_only (GTK_GESTURE_SINGLE (gesture), TRUE); g_signal_connect (gesture, "pressed", G_CALLBACK (hold_action), swatch); gtk_widget_add_controller (GTK_WIDGET (swatch), GTK_EVENT_CONTROLLER (gesture)); gesture = gtk_gesture_click_new (); gtk_gesture_single_set_button (GTK_GESTURE_SINGLE (gesture), 0); g_signal_connect (gesture, "pressed", G_CALLBACK (tap_action), swatch); gtk_widget_add_controller (GTK_WIDGET (swatch), GTK_EVENT_CONTROLLER (gesture)); controller = gtk_event_controller_key_new (); g_signal_connect (controller, "key-pressed", G_CALLBACK (key_controller_key_pressed), swatch); gtk_widget_add_controller (GTK_WIDGET (swatch), controller); gtk_widget_add_css_class (GTK_WIDGET (swatch), "activatable"); swatch->overlay_widget = g_object_new (GTK_TYPE_IMAGE, "accessible-role", GTK_ACCESSIBLE_ROLE_NONE, "css-name", "overlay", NULL); gtk_widget_set_parent (swatch->overlay_widget, GTK_WIDGET (swatch)); } /* Public API {{{1 */ GtkWidget * gtk_color_swatch_new (void) { return (GtkWidget *) g_object_new (GTK_TYPE_COLOR_SWATCH, NULL); } static GdkContentProvider * gtk_color_swatch_drag_prepare (GtkDragSource *source, double x, double y, GtkColorSwatch *swatch) { return gdk_content_provider_new_typed (GDK_TYPE_RGBA, &swatch->color); } void gtk_color_swatch_set_rgba (GtkColorSwatch *swatch, const GdkRGBA *color) { if (!swatch->has_color) { GtkDragSource *source; source = gtk_drag_source_new (); g_signal_connect (source, "prepare", G_CALLBACK (gtk_color_swatch_drag_prepare), swatch); gtk_widget_add_controller (GTK_WIDGET (swatch), GTK_EVENT_CONTROLLER (source)); } swatch->has_color = TRUE; swatch->color = *color; if (INTENSITY (swatch->color.red, swatch->color.green, swatch->color.blue) > 0.5) { gtk_widget_add_css_class (GTK_WIDGET (swatch), "light"); gtk_widget_remove_css_class (GTK_WIDGET (swatch), "dark"); } else { gtk_widget_add_css_class (GTK_WIDGET (swatch), "dark"); gtk_widget_remove_css_class (GTK_WIDGET (swatch), "light"); } gtk_widget_queue_draw (GTK_WIDGET (swatch)); g_object_notify (G_OBJECT (swatch), "rgba"); } gboolean gtk_color_swatch_get_rgba (GtkColorSwatch *swatch, GdkRGBA *color) { if (swatch->has_color) { color->red = swatch->color.red; color->green = swatch->color.green; color->blue = swatch->color.blue; color->alpha = swatch->color.alpha; return TRUE; } else { color->red = 1.0; color->green = 1.0; color->blue = 1.0; color->alpha = 1.0; return FALSE; } } void gtk_color_swatch_set_icon (GtkColorSwatch *swatch, const char *icon) { swatch->icon = g_strdup (icon); update_icon (swatch); gtk_widget_queue_draw (GTK_WIDGET (swatch)); } void gtk_color_swatch_set_can_drop (GtkColorSwatch *swatch, gboolean can_drop) { if (can_drop == (swatch->dest != NULL)) return; if (can_drop && !swatch->dest) { swatch->dest = gtk_drop_target_new (GDK_TYPE_RGBA, GDK_ACTION_COPY); gtk_drop_target_set_preload (swatch->dest, TRUE); g_signal_connect (swatch->dest, "drop", G_CALLBACK (swatch_drag_drop), swatch); g_signal_connect_swapped (swatch->dest, "notify::value", G_CALLBACK (gtk_widget_queue_draw), swatch); gtk_widget_add_controller (GTK_WIDGET (swatch), GTK_EVENT_CONTROLLER (swatch->dest)); } if (!can_drop && swatch->dest) { gtk_widget_remove_controller (GTK_WIDGET (swatch), GTK_EVENT_CONTROLLER (swatch->dest)); swatch->dest = NULL; } g_object_notify (G_OBJECT (swatch), "can-drop"); } void gtk_color_swatch_set_use_alpha (GtkColorSwatch *swatch, gboolean use_alpha) { swatch->use_alpha = use_alpha; gtk_widget_queue_draw (GTK_WIDGET (swatch)); } void gtk_color_swatch_set_selectable (GtkColorSwatch *swatch, gboolean selectable) { if (selectable == swatch->selectable) return; swatch->selectable = selectable; update_accessible_properties (swatch); g_object_notify (G_OBJECT (swatch), "selectable"); } gboolean gtk_color_swatch_get_selectable (GtkColorSwatch *swatch) { return swatch->selectable; } /* vim:set foldmethod=marker: */
28.610955
108
0.640715
[ "object", "model" ]
00f33d00704c20a6d1f8b0b14da40ddd07dba8cd
8,143
h
C
crypt/crypt.h
jonathanrlemos/ezbackup
3a9e0df91eaab7b9b7dec5a074985636b8830393
[ "Zlib", "bzip2-1.0.6", "MIT" ]
null
null
null
crypt/crypt.h
jonathanrlemos/ezbackup
3a9e0df91eaab7b9b7dec5a074985636b8830393
[ "Zlib", "bzip2-1.0.6", "MIT" ]
null
null
null
crypt/crypt.h
jonathanrlemos/ezbackup
3a9e0df91eaab7b9b7dec5a074985636b8830393
[ "Zlib", "bzip2-1.0.6", "MIT" ]
null
null
null
/** @file crypt/crypt.h * * Copyright (c) 2018 Jonathan Lemos * * This software may be modified and distributed under the terms * of the MIT license. See the LICENSE file for details. */ #ifndef __CRYPT_CRYPT_H #define __CRYPT_CRYPT_H #include <openssl/evp.h> #ifndef __GNUC__ #define __attribute__(x) #endif /** * @brief Holds encryption keys and data. */ struct crypt_keys; /** * @brief Generates a new crypt keys structure. * * @return A blank crypt keys structure, or NULL on failure.<br> * All values are set to 0 if it succeeds. */ struct crypt_keys* crypt_new(void) __attribute__((malloc)); /** * @brief Scrubs data with random values.<br> * This prevents fragments of sensitive information such as a password or a key being left in memory. * * @param data The data to scrub. * * @param len The length of the data to scrub. * * @return 0 if it succeeds, positive if low-grade random data was used, negative if it completely failed. */ int crypt_scrub(void* data, int len); /** * @brief Generates random data.<br> * This is identical to crypt_scrub(), as both functions simply fill data with random values. * @see crypt_scrub() * * @param data The data to fill. * * @param len The length of the data to fill. * * @return 0 if it succeeds, positive if low-grade random data was used, negative if it completely failed. */ #define gen_csrand(data, len) ((crypt_scrub(data, len))) /** * @brief Generates a random character. * * @return A random character. */ unsigned char crypt_randc(void); /** * @brief Turns an encryption name into its EVP_CIPHER* equivalent (e.g. "AES-256-CBC" -> EVP_aes_256_cbc()) * * @param encryption_name The name of the encryption algorithm to use. * * @return Its equivalent EVP_CIPHER*, or NULL if encryption_name is NULL/invalid. */ const EVP_CIPHER* crypt_get_cipher(const char* encryption_name); /** * @brief Sets the encryption type.<br> * This function must be called after crypt_new() * * @param encryption The encryption type to set. * @see crypt_get_cipher() * * @param fk A crypt keys structure returned by crypt_new(). * @see crypt_new() * * @return 0 on success, negative on failure. */ int crypt_set_encryption(const EVP_CIPHER* encryption, struct crypt_keys* fk); /** * @brief Generates a random salt. * * @param fk A crypt keys structure returned by crypt_new() * @see crypt_new() * * @return 0 on success, positive if low-grade random data was used, negative on failure. */ int crypt_gen_salt(struct crypt_keys* fk); /** * @brief Sets the salt to a user-specified value.<br> * Do not use with a hard-coded value unless its for testing purposes, as this defeats the purpose of a salt. * * @param salt The salt to set. * * @param fk A crypt keys structure returned by crypt_new() * @see crypt_new() * * @return 0 */ int crypt_set_salt(const unsigned char salt[8], struct crypt_keys* fk); /** * @brief Generates encryption keys based on a password.<br> * This function must be called after crypt_set_encryption().<br> * It is highly recommended that this function is called after crypt_gen_salt() or crypt_set_salt(), as this prevents rainbow table attacks against the encrypted file.<br> * Otherwise, the default salt value is all zeroes. * @see crypt_set_encryption() * @see crypt_gen_salt() * @see crypt_set_salt() * * @param data The data to be used as a password.<br> * This does not have to be a string; it can be any type of data of any length. * * @param data_len The length of the data to be used as the password. * * @param md The digest algorithm to be used during password generation.<br> * This parameter can be NULL, in which case SHA256 is used for compatibillity with the openssl command line utility. * * @param iterations The amount of iterations the password generation utility runs through.<br> * This must be 1 if compatibillity with the openssl command line utility is required. * * @param fk A crypt keys structure with its encryption set. * @see crypt_set_encryption() * * @return 0 on success, or negative on failure. */ int crypt_gen_keys(const void* data, int data_len, const EVP_MD* md, int iterations, struct crypt_keys* fk); /** * @brief Encrypts a file using a crypt keys structure.<br> * This function must be called after crypt_gen_keys().<br> * @see crypt_gen_keys() * * @param in Path to a file to be encrypted. * * @param fk The crypt keys structure to encrypt with. * * @param out Path to write the encrypted file to.<br> * If this file already exists, it will be overwritten.<br> * If this function fails, the output file is removed. * * @return 0 on success, or negative on failure. */ int crypt_encrypt(const char* in, struct crypt_keys* fk, const char* out); /** * @brief Encrypts a file using a crypt keys structure and an optional progress bar.<br> * This function must be called after crypt_gen_keys().<br> * @see crypt_gen_keys() * * @param in Path to a file to be encrypted. * * @param fk The crypt keys structure to encrypt with. * * @param out Path to write the encrypted file to.<br> * If this file already exists, it will be overwritten.<br> * If this function fails, the output file is removed. * * @param verbose 0 if a progress bar should not be displayed. Any other value if it should. * * @param progress_msg The progress message to display.<br> * If this parameter is NULL, a default "Encrypting file..." message is displayed. * * @return 0 on success, or negative on failure. */ int crypt_encrypt_ex(const char* in, struct crypt_keys* fk, const char* out, int verbose, const char* progress_msg); /** * @brief Decrypts a file using a crypt keys structure.<br> * This function must be called after crypt_gen_keys() and crypt_extract_salt()<br> * @see crypt_gen_keys() * @see crypt_extract_salt() * * @param in Path to a file to be decrypted. * * @param fk The crypt keys structure to decrypt with. * * @param out Path to write the decrypted file to.<br> * If this file already exists, it will be overwritten.<br> * If this function fails, the output file is removed. * * @return 0 on success, or negative on failure. */ int crypt_decrypt(const char* in, struct crypt_keys* fk, const char* out); /** * @brief Decrypts a file using a crypt keys structure and an optional progress bar.<br> * This function must be called after crypt_gen_keys() and crypt_extract_salt() * @see crypt_gen_keys() * @see crypt_extract_salt() * * @param in Path to a file to be decrypted. * * @param fk The crypt keys structure to decrypt with. * * @param out Path to write the decrypted file to.<br> * If this file already exists, it will be overwritten.<br> * If this function fails, the output file is removed. * * @param verbose 0 if a progress bar should not be displayed. Any other value if it should. * * @param progress_msg The progress message to display.<br> * If this parameter is NULL, a default "Decrypting file..." message is displayed. * * @return 0 on success, or negative on failure. */ int crypt_decrypt_ex(const char* in, struct crypt_keys* fk, const char* out, int verbose, const char* progress_msg); /** * @brief Extracts the salt from an encrypted file. * * @param in Path to a file to extract salt from. * * @param fk A crypt keys structure returned by crypt_new() * @see crypt_new() * * @return 0 on success, or negative on failure. */ int crypt_extract_salt(const char* in, struct crypt_keys* fk); /** * @brief Frees all memory associated with a crypt keys structure.<br> * This also scrubs sensitive data like encryption keys and the initialization vector. * * @param fk The crypt keys structure to free. * * @return void */ void crypt_free(struct crypt_keys* fk); /** * @brief Resets a crypt keys structure for reuse.<br> * This also scrubs sensitive data like encryption keys and the initialization vector.<br> * The resulting crypt keys structure will be identical to one returned by crypt_new() * @see crypt_new() * * @param fk The crypt keys structure to reset. * * @return void */ void crypt_reset(struct crypt_keys* fk); #endif
32.442231
171
0.719882
[ "vector" ]
00f514ae196505328a5ad70455f813ffb6c72120
16,138
c
C
private/ntos/config/hivebin.c
King0987654/windows2000
01f9c2e62c4289194e33244aade34b7d19e7c9b8
[ "MIT" ]
11
2017-09-02T11:27:08.000Z
2022-01-02T15:25:24.000Z
private/ntos/config/hivebin.c
King0987654/windows2000
01f9c2e62c4289194e33244aade34b7d19e7c9b8
[ "MIT" ]
null
null
null
private/ntos/config/hivebin.c
King0987654/windows2000
01f9c2e62c4289194e33244aade34b7d19e7c9b8
[ "MIT" ]
14
2019-01-16T01:01:23.000Z
2022-02-20T15:54:27.000Z
/*++ Copyright (c) 1991 Microsoft Corporation Module Name: hivebin.c Abstract: This module implements HvpAddBin - used to grow a hive. Author: Bryan M. Willman (bryanwi) 27-Mar-92 Environment: Revision History: --*/ #include "cmp.h" // // Private function prototypes // BOOLEAN HvpCoalesceDiscardedBins( IN PHHIVE Hive, IN ULONG NeededSize, IN HSTORAGE_TYPE Type ); #ifdef ALLOC_PRAGMA #pragma alloc_text(PAGE,HvpAddBin) #pragma alloc_text(PAGE,HvpFreeMap) #pragma alloc_text(PAGE,HvpAllocateMap) #pragma alloc_text(PAGE,HvpCoalesceDiscardedBins) #endif PHBIN HvpAddBin( IN PHHIVE Hive, IN ULONG NewSize, IN HSTORAGE_TYPE Type ) /*++ Routine Description: Grows either the Stable or Volatile storage of a hive by adding a new bin. Bin will be allocated space in Stable store (e.g. file) if Type == Stable. Memory image will be allocated and initialized. Map will be grown and filled in to describe the new bin. Arguments: Hive - supplies a pointer to the hive control structure for the hive of interest NewSize - size of the object caller wishes to put in the hive. New bin will be at least large enough to hold this. Type - Stable or Volatile Return Value: Pointer to the new BIN if we succeeded, NULL if we failed. --*/ { BOOLEAN UseForIo; PHBIN NewBin; ULONG OldLength; ULONG NewLength; ULONG OldMap; ULONG NewMap; ULONG OldTable; ULONG NewTable; PHMAP_DIRECTORY Dir; PHMAP_TABLE newt; PHMAP_ENTRY Me; PHCELL t; ULONG i; ULONG j; PULONG NewVector; PLIST_ENTRY Entry; PFREE_HBIN FreeBin; ULONG TotalDiscardedSize; CMLOG(CML_FLOW, CMS_HIVE) { KdPrint(("HvpAddBin:\n")); KdPrint(("\tHive=%08lx NewSize=%08lx\n",Hive,NewSize)); } // // Round size up to account for bin overhead. Caller should // have accounted for cell overhead. // NewSize += sizeof(HBIN); if ((NewSize < HCELL_BIG_ROUND) && ((NewSize % HBLOCK_SIZE) > HBIN_THRESHOLD)) { NewSize += HBLOCK_SIZE; } // // Try not to create HBINs smaller than the page size of the machine // (it is not illegal to have bins smaller than the page size, but it // is less efficient) // NewSize = ROUND_UP(NewSize, ((HBLOCK_SIZE >= PAGE_SIZE) ? HBLOCK_SIZE : PAGE_SIZE)); // // see if there's a discarded HBIN of the right size // TotalDiscardedSize = 0; Retry: Entry = Hive->Storage[Type].FreeBins.Flink; while (Entry != &Hive->Storage[Type].FreeBins) { FreeBin = CONTAINING_RECORD(Entry, FREE_HBIN, ListEntry); TotalDiscardedSize += FreeBin->Size; if (FreeBin->Size >= NewSize) { if (!HvMarkDirty(Hive, FreeBin->FileOffset + (Type * HCELL_TYPE_MASK), FreeBin->Size)) { goto ErrorExit1; } NewSize = FreeBin->Size; ASSERT_LISTENTRY(&FreeBin->ListEntry); RemoveEntryList(&FreeBin->ListEntry); if (FreeBin->Flags & FREE_HBIN_DISCARDABLE) { // // HBIN is still in memory, don't need any more allocs, just // fill in the block addresses. // for (i=0;i<NewSize;i+=HBLOCK_SIZE) { Me = HvpGetCellMap(Hive, FreeBin->FileOffset+i+(Type*HCELL_TYPE_MASK)); VALIDATE_CELL_MAP(__LINE__,Me,Hive,FreeBin->FileOffset+i+(Type*HCELL_TYPE_MASK)); Me->BlockAddress = (Me->BinAddress & HMAP_BASE)+i; Me->BinAddress &= ~HMAP_DISCARDABLE; } (Hive->Free)(FreeBin, sizeof(FREE_HBIN)); return((PHBIN)(Me->BinAddress & HMAP_BASE)); } break; } Entry = Entry->Flink; } if ((Entry == &Hive->Storage[Type].FreeBins) && (TotalDiscardedSize >= NewSize)) { // // No sufficiently large discarded bin was found, // but the total discarded space is large enough. // Attempt to coalesce adjacent discarded bins into // a larger bin and retry. // if (HvpCoalesceDiscardedBins(Hive, NewSize, Type)) { goto Retry; } } // // Attempt to allocate the bin. // UseForIo = (BOOLEAN)((Type == Stable) ? TRUE : FALSE); if (Entry != &Hive->Storage[Type].FreeBins) { // // Note we use ExAllocatePool directly here to avoid // charging quota for this bin again. When a bin // is discarded, its quota is not returned. This prevents // sparse hives from requiring more quota after // a reboot than on a running system. // NewBin = ExAllocatePoolWithTag((UseForIo) ? PagedPoolCacheAligned : PagedPool, NewSize, CM_POOL_TAG); if (NewBin == NULL) { InsertHeadList(&Hive->Storage[Type].FreeBins, Entry); HvMarkClean(Hive, FreeBin->FileOffset, FreeBin->Size); goto ErrorExit1; } } else { NewBin = (Hive->Allocate)(NewSize, UseForIo); if (NewBin == NULL) { goto ErrorExit1; } } // // Init the bin // NewBin->Signature = HBIN_SIGNATURE; NewBin->Size = NewSize; NewBin->MemAlloc = NewSize; t = (PHCELL)((PUCHAR)NewBin + sizeof(HBIN)); t->Size = NewSize - sizeof(HBIN); if (USE_OLD_CELL(Hive)) { t->u.OldCell.Last = (ULONG)HBIN_NIL; } if (Entry != &Hive->Storage[Type].FreeBins) { // // found a discarded HBIN we can use, just fill in the map and we // are done. // for (i=0;i<NewSize;i+=HBLOCK_SIZE) { Me = HvpGetCellMap(Hive, FreeBin->FileOffset+i+(Type*HCELL_TYPE_MASK)); VALIDATE_CELL_MAP(__LINE__,Me,Hive,FreeBin->FileOffset+i+(Type*HCELL_TYPE_MASK)); Me->BlockAddress = (ULONG_PTR)NewBin + i; Me->BinAddress = (ULONG_PTR)NewBin; if (i==0) { Me->BinAddress |= HMAP_NEWALLOC; } } NewBin->FileOffset = FreeBin->FileOffset; (Hive->Free)(FreeBin, sizeof(FREE_HBIN)); return(NewBin); } // // Compute map growth needed, grow the map // OldLength = Hive->Storage[Type].Length; NewLength = OldLength + NewSize; NewBin->FileOffset = OldLength; ASSERT((OldLength % HBLOCK_SIZE) == 0); ASSERT((NewLength % HBLOCK_SIZE) == 0); if (OldLength == 0) { // // Need to create the first table // newt = (PVOID)((Hive->Allocate)(sizeof(HMAP_TABLE), FALSE)); if (newt == NULL) { goto ErrorExit2; } RtlZeroMemory(newt, sizeof(HMAP_TABLE)); Hive->Storage[Type].SmallDir = newt; Hive->Storage[Type].Map = (PHMAP_DIRECTORY)&(Hive->Storage[Type].SmallDir); } if (OldLength > 0) { OldMap = (OldLength-1) / HBLOCK_SIZE; } else { OldMap = 0; } NewMap = (NewLength-1) / HBLOCK_SIZE; OldTable = OldMap / HTABLE_SLOTS; NewTable = NewMap / HTABLE_SLOTS; if (NewTable != OldTable) { // // Need some new Tables // if (OldTable == 0) { // // We can get here even if the real directory has already been created. // This can happen if we create the directory then fail on something // later. So we need to handle the case where a directory already exists. // if (Hive->Storage[Type].Map == (PHMAP_DIRECTORY)&Hive->Storage[Type].SmallDir) { ASSERT(Hive->Storage[Type].SmallDir != NULL); // // Need a real directory // Dir = (Hive->Allocate)(sizeof(HMAP_DIRECTORY), FALSE); if (Dir == NULL) { goto ErrorExit2; } RtlZeroMemory(Dir, sizeof(HMAP_DIRECTORY)); Dir->Directory[0] = Hive->Storage[Type].SmallDir; Hive->Storage[Type].SmallDir = NULL; Hive->Storage[Type].Map = Dir; } else { ASSERT(Hive->Storage[Type].SmallDir == NULL); } } Dir = Hive->Storage[Type].Map; // // Fill in directory with new tables // if (HvpAllocateMap(Hive, Dir, OldTable+1, NewTable) == FALSE) { goto ErrorExit3; } } // // If Type == Stable, and the hive is not marked WholeHiveVolatile, // grow the file, the log, and the DirtyVector // Hive->Storage[Type].Length = NewLength; if ((Type == Stable) && (!(Hive->HiveFlags & HIVE_VOLATILE))) { // // Grow the dirtyvector // NewVector = (PULONG)(Hive->Allocate)(ROUND_UP(NewMap+1,sizeof(ULONG)), TRUE); if (NewVector == NULL) { goto ErrorExit3; } RtlZeroMemory(NewVector, NewMap+1); if (Hive->DirtyVector.Buffer != NULL) { RtlCopyMemory( (PVOID)NewVector, (PVOID)Hive->DirtyVector.Buffer, OldMap+1 ); (Hive->Free)(Hive->DirtyVector.Buffer, Hive->DirtyAlloc); } RtlInitializeBitMap( &(Hive->DirtyVector), NewVector, NewLength / HSECTOR_SIZE ); Hive->DirtyAlloc = NewMap+1; // // Grow the log // if ( ! (HvpGrowLog2(Hive, NewSize))) { goto ErrorExit4; } // // Grow the primary // if ( ! (Hive->FileSetSize)( Hive, HFILE_TYPE_PRIMARY, NewLength+HBLOCK_SIZE ) ) { goto ErrorExit4; } // // Grow the alternate if it exists // if (Hive->Alternate == TRUE) { if ( ! (Hive->FileSetSize)( Hive, HFILE_TYPE_ALTERNATE, NewLength+HBLOCK_SIZE ) ) { (Hive->FileSetSize)( Hive, HFILE_TYPE_PRIMARY, OldLength+HBLOCK_SIZE ); goto ErrorExit4; } } // // Mark new bin dirty so all control structures get written at next sync // if ( ! HvMarkDirty(Hive, OldLength, NewSize)) { goto ErrorExit4; } } // // Fill in the map, mark new allocation. // j = 0; for (i = OldLength; i < NewLength; i += HBLOCK_SIZE) { Me = HvpGetCellMap(Hive, i + (Type*HCELL_TYPE_MASK)); VALIDATE_CELL_MAP(__LINE__,Me,Hive,i + (Type*HCELL_TYPE_MASK)); Me->BlockAddress = (ULONG_PTR)NewBin + j; Me->BinAddress = (ULONG_PTR)NewBin; if (j == 0) { // // First block of allocation, mark it. // Me->BinAddress |= HMAP_NEWALLOC; } j += HBLOCK_SIZE; } return NewBin; ErrorExit4: RtlInitializeBitMap(&Hive->DirtyVector, NewVector, OldLength / HSECTOR_SIZE); Hive->DirtyCount = RtlNumberOfSetBits(&Hive->DirtyVector); ErrorExit3: Hive->Storage[Type].Length = OldLength; HvpFreeMap(Hive, Dir, OldTable+1, NewTable); ErrorExit2: (Hive->Free)(NewBin, NewSize); ErrorExit1: return NULL; } BOOLEAN HvpCoalesceDiscardedBins( IN PHHIVE Hive, IN ULONG NeededSize, IN HSTORAGE_TYPE Type ) /*++ Routine Description: Walks through the list of discarded bins and attempts to coalesce adjacent discarded bins into one larger bin in order to satisfy an allocation request. Arguments: Hive - Supplies pointer to hive control block. NeededSize - Supplies size of allocation needed. Type - Stable or Volatile Return Value: TRUE - A bin of the desired size was created. FALSE - No bin of the desired size could be created. --*/ { PLIST_ENTRY List; PFREE_HBIN FreeBin; PFREE_HBIN PreviousFreeBin; PFREE_HBIN NextFreeBin; PHMAP_ENTRY Map; PHMAP_ENTRY PreviousMap; PHMAP_ENTRY NextMap; ULONG MapBlock; List = Hive->Storage[Type].FreeBins.Flink; while (List != &Hive->Storage[Type].FreeBins) { FreeBin = CONTAINING_RECORD(List, FREE_HBIN, ListEntry); if ((FreeBin->Flags & FREE_HBIN_DISCARDABLE)==0) { Map = HvpGetCellMap(Hive, FreeBin->FileOffset); VALIDATE_CELL_MAP(__LINE__,Map,Hive,FreeBin->FileOffset); // // Scan backwards, coalescing previous discarded bins // while (FreeBin->FileOffset > 0) { PreviousMap = HvpGetCellMap(Hive, FreeBin->FileOffset - HBLOCK_SIZE); VALIDATE_CELL_MAP(__LINE__,PreviousMap,Hive,FreeBin->FileOffset - HBLOCK_SIZE); if (PreviousMap->BinAddress & HMAP_DISCARDABLE) { PreviousFreeBin = (PFREE_HBIN)PreviousMap->BlockAddress; if (PreviousFreeBin->Flags & FREE_HBIN_DISCARDABLE) { break; } RemoveEntryList(&PreviousFreeBin->ListEntry); // // Fill in all the old map entries with the new one. // for (MapBlock = 0; MapBlock < PreviousFreeBin->Size; MapBlock += HBLOCK_SIZE) { PreviousMap = HvpGetCellMap(Hive, PreviousFreeBin->FileOffset + MapBlock); VALIDATE_CELL_MAP(__LINE__,PreviousMap,Hive,PreviousFreeBin->FileOffset + MapBlock); PreviousMap->BlockAddress = (ULONG_PTR)FreeBin; } FreeBin->FileOffset = PreviousFreeBin->FileOffset; FreeBin->Size += PreviousFreeBin->Size; (Hive->Free)(PreviousFreeBin, sizeof(FREE_HBIN)); } else { break; } } // // Scan forwards, coalescing subsequent discarded bins // while ((FreeBin->FileOffset + FreeBin->Size) < Hive->BaseBlock->Length) { NextMap = HvpGetCellMap(Hive, FreeBin->FileOffset + FreeBin->Size); VALIDATE_CELL_MAP(__LINE__,NextMap,Hive,FreeBin->FileOffset + FreeBin->Size); if (NextMap->BinAddress & HMAP_DISCARDABLE) { NextFreeBin = (PFREE_HBIN)NextMap->BlockAddress; if (NextFreeBin->Flags & FREE_HBIN_DISCARDABLE) { break; } RemoveEntryList(&NextFreeBin->ListEntry); // // Fill in all the old map entries with the new one. // for (MapBlock = 0; MapBlock < NextFreeBin->Size; MapBlock += HBLOCK_SIZE) { NextMap = HvpGetCellMap(Hive, NextFreeBin->FileOffset + MapBlock); VALIDATE_CELL_MAP(__LINE__,NextMap,Hive,NextFreeBin->FileOffset + MapBlock); NextMap->BlockAddress = (ULONG_PTR)FreeBin; } FreeBin->Size += NextFreeBin->Size; (Hive->Free)(NextFreeBin, sizeof(FREE_HBIN)); } else { break; } } if (FreeBin->Size >= NeededSize) { return(TRUE); } } List=List->Flink; } return(FALSE); }
29.077477
109
0.534887
[ "object" ]
00fbef23199bb41673d49882fd82447be3ac04e5
2,831
h
C
sdk/include/alibabacloud/pds/Types.h
aliyun/aliyun-pds-cpp-sdk
d1f5091efe7a3ac971285ccb82bbf9cc77a41ccc
[ "Apache-2.0" ]
2
2021-09-18T12:51:39.000Z
2021-09-19T13:38:31.000Z
sdk/include/alibabacloud/pds/Types.h
aliyun/aliyun-pds-cpp-sdk
d1f5091efe7a3ac971285ccb82bbf9cc77a41ccc
[ "Apache-2.0" ]
null
null
null
sdk/include/alibabacloud/pds/Types.h
aliyun/aliyun-pds-cpp-sdk
d1f5091efe7a3ac971285ccb82bbf9cc77a41ccc
[ "Apache-2.0" ]
null
null
null
/* * Copyright 2009-2021 Alibaba Cloud 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. */ #pragma once #include <cstdint> #include <vector> #include <string> #include <map> #include <memory> #include <functional> #include <alibabacloud/pds/Export.h> namespace AlibabaCloud { namespace PDS { enum LogLevel { LogOff = 0, LogFatal, LogError, LogWarn, LogInfo, LogDebug, LogTrace, LogAll, }; typedef void(*LogCallback)(LogLevel level, const std::string& stream); struct ALIBABACLOUD_PDS_EXPORT caseSensitiveLess { bool operator() (const std::string& lhs, const std::string& rhs) const { return lhs < rhs; } }; struct ALIBABACLOUD_PDS_EXPORT caseInsensitiveLess { bool operator() (const std::string& lhs, const std::string& rhs) const { auto first1 = lhs.begin(), last1 = lhs.end(); auto first2 = rhs.begin(), last2 = rhs.end(); while (first1 != last1) { if (first2 == last2) return false; auto first1_ch = ::tolower(*first1); auto first2_ch = ::tolower(*first2); if (first1_ch != first2_ch) { return (first1_ch < first2_ch); } ++first1; ++first2; } return (first2 != last2); } }; using TransferProgressHandler = std::function<void(size_t increment, int64_t transferred, int64_t total, void *userData)>; struct ALIBABACLOUD_PDS_EXPORT TransferProgress { TransferProgressHandler Handler; void *UserData; }; using ProgressControlHandler = std::function<int32_t(void *userData)>; struct ALIBABACLOUD_PDS_EXPORT ProgressControl { ProgressControlHandler Handler; void *UserData; }; using MetaData = std::map<std::string, std::string, caseInsensitiveLess>; using HeaderCollection = std::map<std::string, std::string, caseInsensitiveLess>; using ParameterCollection = std::map<std::string, std::string, caseSensitiveLess>; using IOStreamFactory = std::function< std::shared_ptr<std::iostream>(void)>; using ByteBuffer = std::vector<unsigned char>; } }
30.117021
126
0.628753
[ "vector" ]
00fbf2fb89ac116368c89d430cd2a2a47059e73a
18,354
c
C
src/parseconfig.c
mxplusb/udp-repeater
f8b2b74ecc9710432306a61bdaed54bbda149a0e
[ "Apache-2.0" ]
25
2016-12-07T16:24:44.000Z
2022-01-27T10:26:54.000Z
src/parseconfig.c
mxplusb/udp-repeater
f8b2b74ecc9710432306a61bdaed54bbda149a0e
[ "Apache-2.0" ]
2
2018-04-29T10:03:49.000Z
2019-01-17T01:10:11.000Z
src/parseconfig.c
mxplusb/udp-repeater
f8b2b74ecc9710432306a61bdaed54bbda149a0e
[ "Apache-2.0" ]
8
2017-09-05T15:28:06.000Z
2022-01-27T16:14:40.000Z
/* * parseconfig.c * * Parses a json config file for repeater.c * * Created 2015-07-29 * Updated 2015-10-15 * * Thomas Coe * Union Pacific Railroad * */ #include <arpa/inet.h> #include <stdio.h> #include <stdlib.h> #include <sys/stat.h> #include "parseconfig.h" #include "repeater.h" int main(int argc, char *argv[]) { // Check params if (argc != 3) { fprintf(stderr, "USAGE: %s rules.json repeater.log\n", argv[0]); return 1; } // Parse json config file parse_config(argv[1]); // Start the repeater if (start_repeater(argv[2]) < 0) { fprintf(stderr, "Couldn't start repeater.\n"); } } /** * Opens the file at the filename provided, and runs the json parser on the * file data to get it into a usable form to process. Calls parse_rules() on * the parsed json. * * @param filename The path to the json config file */ void parse_config(char *filename) { FILE* fp; char* rules; // Open the rules file fp = fopen(filename, "r"); if (fp == NULL) { fprintf(stderr, "ERROR (fatal): Could not open rules file\n"); exit(1); } // Malloc size of rules file struct stat st; int rc = fstat(fileno(fp), &st); if (rc < 0) { perror("fstat: "); exit(1); } int filesize = st.st_size; rules = calloc(1, filesize + 1); if (rules == NULL) { fprintf(stderr, "ERROR (fatal): Malloc on %d bytes failed!\n", (filesize + 1)); exit(1); } // Read in json from rules file if (fread(rules, filesize, 1, fp) != 1) { fprintf(stderr, "ERROR (fatal): Could not read from rules file\n"); exit(1); } fclose(fp); #ifdef DEBUG printf("%s\n", rules); #endif // Run the json parser on the rules pointer json_settings settings = { 0 }; settings.settings |= json_enable_comments; // Enable C style comments in the json json_value* json_rules = json_parse_ex(&settings, (json_char*)rules, filesize); if (json_rules == NULL) { fprintf(stderr, "ERROR (fatal): Couldn't parse json rules\n"); free(rules); exit(1); } // Decode the rules parse_rules(json_rules); // Free data json_value_free(json_rules); free(rules); } /** * Parses the decoded json_value. Ensures that the rules have listen, * transmit, target, and map arrays defined. Calls other functions to parse * those types individually. * * @param json_rules The json_value* obtained from json_parse() */ int parse_rules(json_value* json_rules) { bool listen_found = false; bool transmit_found = false; bool target_found = false; bool map_found = false; bool exit_now = false; // Loop through each json object for (int i = 0; i < json_rules->u.object.length; i++) { char *name = json_rules->u.object.values[i].name; json_value *value = json_rules->u.object.values[i].value; int type = value->type; if ( strncmp(name, "listen", 6) == 0 ) { listen_found = true; if (type != json_array) { printf("Error: listen type is not array\n"); exit(1); } // Loop through all listeners in the array for (int x = 0; x < value->u.array.length; x++) { parse_listener(value->u.array.values[x]); } } else if ( strncmp(name, "transmit", 8) == 0 ) { transmit_found = true; if (type != json_array) { printf("Error: transmit type is not array\n"); exit(1); } // Loop through all transmitters in the array for (int x = 0; x < value->u.array.length; x++) { parse_transmitter(value->u.array.values[x]); } } else if ( strncmp(name, "target", 6) == 0 ) { target_found = true; if (type != json_array) { printf("Error: target type is not array\n"); exit(1); } // Loop through all targets in the array for (int x = 0; x < value->u.array.length; x++) { parse_target(value->u.array.values[x]); } } else if ( strncmp(name, "map", 3) == 0 ) { map_found = true; if (type != json_array) { printf("Error: map type is not array\n"); exit(1); } // Loop through all maps in the array for (int x = 0; x < value->u.array.length; x++) { parse_map(value->u.array.values[x]); } } else { printf("Unrecognized token in rules (%s)", name); } } // If one type of array was not found, kill the program if (!listen_found) { fprintf(stderr, "ERROR: listen config not found\n"); exit_now = true; } if (!transmit_found) { fprintf(stderr, "ERROR: transmit config not found\n"); exit_now = true; } if (!target_found) { fprintf(stderr, "ERROR: target config not found\n"); exit_now = true; } if (!map_found) { fprintf(stderr, "ERROR: map config not found\n"); exit_now = true; } if (exit_now) { exit(1); } return 0; } /** * Parses a json object identified as a listener * * Iterates through the fields, and ensures the proper fields have been * included. If a field is missing, reports the error and kills the program. * * Uses repeater.c's create_listener() function */ void parse_listener(json_value *value) { int id = 0; uint32_t address = 0; uint16_t port = 0; bool id_found = false; bool address_found = false; bool port_found = false; bool exit_now = false; // Iterate through the fields in the listener for (int i = 0; i < value->u.object.length; i++) { char *name = value->u.object.values[i].name; json_value *field = value->u.object.values[i].value; int type = field->type; if ( strncmp(name, "id", 2) == 0 ) { id_found = true; if (type != json_integer) { printf("Error: listen->id must be an integer\n"); exit(1); } id = field->u.integer; } else if ( strncmp(name, "address", 7) == 0 ) { address_found = true; if (type != json_string) { printf("Error: listen->address must be a dotted decimal string\n"); exit(1); } if ( strncmp(field->u.string.ptr, "*", 1) == 0 ) { address = 0; } else { struct in_addr addr; int rc = inet_pton(AF_INET, field->u.string.ptr, &addr); if (rc == 0) { printf("Error: listen->address is not a valid IPv4 address\n"); exit(1); } address = ntohl(addr.s_addr); } } else if ( strncmp(name, "port", 4) == 0 ) { port_found = true; if (type != json_string) { printf("Error: listen->port must be a string\n"); exit(1); } int temp = atoi(field->u.string.ptr); if (temp <= 1024 || temp > 65535) { printf("%d is an invalid port. Must be between 1024-65536 noninclusive", temp); exit(1); } port = temp; } } // Check that all parameters were included for this listener if (!id_found) { fprintf(stderr, "ERROR: listen->id not found\n"); exit_now = true; } if (!address_found) { fprintf(stderr, "ERROR: listen->address not found\n"); exit_now = true; } if (!port_found) { fprintf(stderr, "ERROR: listen->port not found\n"); exit_now = true; } if (exit_now) { exit(1); } #ifdef DEBUG printf("Listener- ID: %d, addr: %lu, port: %d\n", id, (long unsigned int)address, port); #endif create_listener(id, address, port); } /** * Parses a json object identified as a transmitter * * Iterates through the fields, and ensures the proper fields have been * included. If a field is missing, reports the error and kills the program. * * Uses repeater.c's create_transmitter() function */ void parse_transmitter(json_value *value) { int id = 0; uint32_t address = 0; uint16_t port = 0; bool id_found = false; bool address_found = false; bool port_found = false; bool exit_now = false; // Iterate through the fields in the listener for (int i = 0; i < value->u.object.length; i++) { char *name = value->u.object.values[i].name; json_value *field = value->u.object.values[i].value; int type = field->type; if ( strncmp(name, "id", 2) == 0 ) { id_found = true; if (type != json_integer) { printf("Error: transmit->id must be an integer\n"); exit(1); } id = field->u.integer; } else if ( strncmp(name, "address", 7) == 0 ) { address_found = true; if (type != json_string) { printf("Error: transmit->address must be a dotted decimal string\n"); exit(1); } if ( strncmp(field->u.string.ptr, "*", 1) == 0 ) { address = 0; } else { //address = ntohl(inet_addr(field->u.string.ptr)); struct in_addr addr; int rc = inet_pton(AF_INET, field->u.string.ptr, &addr); if (rc == 0) { printf("Error: transmit->address is not a valid IPv4 address\n"); exit(1); } address = ntohl(addr.s_addr); } } else if ( strncmp(name, "port", 4) == 0 ) { port_found = true; if (type != json_string) { printf("Error: transmit->port must be a string\n"); exit(1); } if ( strncmp(field->u.string.ptr, "*", 1) == 0 ) { port = 0; } else { int temp = atoi(field->u.string.ptr); if (temp <= 1024 || temp > 65535) { printf("%d is an invalid port. Must be between 1024-65536 noninclusive", temp); exit(1); } port = temp; } } } // Check that all parameters were included for this listener if (!id_found) { fprintf(stderr, "ERROR: transmit->id not found\n"); exit_now = true; } if (!address_found) { fprintf(stderr, "ERROR: transmit->address not found\n"); exit_now = true; } if (!port_found) { fprintf(stderr, "ERROR: transmit->port not found\n"); exit_now = true; } if (exit_now) { exit(1); } #ifdef DEBUG printf("Transmitter- ID: %d, addr: %lu, port: %d\n", id, (long unsigned int)address, port); #endif create_transmitter(id, address, port); } /** * Parses a json object identified as a target * * Iterates through the fields, and ensures the proper fields have been * included. If a field is missing, reports the error and kills the program. * * Uses repeater.c's create_target() function */ void parse_target(json_value *value) { int id = 0; uint32_t address = 0; uint16_t port = 0; int transmit_id = 0; bool id_found = false; bool address_found = false; bool port_found = false; bool transmit_found = false; bool exit_now = false; // Iterate through the fields in the target for (int i = 0; i < value->u.object.length; i++) { char *name = value->u.object.values[i].name; json_value *field = value->u.object.values[i].value; int type = field->type; if ( strncmp(name, "id", 2) == 0 ) { id_found = true; if (type != json_integer) { printf("Error: target->id must be an integer\n"); exit(1); } id = field->u.integer; } else if ( strncmp(name, "address", 7) == 0 ) { address_found = true; if (type != json_string) { printf("Error: target->address must be a dotted decimal string\n"); exit(1); } //address = ntohl(inet_addr(field->u.string.ptr)); struct in_addr addr; int rc = inet_pton(AF_INET, field->u.string.ptr, &addr); if (rc == 0) { printf("Error: target->address is not a valid IPv4 address\n"); exit(1); } address = ntohl(addr.s_addr); } else if ( strncmp(name, "port", 4) == 0 ) { port_found = true; if (type != json_string) { printf("Error: target->port must be a string\n"); exit(1); } int temp = atoi(field->u.string.ptr); if (temp <= 1024 || temp > 65535) { printf("%d is an invalid port. Must be between 1024-65536 noninclusive", temp); exit(1); } port = temp; } else if ( strncmp(name, "transmitter", 11) == 0 ) { transmit_found = true; if (type != json_integer) { printf("Error: target->transmitter must be an integer\n"); exit(1); } transmit_id = field->u.integer; } } // Check that all parameters were included for this target if (!id_found) { fprintf(stderr, "ERROR: target->id not found\n"); exit_now = true; } if (!address_found) { fprintf(stderr, "ERROR: target->address not found\n"); exit_now = true; } if (!port_found) { fprintf(stderr, "ERROR: target->port not found\n"); exit_now = true; } if (!transmit_found) { fprintf(stderr, "ERROR: target->transmitter not found\n"); exit_now = true; } if (exit_now) { exit(1); } #ifdef DEBUG printf("Target- ID: %d, addr: %lu, port: %d transmitter: %d\n", id, (long unsigned int)address, port, transmit_id); #endif create_target(id, address, port, transmit_id); } /** * Parses a json object identified as a map * * Iterates through the fields, and ensures the proper fields have been * included. If a field is missing, reports the error and kills the program. * * Uses repeater.c's create_map() function */ void parse_map(json_value *value) { int source = 0; int target = 0; int i = 0; json_value *targets = NULL; uint32_t address = 0; uint16_t port = 0; bool source_found = false; bool target_found = false; bool address_found = false; bool port_found = false; bool exit_now = false; // Iterate through the fields in the listener for (int i = 0; i < value->u.object.length; i++) { char *name = value->u.object.values[i].name; json_value *field = value->u.object.values[i].value; int type = field->type; if ( strncmp(name, "source", 6) == 0 ) { source_found = true; if (type != json_integer) { printf("Error: map->source must be an integer\n"); exit(1); } source = field->u.integer; } else if ( strncmp(name, "target", 6) == 0 ) { target_found = true; if (type != json_array) { printf("Error: map->target must be an array of integers\n"); exit(1); } targets = field; } else if ( strncmp(name, "address", 7) == 0 ) { address_found = true; if (type != json_string) { printf("Error: map->address must be a dotted decimal string\n"); exit(1); } if ( strncmp(field->u.string.ptr, "*", 1) == 0 ) { address = 0; } else { //address = ntohl(inet_addr(field->u.string.ptr)); struct in_addr addr; int rc = inet_pton(AF_INET, field->u.string.ptr, &addr); if (rc == 0) { printf("Error: map->address is not a valid IPv4 address\n"); exit(1); } address = ntohl(addr.s_addr); } } else if ( strncmp(name, "port", 4) == 0 ) { port_found = true; if (type != json_string) { printf("Error: map->port must be a string\n"); exit(1); } if ( strncmp(field->u.string.ptr, "*", 1) == 0 ) { port = 0; } else { int temp = atoi(field->u.string.ptr); if (temp <= 1024 || temp > 65535) { printf("%d is an invalid port. Must be between 1024-65536 noninclusive", temp); exit(1); } port = temp; } } } // Check that all parameters were included for this listener if (!source_found) { fprintf(stderr, "ERROR: map->source not found\n"); exit_now = true; } if (!target_found) { fprintf(stderr, "ERROR: map->target not found\n"); exit_now = true; } if (!address_found) { fprintf(stderr, "ERROR: map->address not found\n"); exit_now = true; } if (!port_found) { fprintf(stderr, "ERROR: map->port not found\n"); exit_now = true; } if (exit_now) { exit(1); } // Loop through all of the targets, creating map for each if (targets == NULL) { fprintf(stderr, "ERROR: targets is NULL\n"); exit(1); } for (i = 0; i < targets->u.array.length; i++) { json_value *value = targets->u.array.values[i]; if (value->type != json_integer) { printf("Error: map->target must be an array of integers\n"); exit(1); } target = value->u.integer; #ifdef DEBUG printf("Map- source: %d, target: %d addr: %lu, port: %d\n", source, target, (long unsigned int)address, port); #endif create_map(source, address, port, target); } }
31.214286
119
0.522992
[ "object" ]
2e08407c3d9526dbbc3800661987fd7cab5b6b4f
691
h
C
src/sl/gfx/FrameBuffer.h
nekoffski/starlight
350aba4445a242c427961da2aad51af13e596c5f
[ "MIT" ]
8
2020-02-18T18:12:40.000Z
2022-03-06T00:30:37.000Z
src/sl/gfx/FrameBuffer.h
nekoffski/starlight
350aba4445a242c427961da2aad51af13e596c5f
[ "MIT" ]
null
null
null
src/sl/gfx/FrameBuffer.h
nekoffski/starlight
350aba4445a242c427961da2aad51af13e596c5f
[ "MIT" ]
1
2021-04-05T13:18:52.000Z
2021-04-05T13:18:52.000Z
#pragma once #include <memory> #include "sl/gfx/Cubemap.h" #include "sl/gfx/RenderBuffer.h" #include "sl/gfx/Texture.h" namespace sl::gfx { class FrameBuffer { public: struct Factory { virtual std::shared_ptr<FrameBuffer> create() = 0; virtual ~Factory() = default; }; virtual ~FrameBuffer() = default; virtual void bindRenderBuffer(RenderBuffer&) = 0; virtual void bindTexture(Texture&, unsigned int attachment) = 0; virtual void bindTexture(Texture&) = 0; virtual void bindCubemap(Cubemap&) = 0; virtual void specifyColorBuffers(const std::vector<unsigned int>&) = 0; virtual void bind() = 0; virtual void unbind() = 0; }; }
22.290323
75
0.668596
[ "vector" ]
2e1cf3fa1da2030f8b1819a1cb2e325dfda6b4df
1,782
h
C
Space Bandits/dynosprite/src/DSObjectCoordinator.h
jamieleecho/dynosprite
3764bd080e55ca2ca5b0d6a87cf485e16a9d1e82
[ "BSD-2-Clause" ]
6
2016-05-01T13:02:27.000Z
2021-01-04T18:18:20.000Z
Space Bandits/dynosprite/src/DSObjectCoordinator.h
jamieleecho/space-bandits
b0f45c4d6e8a2bbf8d1653b7b3c10059fa9ff13d
[ "BSD-2-Clause" ]
null
null
null
Space Bandits/dynosprite/src/DSObjectCoordinator.h
jamieleecho/space-bandits
b0f45c4d6e8a2bbf8d1653b7b3c10059fa9ff13d
[ "BSD-2-Clause" ]
1
2016-05-01T13:02:30.000Z
2016-05-01T13:02:30.000Z
// // DSObjectCoordinator.h // Space Bandits // // Created by Jamie Cho on 7/7/20. // Copyright © 2020 Jamie Cho. All rights reserved. // #import <Foundation/Foundation.h> #import <SpriteKit/SpriteKit.h> #import "DSLevel.h" #import "DSSpriteObjectClass.h" #import "DSObjectClassData.h" #import "DSObjectClassDataRegistry.h" #import "DynospriteDirectPageGlobals.h" NS_ASSUME_NONNULL_BEGIN /** * This class builds all of the */ @interface DSObjectCoordinator : NSObject { /** Number of items in _cobs and _odts */ size_t _count; /** Object data table entries */ DynospriteODT *_odts; /** Pointers to individual COB entries for each object */ DynospriteCOB * _Nonnull _cobs; /** Ponters to individual initialization data for eacb object */ byte * _Nonnull * _Nonnull _initData; DSLevel *_level; DSObjectClassDataRegistry *_classRegistry; } - (DSLevel *)level; - (DSObjectClassDataRegistry *)classRegistry; /** * Initializes level objects by building up all of the objects required to run it. */ - (id)initWithLevel:(DSLevel *)level andClassRegistry:(DSObjectClassDataRegistry *)classRegistry; /** * Calls the initMethod on each object. */ - (void)initializeObjects; /** * Calls the update or reactivate on each object, depending on whether they are active. * @return 0 if no new level, otherwise returns the level we should move to. */ - (byte)updateOrReactivateObjects; /** @return the number of objects in this level */ - (size_t)count; /** @return the ODT for this level*/ - (DynospriteODT * _Nonnull)odts; /** @return the COB for this level*/ - (DynospriteCOB * _Nonnull)cobs; /** @return the initialization data for each COB */ - (byte * _Nonnull * _Nonnull)initData; @end NS_ASSUME_NONNULL_END
24.081081
97
0.713805
[ "object" ]
2e3109bfd921aa26c593a2cc35abdff049dff85a
3,803
c
C
leetcode/113-path-sum-ii/solution.c
dantin/poj
812859a982da666daecedbb1197afed21485a432
[ "BSD-3-Clause" ]
null
null
null
leetcode/113-path-sum-ii/solution.c
dantin/poj
812859a982da666daecedbb1197afed21485a432
[ "BSD-3-Clause" ]
null
null
null
leetcode/113-path-sum-ii/solution.c
dantin/poj
812859a982da666daecedbb1197afed21485a432
[ "BSD-3-Clause" ]
null
null
null
#include <stdio.h> #include <stdlib.h> #include <string.h> #include <limits.h> struct Object { int *nums; int len; int target; }; struct TreeNode { int val; struct TreeNode *left; struct TreeNode *right; }; void print_nums(int *nums, int size) { if (size < 1) { printf("[]"); return; } int i; printf("[%d", nums[0]); for (i = 1; i < size; i++) { printf(", %d", nums[i]); } printf("]"); } struct TreeNode *make_tree_node(int *nums, int pos, int size) { if (pos < 0 || pos >= size || nums[pos] == INT_MIN) { return NULL; } int left = 2 * pos + 1; int right = 2 * pos + 2; struct TreeNode *node = malloc(sizeof(*node)); node->val = nums[pos]; node->left = make_tree_node(nums, left, size); node->right = make_tree_node(nums, right, size); return node; } struct TreeNode *make_tree(int *nums, int size) { return make_tree_node(nums, 0, size); } void print_tree(struct TreeNode *node) { if (node == NULL) { printf("# "); return; } printf("%d ", node->val); print_tree(node->left); print_tree(node->right); } void free_tree(struct TreeNode *node) { if (node == NULL) { return; } free_tree(node->left); free_tree(node->right); free(node); } void dfs(struct TreeNode *node, int sum, int *stack, int len, int **results, int *sizes, int *count) { if (node == NULL) { return; } sum -= node->val; if (node->left == NULL && node->right == NULL && sum == 0) { results[*count] = malloc((len + 1) * sizeof(int)); memcpy(results[*count], stack, len * sizeof(int)); results[*count][len] = node->val; sizes[*count] = len + 1; (*count)++; return; } stack[len] = node->val; dfs(node->left, sum, stack, len + 1, results, sizes, count); dfs(node->right, sum, stack, len + 1, results, sizes, count); } int **path_sum(struct TreeNode *root, int sum, int **column_sizes, int *return_size) { if (root == NULL) { *return_size = 0; return NULL; } int level = 5000, capacity = 1000; int *stack = malloc(level * sizeof(int)); int **results = malloc(capacity * sizeof(int *)); *column_sizes = malloc(capacity * sizeof(int)); dfs(root, sum, stack, 0, results, *column_sizes, return_size); free(stack); return results; } int main(int argc, char **argv) { int nums1[] = { 5, 4, 8, 11, INT_MIN, 13, 4, 7, 2, INT_MIN, INT_MIN, INT_MIN, INT_MIN, 5, 1 }, len1 = sizeof(nums1) / sizeof(int), target1 = 22; struct Object inputs[] = { { .nums = nums1, .len = len1, .target = target1 }, }; int i, len = sizeof(inputs) / sizeof(struct Object); int indent = 2, j = 0, return_size, *column_sizes; for (i = 0; i < len; i++) { int *nums = inputs[i].nums; int size = inputs[i].len; int target = inputs[i].target; struct TreeNode *root = make_tree(nums, size); printf("\n Input: "); print_tree(root); printf(", target = %d\n", target); int **paths = path_sum(root, target, &column_sizes, &return_size); printf(" Output:\n"); j = 0; if (return_size < 1) { printf("[]\n"); continue; } printf("[\n"); printf("%*s", indent, ""); print_nums(paths[j], column_sizes[j]); for (j = 1; j < return_size; j++) { printf(",\n%*s", indent, ""); print_nums(paths[j], column_sizes[j]); } printf("\n]\n"); for (j = 0; j < return_size; j++) { free(paths[j]); } free(paths); free(column_sizes); free_tree(root); } return EXIT_SUCCESS; }
23.331288
145
0.533789
[ "object" ]
2e372e8e335812605b7e15eb5fd51239f07278d0
2,764
h
C
src/Common/BotBase/PlanBotBase.h
ddelamare/BotWithAPlan
534dfd55ea767b7d860da720f7a65a211c2c8ea4
[ "MIT" ]
2
2018-11-01T07:52:27.000Z
2021-10-09T06:13:40.000Z
src/Common/BotBase/PlanBotBase.h
ddelamare/BotWithAPlan
534dfd55ea767b7d860da720f7a65a211c2c8ea4
[ "MIT" ]
null
null
null
src/Common/BotBase/PlanBotBase.h
ddelamare/BotWithAPlan
534dfd55ea767b7d860da720f7a65a211c2c8ea4
[ "MIT" ]
null
null
null
#pragma once #include <sc2api/sc2_api.h> #include "Common\Resource.h" #include "Planner\Planner.h" #include "Goals\GoalPicker.h" #include "Common\ItemDependencies.h" #include "Common\Managers\ArmyManager.h" #include "Common\Managers\ActionManager.h" #include "sc2api/sc2_api.h" #include "Common\GameState.h" #include <iostream> #include "sc2api/sc2_api.h" #include "sc2lib/sc2_lib.h" #include "sc2utils/sc2_manage_process.h" #include "sc2utils/sc2_arg_parser.h" #include "Common\Analyzers\ThreatAnalyzer.h" #include "Common\Strategy\Attacks\UnitMicro.h" #include "Common/Strategy/Building/ExpandStrategy.h" #include <chrono> #include <Common/Util/UtilConfig.h> using Clock = std::chrono::high_resolution_clock; using namespace sc2; #define LADDER_MODE 1 #define PLANNER_MODE 0 #define REALTIME 0 class PlanBotBase : public Agent { public: PlanBotBase(); void Init(); void OnGameStart(); void OnStep(); void virtual OnBuildingConstructionComplete(const Unit*) {}; void OnUnitCreated(const Unit *); void OnUnitEnterVision(const Unit *); void virtual OnUnitDestroyed(const Unit* unit); void virtual OnGameEnd() {}; void virtual OnError(const std::vector<sc2::ClientError> & client_errors, const std::vector<std::string> & protocol_errors); void DebugWriteInView(string message, Point2D relativePosition, DebugInterface* debug, const ObservationInterface* obs); bool Lost; bool errorOccurred = 0; protected: void ChooseActionFromGoals(vector<BaseAction*> goals, const sc2::ObservationInterface * obs, sc2::ActionInterface * actions, sc2::QueryInterface * query, string name, vector<string>* messages, bool withRetry, bool& stopOthers); bool virtual ShouldSurrender(const sc2::ObservationInterface * obs); void virtual DebugDrawState(chrono::time_point<chrono::steady_clock> startTime); void UpdateGameState(); void ManageScouts(); void virtual ChooseGoals(); void BalanceWorkerAssignments(); void DefendBase(); void CancelBuildingsUnderAttack(); void ManageUnits(); void CheckChat(); ActionManager* GetActionManager(); GoalPicker goalPicker; Planner planner; ArmyManager armyManager; GameState state; ActionManager* actionManager; vector<BaseAction*> EconomyGoals; vector<BaseAction*> BuildOrderGoals; vector<BaseAction*> ArmyGoals; vector<BaseAction*> TacticsGoals; vector<BaseAction*> UpgradeGoals; bool shouldRecalcuate; int StepCounter = 0; const int STEPS_PER_GOAL = 2; vector<string> debugMessages; ThreatAnalyzer threatAnalyzer; vector<UnitMicro*> microManagers; int goalCategory = 0; //Config Values map<string, string> Configs; bool DebugEnabled = 0; bool IsRealTime = 0; bool EnableChat = 0; bool EnableSurrender = 0; bool IgnoreSelected = 0; std::string TargetingType; };
31.05618
228
0.771346
[ "vector" ]
2e5642cc55d0e31fba407eafb5806cecdfe4794d
2,387
h
C
include/weather_app.h
dukhnovs/ECE590_final_project
41b648e77e36aaef74149379bd49a08ff04527aa
[ "MIT" ]
null
null
null
include/weather_app.h
dukhnovs/ECE590_final_project
41b648e77e36aaef74149379bd49a08ff04527aa
[ "MIT" ]
null
null
null
include/weather_app.h
dukhnovs/ECE590_final_project
41b648e77e36aaef74149379bd49a08ff04527aa
[ "MIT" ]
null
null
null
#ifndef _ELMA_STOP_WATCH_H #define _ELMA_STOP_WATCH_H #include "elma/elma.h" // Note installation directory for elma #include "min.h" #include "max.h" #include "user_interface.h" #include <vector> #include <string.h> namespace weather_app { using namespace std::chrono; using namespace elma; //! A stop watch class, that inherits from StateMachine class WeatherApp : public StateMachine { public: //! Make a new weather_app WeatherApp(); //! Start the weather_app // void begin(); //! Reset the weather_app to zero and erase laps void reset(); //! Stop the weather_app // void stop(); void seattle(); //! Add a lap time to the list of lap times. // void lap(); void london(); //! Get the time stored by the weather_app high_resolution_clock::duration value(); //! Get a list of lap times // const vector<high_resolution_clock::duration>& laps() { return _laps; } // //! Get a list of temperatures // inline vector<double> temp() { return _temp; } inline string city() { return _city; } inline int mode() { return _mode; } inline string temp_type() { return _temp_type; } inline bool responded() { return _responded; } double max_temp(); double min_temp(); double temp_result(); void set_temp(double temp); void get_api_data(string api_string); void set_max_min(); void set_city(string city); void set_mode(int mode); void set_temp_type(string temp_type); void set_responded(bool responded); private: vector<double> _temp; // vector of all temperatures from the json result of the api call double _temp_result; // min or max temp depending on user selection double _max; // max temp double _min; // min temp // When overriding the StateMachine class, put state declarations here. MinState min; MaxState max; // Other private variables bool _responded; int _mode; string _temp_type; string _city; // high_resolution_clock::time_point _start_time; // high_resolution_clock::duration _elapsed; // vector<high_resolution_clock::duration> _laps; }; } #endif
28.082353
96
0.615417
[ "vector" ]
2e5bda56ee4dcf11542224e2f49b32f44fb814f3
2,675
h
C
Aplicacion Movil/generated/bundles/login-transition/build/Android/Preview/app/src/main/include/Outracks.Simulator.Si-ca2693fb.h
marferfer/SpinOff-LoL
a9dba8ac9dd476ec1ef94712d9a8e76d3b45aca8
[ "Apache-2.0" ]
null
null
null
Aplicacion Movil/generated/bundles/login-transition/build/Android/Preview/app/src/main/include/Outracks.Simulator.Si-ca2693fb.h
marferfer/SpinOff-LoL
a9dba8ac9dd476ec1ef94712d9a8e76d3b45aca8
[ "Apache-2.0" ]
null
null
null
Aplicacion Movil/generated/bundles/login-transition/build/Android/Preview/app/src/main/include/Outracks.Simulator.Si-ca2693fb.h
marferfer/SpinOff-LoL
a9dba8ac9dd476ec1ef94712d9a8e76d3b45aca8
[ "Apache-2.0" ]
null
null
null
// This file was generated based on C:/Users/JuanJose/AppData/Local/Fusetools/Packages/Fuse.Preview.Core/0.1.0/SimulatorClient.uno. // WARNING: Changes might be lost if you edit this file directly. #pragma once #include <Outracks.Simulator.IS-5cd3f04c.h> #include <Uno.IDisposable.h> #include <Uno.Object.h> namespace g{namespace Outracks{namespace Simulator{struct ConcurrentQueue;}}} namespace g{namespace Outracks{namespace Simulator{struct SimulatorClient;}}} namespace g{namespace System{namespace IO{struct BinaryReader;}}} namespace g{namespace System{namespace IO{struct BinaryWriter;}}} namespace g{namespace Uno{namespace Net{namespace Sockets{struct NetworkStream;}}}} namespace g{namespace Uno{namespace Net{namespace Sockets{struct Socket;}}}} namespace g{namespace Uno{namespace Threading{struct Thread;}}} namespace g{ namespace Outracks{ namespace Simulator{ // public sealed class SimulatorClient :141 // { struct SimulatorClient_type : uType { ::g::Outracks::Simulator::ISimulatorClient interface0; ::g::Uno::IDisposable interface1; }; SimulatorClient_type* SimulatorClient_typeof(); void SimulatorClient__ctor__fn(SimulatorClient* __this, ::g::Uno::Net::Sockets::Socket* socket); void SimulatorClient__Dispose_fn(SimulatorClient* __this); void SimulatorClient__get_IncommingMessages_fn(SimulatorClient* __this, ::g::Outracks::Simulator::ConcurrentQueue** __retval); void SimulatorClient__get_IsOnline_fn(SimulatorClient* __this, bool* __retval); void SimulatorClient__New1_fn(::g::Uno::Net::Sockets::Socket* socket, SimulatorClient** __retval); void SimulatorClient__ReadLoop_fn(SimulatorClient* __this); void SimulatorClient__Send_fn(SimulatorClient* __this, uObject* message); void SimulatorClient__WriteLoop_fn(SimulatorClient* __this); struct SimulatorClient : uObject { uStrong< ::g::Uno::Net::Sockets::Socket*> _socket; uStrong< ::g::Uno::Net::Sockets::NetworkStream*> _stream; uStrong< ::g::System::IO::BinaryWriter*> _writer; uStrong< ::g::System::IO::BinaryReader*> _reader; uStrong< ::g::Outracks::Simulator::ConcurrentQueue*> _messagesFromClient; uStrong< ::g::Outracks::Simulator::ConcurrentQueue*> _messagesToClient; uStrong< ::g::Uno::Threading::Thread*> _readWorker; uStrong< ::g::Uno::Threading::Thread*> _writeWorker; bool _running; void ctor_(::g::Uno::Net::Sockets::Socket* socket); void Dispose(); ::g::Outracks::Simulator::ConcurrentQueue* IncommingMessages(); bool IsOnline(); void ReadLoop(); void Send(uObject* message); void WriteLoop(); static SimulatorClient* New1(::g::Uno::Net::Sockets::Socket* socket); }; // } }}} // ::g::Outracks::Simulator
43.145161
131
0.761121
[ "object" ]
446d873e4b0ddca49cbd71e5fc6e53c5a047de77
563
h
C
include/Components/Bird.h
sujairamprasathc/Flappy-Birds
dcf48d3caf4c49000a7f6d06297469594df2343c
[ "CC-BY-3.0" ]
null
null
null
include/Components/Bird.h
sujairamprasathc/Flappy-Birds
dcf48d3caf4c49000a7f6d06297469594df2343c
[ "CC-BY-3.0" ]
null
null
null
include/Components/Bird.h
sujairamprasathc/Flappy-Birds
dcf48d3caf4c49000a7f6d06297469594df2343c
[ "CC-BY-3.0" ]
null
null
null
#ifndef FLAPPY_BIRD_COMPONENTS_BIRD_H #define FLAPPY_BIRD_COMPONENTS_BIRD_H #include <utility> #include <vector> #include "Drawable.h" class Bird : public Drawable { using Vertex = std::pair<float, float>; using Vertices = std::vector<Vertex>; float verticalPosition; protected: virtual Vertices computeVertices() const; public: Bird(); void draw() const override; virtual Vertices getBoundingBox() const; virtual float getVerticalPosition() const; virtual void setVerticalPosition(float); }; #endif // FLAPPY_BIRD_COMPONENTS_BIRD_H
19.413793
44
0.758437
[ "vector" ]
449879aeee79e48942115947af6092be1bc7b793
5,553
h
C
src/app/qgscustomization.h
dyna-mis/Hilabeling
cb7d5d4be29624a20c8a367162dbc6fd779b2b52
[ "MIT" ]
null
null
null
src/app/qgscustomization.h
dyna-mis/Hilabeling
cb7d5d4be29624a20c8a367162dbc6fd779b2b52
[ "MIT" ]
null
null
null
src/app/qgscustomization.h
dyna-mis/Hilabeling
cb7d5d4be29624a20c8a367162dbc6fd779b2b52
[ "MIT" ]
1
2021-12-25T08:40:30.000Z
2021-12-25T08:40:30.000Z
/*************************************************************************** qgscustomization.h - Customization ------------------- begin : 2011-04-01 copyright : (C) 2011 Radim Blazek email : radim dot blazek at gmail dot com ***************************************************************************/ /*************************************************************************** * * * 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. * * * ***************************************************************************/ #ifndef QGSCUSTOMIZATION_H #define QGSCUSTOMIZATION_H #include "ui_qgscustomizationdialogbase.h" #include "qgshelp.h" #include <QDialog> #include <QDomNode> #include "qgis_app.h" class QString; class QWidget; class QTreeWidgetItem; class QEvent; class QMouseEvent; class QSettings; class APP_EXPORT QgsCustomizationDialog : public QMainWindow, private Ui::QgsCustomizationDialogBase { Q_OBJECT public: QgsCustomizationDialog( QWidget *parent, QSettings *settings ); // get item by path QTreeWidgetItem *item( const QString &path, QTreeWidgetItem *widgetItem = nullptr ); // // return current item state for given path bool itemChecked( const QString &path ); // set item state for given path void setItemChecked( const QString &path, bool on ); // recursively save tree item to settings void itemToSettings( const QString &path, QTreeWidgetItem *item, QSettings *settings ); // recursively save settings to tree items void settingsToItem( const QString &path, QTreeWidgetItem *item, QSettings *settings ); // save current tree to settings void treeToSettings( QSettings *settings ); // restore current tree from settings void settingsToTree( QSettings *settings ); // switch widget item in tree bool switchWidget( QWidget *widget, QMouseEvent *event ); // Get path of the widget QString widgetPath( QWidget *widget, const QString &path = QString() ); void setCatch( bool on ); bool catchOn(); private slots: //void on_btnQgisUser_clicked(); // Save to settings void ok(); void apply(); void cancel(); void showHelp(); // Reset values from settings void reset(); // Save to settings to file void actionSave_triggered( bool checked ); // Load settings from file void actionLoad_triggered( bool checked ); void actionExpandAll_triggered( bool checked ); void actionCollapseAll_triggered( bool checked ); void actionSelectAll_triggered( bool checked ); void mCustomizationEnabledCheckBox_toggled( bool checked ); private: void init(); QTreeWidgetItem *createTreeItemWidgets(); QTreeWidgetItem *readWidgetsXmlNode( const QDomNode &node ); QString mLastDirSettingsName; QSettings *mSettings = nullptr; }; class APP_EXPORT QgsCustomization : public QObject { Q_OBJECT public: enum Status { NotSet = 0, User = 1, // Set by user Default = 2 // Default customization loaded and set }; Q_ENUM( Status ) //! Returns the instance pointer, creating the object on the first call static QgsCustomization *instance(); void openDialog( QWidget *parent ); static void customizeWidget( QWidget *widget, QEvent *event, QSettings *settings ); static void customizeWidget( const QString &path, QWidget *widget, QSettings *settings ); static void removeFromLayout( QLayout *layout, QWidget *widget ); void updateMainWindow( QMenu *toolBarMenu ); // make sure to enable/disable before creating QgisApp in order to get it customized (or not) void setEnabled( bool enabled ) { mEnabled = enabled; } bool isEnabled() const { return mEnabled; } void setSettings( QSettings *settings ) { mSettings = settings ;} // Return the path to the splash screen QString splashPath() const; // Load and set default customization void loadDefault(); // Internal Qt widget which has to bes kipped in paths static QStringList sInternalWidgets; QString statusPath() const { return mStatusPath; } public slots: void preNotify( QObject *receiver, QEvent *event, bool *done ); protected: QgsCustomization(); ~QgsCustomization() override = default; QgsCustomizationDialog *pDialog = nullptr; bool mEnabled = false; QSettings *mSettings = nullptr; QString mStatusPath; void updateMenu( QMenu *menu, QSettings *settings ); void createTreeItemMenus(); void createTreeItemToolbars(); void createTreeItemDocks(); void createTreeItemStatus(); void addTreeItemMenu( QTreeWidgetItem *parentItem, const QMenu *menu, const QAction *action = nullptr ); void addTreeItemActions( QTreeWidgetItem *parentItem, const QList<QAction *> &actions ); QList<QTreeWidgetItem *> mMainWindowItems; friend class QgsCustomizationDialog; // in order to access mMainWindowItems private slots: private: static QgsCustomization *sInstance; }; #endif // QGSCUSTOMIZATION_H
31.551136
108
0.63029
[ "object" ]
44ae2c320470a044282d1c439eb030d006f187a2
3,526
h
C
ni_vision/src/ni/modules/ni/layers/surfacetracking.h
nigroup/ni_vision
6d32fbc8a511d55566a2778ebbd85a4dcf8a8098
[ "BSD-2-Clause" ]
3
2017-03-01T06:57:59.000Z
2019-02-11T03:57:43.000Z
ni_vision/src/ni/modules/ni/layers/surfacetracking.h
nigroup/ni_vision
6d32fbc8a511d55566a2778ebbd85a4dcf8a8098
[ "BSD-2-Clause" ]
null
null
null
ni_vision/src/ni/modules/ni/layers/surfacetracking.h
nigroup/ni_vision
6d32fbc8a511d55566a2778ebbd85a4dcf8a8098
[ "BSD-2-Clause" ]
null
null
null
#ifndef _NI_LAYERS_SURFACETRACKING_H_ #define _NI_LAYERS_SURFACETRACKING_H_ #include <vector> #include "elm/core/typedefs_fwd.h" #include "elm/core/pcl/typedefs_fwd.h" #include "elm/layers/layers_interim/base_matoutputlayer.h" #include "ni/core/surface.h" #include "ni/legacy/surfprop.h" #include "ni/legacy/trackprop.h" namespace ni { /** * @brief layer for tracking surfaces over time, * by assigning newly observed surfaces to surfaces stored * in short-term memory (STM) * @cite Mohr2014 * * Output keys defined by parent */ class SurfaceTracking : public elm::base_MatOutputLayer { public: // params static const std::string PARAM_HIST_BINS; ///< no. of bins in color histogram static const std::string PARAM_WEIGHT_COLOR; ///< color contribution static const std::string PARAM_WEIGHT_POS; ///< position contribution static const std::string PARAM_WEIGHT_SIZE; ///< size contribution static const std::string PARAM_MAX_COLOR; ///< upper threshold for similarly colored surfaces static const std::string PARAM_MAX_POS; ///< upper threshold for similarly positioned surfaces static const std::string PARAM_MAX_SIZE; ///< upper threshold for similarly sized surfaces static const std::string PARAM_MAX_DIST; ///< upper threshold for total feature distance // remaining I/O keys static const std::string KEY_INPUT_BGR_IMAGE; static const std::string KEY_INPUT_CLOUD; static const std::string KEY_INPUT_MAP; static const float DISTANCE_HUGE; virtual ~SurfaceTracking(); SurfaceTracking(); void Clear(); void Reset(const elm::LayerConfig &config); void Reconfigure(const elm::LayerConfig &config); void InputNames(const elm::LayerInputNames &io); void Activate(const elm::Signal &signal); protected: void extractFeatures(const elm::CloudXYZPtr &cloud, const cv::Mat &bgr, const cv::Mat1f &map, std::vector<Surface> &surfaces); void computeFeatureDistance(const std::vector<ni::Surface> &surfaces, const std::vector<ni::Surface> &mem); // members std::string input_name_bgr_; std::string input_name_cloud_; std::string input_name_map_; int nb_bins_; ///< no. of bins in color histogram float weight_color_; ///< weight for distance between color histograms features h float weight_pos_; ///< weight for distance between observed and tracked surface positions float weight_size_; ///< weight for size distance float max_color_; ///< upper threshold for similarly colored surfaces float max_pos_; ///< upper threshold for similarly positioned surfaces float max_size_; ///< upper threshold for similarly sized surfaces float max_dist_; ///< upper threshold for total feature distance cv::Mat1f dist_color_; ///< distance matrix for color features cv::Mat1f dist_pos_; ///< distance matrix for position cv::Mat1f dist_size_; ///< distance matrix for size cv::Mat1f dist_; ///< weighted sum of feature distance matrices std::vector<ni::Surface> obsereved_; std::vector<ni::Surface> memory_; // legacy members SurfProp stMems; int nMemsCnt; TrackProp stTrack; VecI vnMemsValidIdx; std::vector<elm::VecF > mnMemsRelPose; int framec; }; } // namespace ni #endif // _NI_LAYERS_SURFACETRACKING_H_
34.23301
106
0.685196
[ "vector" ]
44b391fdb17da8d63c21c111c5547c5fe5f60ffc
7,679
h
C
src/pan_tilt_forest/cvx_gl/gl_homg_point_2d.h
lood339/two_point_calib
b4b861429c92368e8e4accecc986272070fb19bc
[ "BSD-2-Clause" ]
45
2018-04-22T10:12:52.000Z
2022-03-15T07:35:07.000Z
src/boundle_adjustment/cvx_gl/gl_homg_point_2d.h
lood339/CalibMe
03c4f51e63b2ec0824d47fae6daeae8ef52040c7
[ "BSD-2-Clause" ]
6
2019-01-18T06:33:03.000Z
2020-10-02T06:11:14.000Z
src/boundle_adjustment/cvx_gl/gl_homg_point_2d.h
lood339/CalibMe
03c4f51e63b2ec0824d47fae6daeae8ef52040c7
[ "BSD-2-Clause" ]
8
2018-03-07T07:25:00.000Z
2022-03-15T06:16:42.000Z
#ifndef gl_homg_point_2d_h_ #define gl_homg_point_2d_h_ #include <cmath> namespace cvx_gl { //: Represents a homogeneous 2D point class homg_point_2d { // the data associated with this point double x_; double y_; double w_; public: // Constructors/Initializers/Destructor------------------------------------ //: Default constructor with (0,0,1) inline homg_point_2d() : x_(0), y_(0), w_(1.0) {} //: Construct from two (nonhomogeneous) or three (homogeneous) Types. inline homg_point_2d(double px, double py, double pw = 1.0) : x_(px), y_(py), w_(pw) {} // Data Access------------------------------------------------------------- inline double x() const { return x_; } inline double y() const { return y_; } inline double w() const { return w_; } //: Return true iff the point is at infinity (an ideal point). // The method checks whether |w| <= tol * max(|x|,|y|) inline bool ideal(double tol = 0.0) const { return std::fabs(w()) <= tol * std::fabs(x()) || std::fabs(w()) <= tol * std::fabs(y()); } }; } #endif /* // +-+-+ point_2d simple I/O +-+-+ //: Write "<vgl_homg_point_2d (x,y,w) >" to stream // \relatesalso vgl_homg_point_2d template <class T> vcl_ostream& operator<<(vcl_ostream& s, vgl_homg_point_2d<T> const& p); //: Read x y w from stream // \relatesalso vgl_homg_point_2d template <class T> vcl_istream& operator>>(vcl_istream& s, vgl_homg_point_2d<T>& p); // +-+-+ homg_point_2d arithmetic +-+-+ //: Return true iff the point is at infinity (an ideal point). // The method checks whether |w| <= tol * max(|x|,|y|) // \relatesalso vgl_homg_point_2d template <class T> inline bool is_ideal(vgl_homg_point_2d<T> const& p, T tol=(T)0){return p.ideal(tol);} //: The difference of two points is the vector from second to first point // This function is only valid if the points are not at infinity. // \relatesalso vgl_homg_point_2d template <class T> inline vgl_vector_2d<T> operator-(vgl_homg_point_2d<T> const& p1, vgl_homg_point_2d<T> const& p2) { assert(p1.w() && p2.w()); return vgl_vector_2d<T>(p1.x()/p1.w()-p2.x()/p2.w(), p1.y()/p1.w()-p2.y()/p2.w()); } //: Adding a vector to a point gives a new point at the end of that vector // If the point is at infinity, nothing happens. // Note that vector + point is not defined! It's always point + vector. // \relatesalso vgl_homg_point_2d template <class T> inline vgl_homg_point_2d<T> operator+(vgl_homg_point_2d<T> const& p, vgl_vector_2d<T> const& v) { return vgl_homg_point_2d<T>(p.x()+v.x()*p.w(), p.y()+v.y()*p.w(), p.w()); } //: Adding a vector to a point gives the point at the end of that vector // If the point is at infinity, nothing happens. // \relatesalso vgl_homg_point_2d template <class T> inline vgl_homg_point_2d<T>& operator+=(vgl_homg_point_2d<T>& p, vgl_vector_2d<T> const& v) { p.set(p.x()+v.x()*p.w(), p.y()+v.y()*p.w(), p.w()); return p; } //: Subtracting a vector from a point is the same as adding the inverse vector // \relatesalso vgl_homg_point_2d template <class T> inline vgl_homg_point_2d<T> operator-(vgl_homg_point_2d<T> const& p, vgl_vector_2d<T> const& v) { return p + (-v); } //: Subtracting a vector from a point is the same as adding the inverse vector // \relatesalso vgl_homg_point_2d template <class T> inline vgl_homg_point_2d<T>& operator-=(vgl_homg_point_2d<T>& p, vgl_vector_2d<T> const& v) { return p += (-v); } // +-+-+ homg_point_2d geometry +-+-+ //: cross ratio of four collinear points // This number is projectively invariant, and it is the coordinate of p4 // in the reference frame where p2 is the origin (coordinate 0), p3 is // the unity (coordinate 1) and p1 is the point at infinity. // This cross ratio is often denoted as ((p1, p2; p3, p4)) (which also // equals ((p3, p4; p1, p2)) or ((p2, p1; p4, p3)) or ((p4, p3; p2, p1)) ) // and is calculated as // \verbatim // p1 - p3 p2 - p3 (p1-p3)(p2-p4) // ------- : -------- = -------------- // p1 - p4 p2 - p4 (p1-p4)(p2-p3) // \endverbatim // If three of the given points coincide, the cross ratio is not defined. // // In this implementation, a least-squares result is calculated when the // points are not exactly collinear. // \relatesalso vgl_homg_point_2d // template <class T> double cross_ratio(vgl_homg_point_2d<T>const& p1, vgl_homg_point_2d<T>const& p2, vgl_homg_point_2d<T>const& p3, vgl_homg_point_2d<T>const& p4); //: Are three points collinear, i.e., do they lie on a common line? // \relatesalso vgl_homg_point_2d template <class T> inline bool collinear(vgl_homg_point_2d<T> const& p1, vgl_homg_point_2d<T> const& p2, vgl_homg_point_2d<T> const& p3) { return (p1.x()*p2.y()-p1.y()*p2.x())*p3.w() +(p3.x()*p1.y()-p3.y()*p1.x())*p2.w() +(p2.x()*p3.y()-p2.y()*p3.x())*p1.w()==0; } //: Return the relative distance to p1 wrt p1-p2 of p3. // The three points should be collinear and p2 should not equal p1. // This is the coordinate of p3 in the affine 1D reference frame (p1,p2). // If p3=p1, the ratio is 0; if p1=p3, the ratio is 1. // The mid point of p1 and p2 has ratio 0.5. // Note that the return type is double, not T, since the ratio of e.g. // two vgl_vector_2d<int> need not be an int. // \relatesalso vgl_homg_point_2d template <class T> inline double ratio(vgl_homg_point_2d<T> const& p1, vgl_homg_point_2d<T> const& p2, vgl_homg_point_2d<T> const& p3) { return (p3-p1)/(p2-p1); } //: Return the point at a given ratio wrt two other points. // By default, the mid point (ratio=0.5) is returned. // Note that the third argument is T, not double, so the midpoint of e.g. // two vgl_homg_point_2d<int> is not a valid concept. But the reflection point // of p2 wrt p1 is: in that case f=-1. template <class T> inline vgl_homg_point_2d<T> midpoint(vgl_homg_point_2d<T> const& p1, vgl_homg_point_2d<T> const& p2, T f = (T)0.5) { return p1 + f*(p2-p1); } //: Return the point at the centre of gravity of two given points. // Identical to midpoint(p1,p2). // Invalid when both points are at infinity. // If only one point is at infinity, that point is returned. // \relatesalso vgl_homg_point_2d template <class T> inline vgl_homg_point_2d<T> centre(vgl_homg_point_2d<T> const& p1, vgl_homg_point_2d<T> const& p2) { return vgl_homg_point_2d<T>(p1.x()*p2.w() + p2.x()*p1.w(), p1.y()*p2.w() + p2.y()*p1.w(), p1.w()*p2.w()*2 ); } //: Return the point at the centre of gravity of a set of given points. // There are no rounding errors when T is e.g. int, if all w() are 1. // \relatesalso vgl_homg_point_2d template <class T> inline vgl_homg_point_2d<T> centre(vcl_vector<vgl_homg_point_2d<T> > const& v) { int n=v.size(); assert(n>0); // it is *not* correct to return the point (0,0) when n==0. T x = 0, y = 0; for (int i=0; i<n; ++i) x+=v[i].x()/v[i].w(), y+=v[i].y()/v[i].w(); return vgl_homg_point_2d<T>(x,y,(T)n); } #define VGL_HOMG_POINT_2D_INSTANTIATE(T) extern "please include vgl/vgl_homg_point_2d.txx first" #endif // vgl_homg_point_2d_h_ */
37.458537
96
0.609715
[ "geometry", "vector" ]
44d780b0d109f05f64772aedef321b21b992552d
4,412
h
C
src/batterytech/src/batterytech/ui/Menu.h
puretekniq/batterytech
cc831b2835b7bf4826948831f0274e3d80921339
[ "MIT", "BSD-3-Clause-Clear", "Zlib", "BSD-3-Clause" ]
10
2015-04-07T22:23:31.000Z
2016-03-06T11:48:32.000Z
src/batterytech/src/batterytech/ui/Menu.h
robdoesstuff/batterytech
cc831b2835b7bf4826948831f0274e3d80921339
[ "MIT", "BSD-3-Clause-Clear", "Zlib", "BSD-3-Clause" ]
3
2015-05-17T10:45:48.000Z
2016-07-29T18:34:53.000Z
src/batterytech/src/batterytech/ui/Menu.h
puretekniq/batterytech
cc831b2835b7bf4826948831f0274e3d80921339
[ "MIT", "BSD-3-Clause-Clear", "Zlib", "BSD-3-Clause" ]
4
2015-05-03T03:00:48.000Z
2016-03-03T12:49:01.000Z
/* * BatteryTech * Copyright (c) 2010 Battery Powered Games LLC. * * This code is a component of BatteryTech and is subject to the 'BatteryTech * End User License Agreement'. Among other important provisions, this * license prohibits the distribution of source code to anyone other than * authorized parties. If you have any questions or would like an additional * copy of the license, please contact: support@batterypoweredgames.com */ //============================================================================ // Name : Menu.h // Description : Abstract class for creating menus. A menu is a collection of UIComponents, Layouts and programmed behavior. // Usage : Subclass to make a menu and add an instance of the subclass via UIManager::addMenu() //============================================================================ #ifndef MENU_H_ #define MENU_H_ #include "UIComponent.h" #include <batterytech/render/MenuRenderer.h> #include <batterytech/ui/UIManager.h> namespace BatteryTech { /** \brief A UI Menu * * Every menu has one root UIComponent of which all other UIComponents must be children or have parents that are children of. * * Only one menu at a time may be active (top of the menu stack) and menus may be pushed and popped off the stack. This works well for * simple systems but does have limitations for how much compositing of multiple menus the screen may have. It is recommended to use * shared layouts and components across different menus should the need for such complex UI systems arise. Another option is to instantiate * additional UIManagers for larger, more customized UIs that need to support multiple active menus. * * \ingroup UI * \class Menu */ class Menu { public: /** * Name constructor. Every menu must have a name. * The name is used in UIManager::showMenu(name) to push the menu onto the stack and display it. */ Menu(const char *name) { this->name = name; isFocused = FALSE; layoutRequested = FALSE; } /** * Name and root component constructor. * Every menu must have a name. * The name is used in UIManager::showMenu(name) to push the menu onto the stack and display it. * The root component is the base component of the hierarchy that will be rendered. */ Menu(const char *name, UIComponent *component) { this->name = name; this->rootComponent = component; isFocused = FALSE; layoutRequested = FALSE; } /** * Sets the root component of this menu * The root component is the base component of the hierarchy that will be rendered. */ virtual void setRootComponent(UIComponent *component) { this->rootComponent = component; } /** * Gets the root component of this menu */ virtual UIComponent* getRootComponent() { return rootComponent; } virtual ~Menu(); /** * Override to handle click down events for a component. * The component is a component in this menu's component hierarchy, starting at the root. */ virtual void onClickDown(UIComponent *component){}; /** * Override to handle click up events for a component. * The component is a component in this menu's component hierarchy, starting at the root. */ virtual void onClickUp(UIComponent *component){}; /** * Override to handle custom data passed before show * called if any data was passed from the invoking UIManager::showMenu call */ virtual void setData(void *data){}; /** * Override to perform any task before the menu is shown * called right before the menu is shown */ virtual void onPreShow(){}; /** * Call this to request that the menu (using root component) performs a new layout. * Useful if number of components or sizes have changed */ virtual void requestLayout() { layoutRequested = true; }; /** * Overide to handle special key presses */ virtual void onSpecialKey(SpecialKey sKey){}; /** * The menu's ID (used by UIManager) */ S32 menuId; /** * The menu's name (used to show menus by name) */ const char *name; /** * If the menu is currently focused */ BOOL32 isFocused; /** * If a layout has been requested */ BOOL32 layoutRequested; private: UIComponent *rootComponent; }; } #endif /* MENU_H_ */
34.740157
142
0.658658
[ "render" ]
44d84da16121c439ad61f23f927b8733933aa31d
2,866
h
C
TAO/tao/CSD_Framework/CSD_POA.h
cflowe/ACE
5ff60b41adbe1772372d1a43bcc1f2726ff8f810
[ "DOC" ]
36
2015-01-10T07:27:33.000Z
2022-03-07T03:32:08.000Z
TAO/tao/CSD_Framework/CSD_POA.h
cflowe/ACE
5ff60b41adbe1772372d1a43bcc1f2726ff8f810
[ "DOC" ]
2
2018-08-13T07:30:51.000Z
2019-02-25T03:04:31.000Z
TAO/tao/CSD_Framework/CSD_POA.h
cflowe/ACE
5ff60b41adbe1772372d1a43bcc1f2726ff8f810
[ "DOC" ]
38
2015-01-08T14:12:06.000Z
2022-01-19T08:33:00.000Z
// -*- C++ -*- //============================================================================= /** * @file CSD_POA.h * * $Id: CSD_POA.h 93359 2011-02-11 11:33:12Z mcorino $ * * @author Yan Dai (dai_y@ociweb.com) */ //============================================================================= #ifndef TAO_CSD_POA_H #define TAO_CSD_POA_H #include /**/ "ace/pre.h" #include "tao/CSD_Framework/CSD_FW_Export.h" #if !defined (ACE_LACKS_PRAGMA_ONCE) #pragma once #endif /* ACE_LACKS_PRAGMA_ONCE */ #include "tao/PortableServer/Regular_POA.h" #include "tao/CSD_Framework/CSD_Strategy_Proxy.h" TAO_BEGIN_VERSIONED_NAMESPACE_DECL /** * @class TAO_CSD_POA * * @brief Implementation of the CSD_Framework::POA interface. * * Implementation of the CSD_Framework::POA interface. */ class TAO_CSD_FW_Export TAO_CSD_POA : public virtual CSD_Framework::POA, public virtual TAO_Regular_POA { public: /// Constructor TAO_CSD_POA (const String &name, PortableServer::POAManager_ptr poa_manager, const TAO_POA_Policy_Set &policies, TAO_Root_POA *parent, ACE_Lock &lock, TAO_SYNCH_MUTEX &thread_lock, TAO_ORB_Core &orb_core, TAO_Object_Adapter *object_adapter); /// Destructor virtual ~TAO_CSD_POA (void); /// Pass the Strategy object reference to the CSD poa. virtual void set_csd_strategy (::CSD_Framework::Strategy_ptr s); /// Hook - The POA has been (or is being) activated. virtual void poa_activated_hook (); /// Hook - The POA has been deactivated. virtual void poa_deactivated_hook (); /// Hook - A servant has been activated. virtual void servant_activated_hook (PortableServer::Servant servant, const PortableServer::ObjectId& oid); /// Hook - A servant has been deactivated. virtual void servant_deactivated_hook (PortableServer::Servant servant, const PortableServer::ObjectId& oid); /// Method for creating new CSD POA. TAO_Root_POA * new_POA (const String &name, PortableServer::POAManager_ptr poa_manager, const TAO_POA_Policy_Set &policies, TAO_Root_POA *parent, ACE_Lock &lock, TAO_SYNCH_MUTEX &thread_lock, TAO_ORB_Core &orb_core, TAO_Object_Adapter *object_adapter); /// Servant Dispatching Strategy proxy accessor. TAO::CSD::Strategy_Proxy& servant_dispatching_strategy_proxy (void) const; private: TAO::CSD::Strategy_Proxy* sds_proxy_; }; TAO_END_VERSIONED_NAMESPACE_DECL #if defined (__ACE_INLINE__) # include "tao/CSD_Framework/CSD_POA.inl" #endif /* __ACE_INLINE__ */ #include /**/ "ace/post.h" #endif /* TAO_CSD_POA_H */
28.098039
79
0.617934
[ "object" ]
44e21d13d97b5f68624ea46cd07d6c176a61bdf0
1,371
h
C
src/patch.h
ion9/evegen
954dfef8831c7723ceff0d0b7bcedf19b56777ab
[ "MIT" ]
4
2020-02-18T02:37:32.000Z
2021-04-22T07:57:48.000Z
src/patch.h
ion9/evegen
954dfef8831c7723ceff0d0b7bcedf19b56777ab
[ "MIT" ]
1
2021-04-06T19:38:46.000Z
2021-04-18T19:45:02.000Z
src/patch.h
ion9/evegen
954dfef8831c7723ceff0d0b7bcedf19b56777ab
[ "MIT" ]
3
2020-02-18T02:52:39.000Z
2021-10-10T00:13:41.000Z
#ifndef __PATCH_H__ #define __PATCH_H__ #include <Python.h> #include <vector> #include <uchar.h> #define LIVEUPDATEMAGIC "$lu1" // Structure for passing patch info between calls struct Patch { uint32_t class_name_size; uint32_t method_name_size; uint32_t func_name_size; uint32_t type_size; uint32_t name_size; uint32_t desc_size; uint32_t bytecode_size; char *class_name; char *method_name; char *func_name; char *type; char *name; char *desc; char *data; char *bytecode; }; struct PatchFile { char magic[4]; uint32_t patch_count; Patch *patches; }; // LoadPatches will load all patches from a given directory std::vector<Patch *> LoadPatches(const char *patch_dir); enum PatchError_ { __patch_null, patch_ok, patch_invalid_magic, patch_file_too_small, patch_file_error, }; struct PatchError { uint32_t line; PatchError_ err; }; #define MAKE_PATCH_ERROR(__error) { \ PatchError e; \ e.line = __LINE__; \ e.err = __error; \ return e; \ } const char *PatchErrorString(PatchError p); PatchError DumpRawPatchFile(std::vector<Patch *> patches, const char *filename); PatchError LoadRawPatchFile(PatchFile *pf, const char *filename); #endif
21.092308
80
0.645514
[ "vector" ]
44ea58f9cc5963ea6e5b49a6dcf56ae2780fcba5
6,027
c
C
src/memgraph/main.c
turbio/evaldb
9d4aa5336b92f2957027e88cbb84db055e83cd29
[ "MIT" ]
12
2019-12-13T18:44:38.000Z
2021-03-03T16:26:51.000Z
src/memgraph/main.c
turbio/evaldb
9d4aa5336b92f2957027e88cbb84db055e83cd29
[ "MIT" ]
null
null
null
src/memgraph/main.c
turbio/evaldb
9d4aa5336b92f2957027e88cbb84db055e83cd29
[ "MIT" ]
null
null
null
#include <errno.h> #include <fcntl.h> #include <malloc.h> #include <sched.h> #include <signal.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #include <sys/mman.h> #include <sys/stat.h> #include <sys/types.h> #include <sys/wait.h> #include <unistd.h> #include <sys/personality.h> #include "../alloc.h" #include "./cmdline.h" int n = 0; static struct gengetopt_args_info args; void print_node_connection(void *from, void *to); void print_segment(struct snap_segment *s) { printf("\"%p\" ", (void *)s); printf("["); if (args.labels_flag) { printf(" label=\"%p\\nsize: %lu\"", (void *)s, (unsigned long)s->size); printf(" tooltip=\"%p\\nsize: %lu\"", (void *)s, (unsigned long)s->size); } else { printf(" label=\"\""); } printf(" width=.1"); printf(" height=.1"); printf(" style=filled"); printf(" fontsize=9"); printf(" shape=box"); printf(" penwidth=.5"); if (s->used) { printf(" fillcolor=\"#eeeeee\""); } else { printf(" fillcolor=\"#888888\""); } printf("]\n"); n++; } void print_node(struct snap_node *n) { printf("\"%p\" ", (void *)n); printf("["); if (n->type == SNAP_NODE_GENERATION) { struct snap_generation *g = (struct snap_generation *)n; printf(" label=\"%p\\ngen: %d\"", (void *)n, g->gen); printf(" tooltip=\"%p\\ngen: %d\"", (void *)n, g->gen); printf(" fillcolor=\"#aaaaff\""); } else if (n->type == SNAP_NODE_PAGE) { struct snap_page *p = (struct snap_page *)n; printf( " tooltip=\"%p\\nlen: %d\\npages: %d\"", (void *)n, p->len, p->pages); if (p->real_addr == p) { printf( " label=\"%p\\nlen: %d\\npages: %d\"", (void *)p->real_addr, p->len, p->pages); printf(" fillcolor=\"#88ff88\""); } else { printf( " label=\"%p\\nat %p\\nlen: %d\\npages: %d\"", (void *)p->real_addr, (void *)p, p->len, p->pages); printf(" fillcolor=\"#ffff88\""); } } else { printf(" label=\"%p\\nUNKNOWN\"", (void *)n); printf(" tooltip=\"%p\\nUNKNOWN\"", (void *)n); printf(" fillcolor=\"#888888\""); } if (!args.labels_flag) { printf(" label=\"\""); } printf(" width=.1"); printf(" height=.1"); printf(" style=filled"); printf(" fontsize=9"); printf(" shape=box"); printf(" penwidth=.5"); if (n->committed) { printf(" color=\"#888888\""); } else { printf(" color=\"#ff0000\""); } printf("]\n"); } void print_node_connection(void *from, void *to) { printf("\"%p\" -> \"%p\" ", from, to); printf("[arrowsize=.25]\n"); } void print_tree_nodes(struct snap_node *n) { print_node(n); if (n->type == SNAP_NODE_GENERATION) { struct snap_generation *g = (struct snap_generation *)n; for (int i = 0; i < GENERATION_CHILDREN; i++) { if (!g->c[i]) { continue; } print_node_connection(g, g->c[i]); print_tree_nodes(g->c[i]); } } else if (n->type == SNAP_NODE_PAGE) { if (args.segments_flag) { struct snap_page *p = (struct snap_page *)n; for (int i = 0; i < p->len; i++) { print_node_connection(p, p->c[i]); print_segment(p->c[i]); } } } else { printf("unknown node type %d at %p", n->type, (void *)n); exit(1); } } void *find_next_with_raddr(struct snap_generation *g, void *addr, int after) { for (int i = 0; i < GENERATION_CHILDREN; i++) { if (!g->c[i]) { continue; } struct snap_node *n2 = g->c[i]; if (n2->type == SNAP_NODE_PAGE) { struct snap_page *p = (struct snap_page *)n2; if (p->real_addr == addr && g->gen > after) { return p; } continue; } else if (n2->type == SNAP_NODE_GENERATION) { void *a = find_next_with_raddr((struct snap_generation *)n2, addr, after); if (a) { return a; } } } return NULL; } void print_node_history( struct snap_generation *root, struct snap_generation *g) { for (int i = 0; i < GENERATION_CHILDREN; i++) { if (!g->c[i]) { continue; } struct snap_node *n = g->c[i]; if (n->type == SNAP_NODE_PAGE) { struct snap_page *p = (struct snap_page *)n; if (p->real_addr != p) { printf( "\"%p\" -> \"%p\" ", (void *)p, find_next_with_raddr(root, p->real_addr, g->gen)); printf("[arrowsize=.25 color=\"#888888\"]\n"); } } else if (n->type == SNAP_NODE_GENERATION) { struct snap_generation *g = (struct snap_generation *)n; print_node_history(root, g); } } } void render_tree(struct heap_header *heap) { printf("nodesep=0.0\n"); printf("ranksep=0.1\n"); /*printf("overlap=false\n");*/ printf("\"committed\" [shape=box fontsize=9 width=.1 height=.1]\n"); printf("\"working\" [shape=box fontsize=9 width=.1 height=.1]\n"); printf("\"root\" [shape=box fontsize=9 width=.1 height=.1]\n"); printf("\"committed\" -> \"%p\" [arrowsize=.25]\n", (void *)heap->committed); printf("\"working\" -> \"%p\" [arrowsize=.25]\n", (void *)heap->working); printf("\"root\" -> \"%p\" [arrowsize=.25]\n", (void *)heap->root); print_tree_nodes((struct snap_node *)heap->root); if (args.history_flag) { print_node_history(heap->root, heap->root); } } int main(int argc, char *argv[]) { int pers = personality(0xffffffff); if (pers == -1) { fprintf(stderr, "could not get personality %s\n", strerror(errno)); exit(1); } if (!(pers & ADDR_NO_RANDOMIZE)) { if (personality(ADDR_NO_RANDOMIZE) == -1) { fprintf(stderr, "could not set personality %s\n", strerror(errno)); exit(1); } execve("/proc/self/exe", argv, NULL); } cmdline_parser(argc, argv, &args); struct heap_header *heap = snap_init(args.db_arg); if (heap->v != 0xffca) { printf("got a bad heap! %d != %d (expected)", heap->v, 0xffca); exit(1); } printf("digraph \"memory\" {\n"); printf("rankdir=LR\n"); render_tree(heap); printf("}\n"); return 0; }
25.323529
80
0.5555
[ "shape" ]
44f0878432a3584de138073a5c7dbc287ea5f1e3
891
h
C
test/shared_test/lib_time_test.h
pvyield/ssc
cfed15c922c5d76a576ac89dcbe91623090c737b
[ "MIT" ]
3
2017-09-04T12:19:13.000Z
2017-09-12T15:44:38.000Z
test/shared_test/lib_time_test.h
pvyield/ssc
cfed15c922c5d76a576ac89dcbe91623090c737b
[ "MIT" ]
1
2018-03-26T06:50:20.000Z
2018-03-26T06:50:20.000Z
test/shared_test/lib_time_test.h
pvyield/ssc
cfed15c922c5d76a576ac89dcbe91623090c737b
[ "MIT" ]
2
2018-02-12T22:23:55.000Z
2018-08-23T07:32:54.000Z
#ifndef __LIB_TIME_TEST_H__ #define __LIB_TIME_TEST_H__ #include "lib_util.h" #include <gtest/gtest.h> #include <vector> class libTimeTests : public ::testing::Test { protected: bool is_lifetime; size_t n_years; std::vector<float> lifetime60min; std::vector<float> lifetime30min; std::vector<float> singleyear60min; void SetUp() { is_lifetime = true; n_years = 25; lifetime60min.reserve(n_years * util::hours_per_year); for (size_t i = 0; i < n_years * util::hours_per_year; i++) { lifetime60min.push_back(100); } singleyear60min.reserve(util::hours_per_year); for (size_t i = 0; i < util::hours_per_year; i++) { singleyear60min.push_back(50); } lifetime30min.reserve(2 * n_years * util::hours_per_year); for (size_t i = 0; i < n_years * 2 * util::hours_per_year; i++) { lifetime30min.push_back(100); } } }; #endif // !__LIB_TIME_TEST_H__
20.72093
67
0.699214
[ "vector" ]
44f9b89e6bd2bdd9e510f400587fb0212b475c1d
3,169
h
C
TLOTCD/j1EntityFactory.h
thedoctormarc/Design_MiniGame_TLOTCD
daac115fcb7456fc2a6b4ac6ae3513bd10d6d722
[ "MIT" ]
null
null
null
TLOTCD/j1EntityFactory.h
thedoctormarc/Design_MiniGame_TLOTCD
daac115fcb7456fc2a6b4ac6ae3513bd10d6d722
[ "MIT" ]
null
null
null
TLOTCD/j1EntityFactory.h
thedoctormarc/Design_MiniGame_TLOTCD
daac115fcb7456fc2a6b4ac6ae3513bd10d6d722
[ "MIT" ]
null
null
null
#ifndef __J1ENTITYFACTORY_H__ #define __J1ENTITYFACTORY_H__ #include "j1Module.h" #include "SDL/include/SDL.h" #include <vector> #include <list> #include "Color.h" #include <map> #include <array> #include "p2Point.h" #include "Character.h" #include <random> #include "j1Fonts.h" #define RECHARGE 3 class RNG; class j1EntityFactory : public j1Module { public: j1EntityFactory(); ~j1EntityFactory(); bool Awake(pugi::xml_node& node); bool Start(); bool PreUpdate(); bool Update(float dt); bool PostUpdate(); bool CleanUp() { for (auto& c : characters) { c->CleanUp(); RELEASE(c); } characters.clear(); for (auto& c : actionHelpers) RELEASE(c); actionHelpers.clear(); for (auto& c : defenseHelpers) RELEASE(c); defenseHelpers.clear(); for (auto& c : AIHelpers) RELEASE(c); AIHelpers.clear(); for (auto& c : AIHelpersEmemy) RELEASE(c); AIHelpersEmemy.clear(); for (auto& c : allyCharacters) RELEASE(c); allyCharacters.clear(); for (auto& c : enemyCharacters) RELEASE(c); enemyCharacters.clear(); RELEASE(dmgLabel); RELEASE(rng); return true; }; bool hasIntersectionRectAndLine(const SDL_Rect* rect, std::array<int, 4> line) const // line is passed like this: {x1, y1, x2, y2} { return SDL_IntersectRectAndLine(rect, &line[0], &line[1], &line[2], &line[3]); } bool isPointInsideRect(const iPoint* p, const SDL_Rect* r) const { const SDL_Point P = { p->x, p->y }; return SDL_PointInRect(&P, r); } void CheckBothCompleted() { uint success = 0; Character* lastAttacker = nullptr; Character* lastDefender = nullptr; for (auto& c : characters) { if (c->active && c->actionCompleted) { if (c->attackTurn) lastAttacker = c; else lastDefender = c; success++; } if (success == 2) break; } if (success == 2) { SwitchTurn(lastAttacker, lastDefender); } } void SwitchTurn(Character* lastAttacker, Character* lastDefender); void ToggleAIModes(bool ally, bool enemy, Character* allyC, Character* enemyC); void ToggleUIVisibility(bool ally, bool enemy, Character* allyC, Character* enemyC); void ToggleBattleMode(Character* targetEnemy = nullptr); void Death(Character* dead, Character* targetEnemy = nullptr); void ResetAIHelperColors(bool ally, bool enemy); void InvincibleEnemyMode(); public: bool AIvsAI = false; float popUpCurrentTime = 0.f; float popUpTime = 2.f; float popUpWinCurrentTime = 0.f; float popUpWinTime = 2.f; unsigned int currentAttack = 0; UiItem_Label* dmgLabel = nullptr; RNG* rng = nullptr; std::vector<Character*> characters; std::vector<Character*> allyCharacters; std::vector<Character*> enemyCharacters; std::vector<UiItem_Image*> actionHelpers; std::vector<UiItem_Image*> defenseHelpers; std::vector<UiItem_Label*> AIHelpers; // attack and defence labels std::vector<UiItem_Label*> AIHelpersEmemy; // attack and defence labels UiItem_Image* topRight = nullptr; UiItem_Image* bottomLeft = nullptr; UiItem_Label* allyName = nullptr; UiItem_Label* enemyName = nullptr; UiItem_Label* winner = nullptr; }; #endif
21.126667
132
0.686021
[ "vector" ]
6d0650a12b511870562faf26186c01296b339f7f
4,501
h
C
stage5/02-installqtlibs/qt5.15/include/QtQuickParticles/5.15.1/QtQuickParticles/private/qquickparticleflatset_p.h
damir1996iz/tabletos
bfc2f650e3291ce63f083bcf36e81392341fbc40
[ "BSD-3-Clause" ]
null
null
null
stage5/02-installqtlibs/qt5.15/include/QtQuickParticles/5.15.1/QtQuickParticles/private/qquickparticleflatset_p.h
damir1996iz/tabletos
bfc2f650e3291ce63f083bcf36e81392341fbc40
[ "BSD-3-Clause" ]
null
null
null
stage5/02-installqtlibs/qt5.15/include/QtQuickParticles/5.15.1/QtQuickParticles/private/qquickparticleflatset_p.h
damir1996iz/tabletos
bfc2f650e3291ce63f083bcf36e81392341fbc40
[ "BSD-3-Clause" ]
null
null
null
/**************************************************************************** ** ** Copyright (C) 2020 Klarälvdalens Datakonsult AB, a KDAB Group company, info@kdab.com, author Giuseppe D'Angelo <giuseppe.dangelo@kdab.com> ** Contact: https://www.qt.io/licensing/ ** ** This file is part of the QtQuick module of the Qt Toolkit. ** ** $QT_BEGIN_LICENSE:LGPL$ ** 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 https://www.qt.io/terms-conditions. For further ** information use the contact form at https://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 3 as published by the Free Software ** Foundation and appearing in the file LICENSE.LGPL3 included in the ** packaging of this file. Please review the following information to ** ensure the GNU Lesser General Public License version 3 requirements ** will be met: https://www.gnu.org/licenses/lgpl-3.0.html. ** ** GNU General Public License Usage ** Alternatively, this file may be used under the terms of the GNU ** General Public License version 2.0 or (at your option) the GNU General ** Public license version 3 or any later version approved by the KDE Free ** Qt Foundation. The licenses are as published by the Free Software ** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3 ** included in the packaging of this file. Please review the following ** information to ensure the GNU General Public License requirements will ** be met: https://www.gnu.org/licenses/gpl-2.0.html and ** https://www.gnu.org/licenses/gpl-3.0.html. ** ** $QT_END_LICENSE$ ** ****************************************************************************/ #ifndef QQUICKPARTICLEFLATSET_P_H #define QQUICKPARTICLEFLATSET_P_H // // W A R N I N G // ------------- // // This file is not part of the Qt API. It exists purely as an // implementation detail. This header file may change from version to // version without notice, or even be removed. // // We mean it. // #include <QtGlobal> #include <vector> #include <algorithm> #include <iterator> QT_BEGIN_NAMESPACE // Minimal API, just for the consumption of Qt Quick Particles. // For extra safety, it's in a private namespace namespace QtQuickParticlesPrivate { template <typename T> class QFlatSet { public: using iterator = typename std::vector<T>::iterator; using const_iterator = typename std::vector<T>::const_iterator; using value_type = typename std::vector<T>::value_type; using size_type = int; iterator find(const T &t) { return std::find(begin(), end(), t); } const_iterator find(const T &t) const { return std::find(begin(), end(), t); } bool contains(const T &t) const { return find(t) != end(); } void clear() { m_data.clear(); } void reserve(int capacity) { m_data.reserve(capacity); } iterator insert(const T &t) { auto i = find(t); if (i != end()) return i; T copy = t; m_data.push_back(std::move(copy)); return std::prev(m_data.end()); } iterator insert(T &&t) { auto i = find(t); if (i != end()) return i; m_data.push_back(std::move(t)); return std::prev(m_data.end()); } size_type remove(const T &t) { auto i = std::find(m_data.begin(), m_data.end(), t); if (i != m_data.end()) { m_data.erase(i); return 1; } return 0; } iterator operator<<(const T &t) { return insert(t); } iterator operator<<(T &&t) { return insert(std::move(t)); } iterator begin() { return m_data.begin(); } const_iterator begin() const { return m_data.begin(); } const_iterator cbegin() const { return m_data.cbegin(); } iterator end() { return m_data.end(); } const_iterator end() const { return m_data.end(); } const_iterator cend() const { return m_data.cend(); } private: std::vector<T> m_data; }; } // namespace QtQuickParticlesPrivate QT_END_NAMESPACE #endif // QQUICKPARTICLEFLATSET_P_H
28.66879
141
0.639413
[ "vector" ]
6d1f8f5ffada8bd49095d6f3a17b7a4f2492dfbd
1,437
h
C
src/Player.h
CharlesEngel/Dodgin-Boxes
27bc93938645dab0366b1404d43e09a447a2f198
[ "MIT" ]
null
null
null
src/Player.h
CharlesEngel/Dodgin-Boxes
27bc93938645dab0366b1404d43e09a447a2f198
[ "MIT" ]
null
null
null
src/Player.h
CharlesEngel/Dodgin-Boxes
27bc93938645dab0366b1404d43e09a447a2f198
[ "MIT" ]
null
null
null
#pragma once #include "Renderer/Renderer.h" #include "GameObject.h" #include <glm/mat4x4.hpp> #include "SoundManager.h" #include "GameManager.h" struct PlayerUniform { glm::mat4 model; glm::mat4 view; glm::mat4 proj; int light_index; }; enum PlayerState { PLAYER_DEFAULT = 0, PLAYER_DASHING = 1, PLAYER_DYING = 2, PLAYER_DEAD = 3 }; class Player : public GameObject { public: Player(Renderer *renderer, Input *input, bool *game_end_flag); virtual ~Player(); virtual void update(double time); virtual std::vector<Rectangle *> get_collider(); virtual void submit_for_rendering(glm::mat4 view, glm::mat4 proj, float width, float height) const; virtual void handle_external_collisions(const Rectangle *collider, const GameObject *other); virtual void pause(); virtual void unpause(); glm::vec2 location; private: Renderer *renderer; std::string instance; std::string uniform_buffer; uint8_t light; glm::vec2 light_location; glm::mat4 scale; Rectangle collider; const Input *input; bool *game_end; const float speed = 1.2f; const float dash_speed = 3.8f; const float total_dash_time = 0.10f; const float total_death_time = 0.3f; const float scale_factor = 0.3f; glm::vec2 dash_direction; float current_dash_time; float current_death_time; PlayerState state; size_t dash_sound; bool resume_dash; size_t death_sound; bool resume_death; SoundManager *sound_manager; bool input_w_released; };
20.239437
100
0.751566
[ "vector", "model" ]
6d1fe981677c9fcd0e79d568ac1ce65e7fc5c34a
5,184
h
C
algorithms/kernel/svm/svm_train_kernel.h
zjf2012/daal
1d53cb3d71fb8f49fc7d79e50ca3c503c40a2b04
[ "Apache-2.0" ]
null
null
null
algorithms/kernel/svm/svm_train_kernel.h
zjf2012/daal
1d53cb3d71fb8f49fc7d79e50ca3c503c40a2b04
[ "Apache-2.0" ]
null
null
null
algorithms/kernel/svm/svm_train_kernel.h
zjf2012/daal
1d53cb3d71fb8f49fc7d79e50ca3c503c40a2b04
[ "Apache-2.0" ]
1
2018-11-09T15:59:50.000Z
2018-11-09T15:59:50.000Z
/* file: svm_train_kernel.h */ /******************************************************************************* * Copyright 2014-2019 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. *******************************************************************************/ /* //++ // Declaration of template structs that calculate SVM Training functions. //-- */ #ifndef __SVM_TRAIN_KERNEL_H__ #define __SVM_TRAIN_KERNEL_H__ #include "numeric_table.h" #include "model.h" #include "daal_defines.h" #include "svm_train_types.h" #include "kernel.h" #include "service_numeric_table.h" using namespace daal::data_management; using namespace daal::internal; using namespace daal::services; #include "svm_train_boser_cache.i" namespace daal { namespace algorithms { namespace svm { namespace training { namespace internal { enum SVMVectorStatus { free = 0x0, up = 0x1, low = 0x2, shrink = 0x4 }; template <typename algorithmFPType, typename ParameterType, CpuType cpu> struct SVMTrainTask { static const size_t kernelFunctionBlockSize = 1024; /* Size of the block of kernel function elements */ SVMTrainTask(size_t nVectors) : _cache(nullptr), _nVectors(nVectors){} Status setup(const ParameterType& svmPar, const NumericTablePtr& xTable, NumericTable& yTable); /* Perform Sequential Minimum Optimization (SMO) algorithm to find optimal coefficients alpha */ Status compute(const ParameterType& svmPar); /* Write support vectors and classification coefficients into model */ Status setResultsToModel(const NumericTable& xTable, Model& model, algorithmFPType C) const; ~SVMTrainTask(); protected: Status init(algorithmFPType C); inline void updateI(algorithmFPType C, size_t index); bool findMaximumViolatingPair(size_t nActiveVectors, algorithmFPType tau, int& Bi, int& Bj, algorithmFPType& delta, algorithmFPType& ma, algorithmFPType& Ma, algorithmFPType& curEps, Status& s) const; Status reconstructGradient(size_t& nActiveVectors); algorithmFPType WSSi(size_t nActiveVectors, int& Bi) const; void WSSjLocalBaseline(const size_t jStart, const size_t jEnd, const algorithmFPType *KiBlock, const algorithmFPType GMax, const algorithmFPType Kii, const algorithmFPType tau, int &Bj, algorithmFPType &GMin, algorithmFPType &GMin2, algorithmFPType &delta) const; void WSSjLocal(const size_t jStart, const size_t jEnd, const algorithmFPType *KiBlock, const algorithmFPType GMax, const algorithmFPType Kii, const algorithmFPType tau, int &Bj, algorithmFPType &GMin, algorithmFPType &GMin2, algorithmFPType &delta) const; Status WSSj(size_t nActiveVectors, algorithmFPType tau, int Bi, algorithmFPType GMax, int& Bj, algorithmFPType& delta, algorithmFPType& res) const; Status update(size_t nActiveVectors, algorithmFPType C, int Bi, int Bj, algorithmFPType delta); size_t updateShrinkingFlags(size_t nActiveVectors, algorithmFPType C, algorithmFPType ma, algorithmFPType Ma); /*** Methods used in shrinking ***/ size_t doShrink(size_t nActiveVectors); /** * \brief Write support vectors and classification coefficients into output model */ Status setSVCoefficients(size_t nSV, Model& model) const; Status setSVIndices(size_t nSV, Model& model) const; Status setSV_Dense(Model& model, const NumericTable& xTable, size_t nSV) const; Status setSV_CSR(Model& model, const NumericTable& xTable, size_t nSV) const; algorithmFPType calculateBias(algorithmFPType C) const; inline void updateAlpha(algorithmFPType C, int Bi, int Bj, algorithmFPType delta, algorithmFPType& newDeltai, algorithmFPType& newDeltaj); protected: const size_t _nVectors; //Number of observations in the input data set TArray<algorithmFPType, cpu> _y; //Array of class labels TArray<algorithmFPType, cpu> _alpha; //Array of classification coefficients TArray<algorithmFPType, cpu> _grad; //Objective function gradient TArray<algorithmFPType, cpu> _kernelDiag; //diagonal elements of the matrix Q (kernel(x[i], x[i])) TArray<char, cpu> _I; // array of flags I_LOW and I_UP SVMCacheIface<algorithmFPType, cpu> *_cache; //caches matrix Q (kernel(x[i], x[j])) values }; template <Method method, typename algorithmFPType, typename ParameterType, CpuType cpu> struct SVMTrainImpl : public Kernel { services::Status compute(const NumericTablePtr& xTable, NumericTable& yTable, daal::algorithms::Model *r, const ParameterType *par); }; } // namespace internal } // namespace training } // namespace svm } // namespace algorithms } // namespace daal #endif
35.506849
121
0.72608
[ "model" ]
6d251f84c0dcb0e4a1164346de663000f005b412
465
h
C
Vic2ToHoI4/Source/HOI4World/Map/SupplyArea.h
gawquon/Vic2ToHoI4
8371cfb1fd57cf81d854077963135d8037e754eb
[ "MIT" ]
25
2018-12-10T03:41:49.000Z
2021-10-04T10:42:36.000Z
Vic2ToHoI4/Source/HOI4World/Map/SupplyArea.h
gawquon/Vic2ToHoI4
8371cfb1fd57cf81d854077963135d8037e754eb
[ "MIT" ]
739
2018-12-13T02:01:20.000Z
2022-03-28T02:57:13.000Z
Vic2ToHoI4/Source/HOI4World/Map/SupplyArea.h
Osariusz/Vic2ToHoI4
9738b52c7602b1fe187c3820660c58a8d010d87e
[ "MIT" ]
43
2018-12-10T03:41:58.000Z
2022-03-22T23:55:41.000Z
#ifndef SUPPLY_AREA #define SUPPLY_AREA #include "Parser.h" namespace HoI4 { class SupplyArea: commonItems::parser { public: explicit SupplyArea(std::istream& theStream); [[nodiscard]] auto getID() const { return ID; } [[nodiscard]] auto getValue() const { return value; } [[nodiscard]] const auto& getStates() const { return states; } private: int ID = 0; int value = 0; std::vector<int> states; }; } // namespace HoI4 #endif // SUPPLY_AREA
14.53125
63
0.68172
[ "vector" ]
6d3d709edc5270d5a97f64be1a13689dda59b4f7
3,275
h
C
carrotslam/nodes/include/nodes/orbslam_optimizer.h
mocibb/CarrotSLAM
5c54957c2c2af18c0ad68bcd09a8a5534edc3832
[ "MIT" ]
28
2015-09-24T06:31:33.000Z
2022-03-15T07:35:45.000Z
carrotslam/nodes/include/nodes/orbslam_optimizer.h
ayumizll/CarrotSLAM
5c54957c2c2af18c0ad68bcd09a8a5534edc3832
[ "MIT" ]
1
2015-10-23T08:47:45.000Z
2015-10-23T08:47:45.000Z
carrotslam/nodes/include/nodes/orbslam_optimizer.h
ayumizll/CarrotSLAM
5c54957c2c2af18c0ad68bcd09a8a5534edc3832
[ "MIT" ]
37
2015-09-24T06:31:34.000Z
2021-04-15T20:34:21.000Z
/*! * Author: mocibb mocibb@163.com * Group: CarrotSLAM https://github.com/mocibb/CarrotSLAM * Name: orbslam_optimizer.h * Date: 2015.10.04 * Func: ORB-SLAM tracking * * * The MIT License (MIT) * Copyright (c) 2015 CarrotSLAM Group * 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 <vector> #include <set> #include "core/carrot_slam.h" #include "types/frame.h" #include "types/feature.h" #include "types/map.h" #include "types/point.h" #ifndef NODES_ORBSLAM_OPTIMIZER_H_ #define NODES_ORBSLAM_OPTIMIZER_H_ using namespace std; using namespace Eigen; namespace g2o { class EdgeSE3ProjectXYZ : public BaseBinaryEdge<2, Vector2d, VertexSBAPointXYZ, VertexSE3Expmap> { public: EIGEN_MAKE_ALIGNED_OPERATOR_NEW EdgeSE3ProjectXYZ(); bool read(std::istream& is); bool write(std::ostream& os) const; void computeError() { const VertexSE3Expmap* v1 = static_cast<const VertexSE3Expmap*>(_vertices[1]); const VertexSBAPointXYZ* v2 = static_cast<const VertexSBAPointXYZ*>(_vertices[0]); Vector2d obs(_measurement); _error = obs - cam_project(v1->estimate().map(v2->estimate())); } bool isDepthPositive() { const VertexSE3Expmap* v1 = static_cast<const VertexSE3Expmap*>(_vertices[1]); const VertexSBAPointXYZ* v2 = static_cast<const VertexSBAPointXYZ*>(_vertices[0]); return (v1->estimate().map(v2->estimate()))(2) > 0.0; } virtual void linearizeOplus(); Vector2d cam_project(const Vector3d & trans_xyz) const; double fx, fy, cx, cy; }; } // namespace g2o namespace carrotslam { namespace orbslam { struct XYZ2UV { Eigen::Vector3f pos; Eigen::Vector2f px; float inv_sigma2; bool is_deleted; FeaturePtr current; FeaturePtr previous; XYZ2UV(const FeaturePtr& feat) { pos = feat->point->pos; px = feat->px; inv_sigma2 = Feature::inv_level_sigma2[feat->level]; is_deleted = false; current = nullptr; previous = nullptr; } }; typedef std::shared_ptr<XYZ2UV> XYZ2UVPtr; //should change method with more specific name??? int poseOptimization(const CameraPtr& cam, std::vector<XYZ2UVPtr>& points, Sophus::SE3f& T_f_w); }// namespace orbslam }// namespace carrotslam #endif /* NODES_ORBSLAM_OPTIMIZER_H_ */
31.190476
96
0.72855
[ "vector" ]
6d445ce049c6096c744c195173542a3d6400a79f
1,750
h
C
include/WeatherDataVec.h
Dan-Qwerty/MNXB01-PROJECT
0da3a0fc6460503953e1d1a14347b9af347278a1
[ "MIT" ]
null
null
null
include/WeatherDataVec.h
Dan-Qwerty/MNXB01-PROJECT
0da3a0fc6460503953e1d1a14347b9af347278a1
[ "MIT" ]
5
2021-11-01T20:25:02.000Z
2021-11-11T16:36:14.000Z
include/WeatherDataVec.h
Dan-Qwerty/MNXB01-PROJECT
0da3a0fc6460503953e1d1a14347b9af347278a1
[ "MIT" ]
null
null
null
#ifndef WEATHERDATAVEC_H #define WEATHERDATAVEC_H #include <iostream> #include <fstream> #include <regex> #include <string> #include <vector> #include <algorithm> #include <iterator> #include <numeric> #include <set> #include "csvregex.h" #include "WeatherDataLine.h" #include "Gregorian.h" class WeatherDataVec{ public: std::vector<WeatherDataLine> data; WeatherDataVec(std::vector<std::string> data_strings); // constructor WeatherDataVec(std::vector<WeatherDataLine> d); // constructor WeatherDataVec(std::string filename); //constructor WeatherDataVec get_by_month(int month); WeatherDataVec get_by_year(int year); WeatherDataVec get_by_day(int day); WeatherDataVec get_by_regex(std::string inpstr); WeatherDataVec get_between(std::string ststr, std::string edstr); WeatherDataVec get_between(int year1, int month1, int day1, int year2, int month2, int day2); WeatherDataVec get_between(Gregorian stdate, Gregorian eddate); WeatherDataVec get_after(std::string datestr); WeatherDataVec get_after(int year, int month, int day); WeatherDataVec get_after(Gregorian inpdate); WeatherDataVec get_before(std::string datestr); WeatherDataVec get_before(int year, int month, int day); WeatherDataVec get_before(Gregorian inpdate); WeatherDataVec avg_by_day(); WeatherDataLine operator[](int index); WeatherDataLine operator()(int index); WeatherDataVec operator()(int startindex, int endindex); std::vector<int> list_years(); std::vector<int> list_days(); std::vector<double> list_temperatures(); double avgtemp(); double maxtemp(); double mintemp(); bool isempty(); }; #endif /*WEATHERDATAVEC_H*/
22.435897
97
0.722857
[ "vector" ]
6d4e41ab3ef520b55f46da16f76781da500569d8
2,893
h
C
include/qpid/console/Schema.h
gcsideal/debian-qpid-cpp
e4d034036f29408f940805f5505ae62ce89650cc
[ "Apache-2.0" ]
null
null
null
include/qpid/console/Schema.h
gcsideal/debian-qpid-cpp
e4d034036f29408f940805f5505ae62ce89650cc
[ "Apache-2.0" ]
null
null
null
include/qpid/console/Schema.h
gcsideal/debian-qpid-cpp
e4d034036f29408f940805f5505ae62ce89650cc
[ "Apache-2.0" ]
null
null
null
/* * * 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 _QPID_CONSOLE_SCHEMA_H_ #define _QPID_CONSOLE_SCHEMA_H_ #include "qpid/console/ClassKey.h" #include <boost/shared_ptr.hpp> #include <vector> namespace qpid { namespace framing { class Buffer; } namespace console { class Value; struct SchemaArgument { SchemaArgument(framing::Buffer& buffer, bool forMethod = false); boost::shared_ptr<Value> decodeValue(framing::Buffer& buffer); std::string name; uint8_t typeCode; bool dirInput; bool dirOutput; std::string unit; int min; int max; int maxLen; std::string desc; std::string defaultVal; }; struct SchemaProperty { SchemaProperty(framing::Buffer& buffer); boost::shared_ptr<Value> decodeValue(framing::Buffer& buffer); std::string name; uint8_t typeCode; uint8_t accessCode; bool isIndex; bool isOptional; std::string unit; int min; int max; int maxLen; std::string desc; }; struct SchemaStatistic { SchemaStatistic(framing::Buffer& buffer); boost::shared_ptr<Value> decodeValue(framing::Buffer& buffer); std::string name; uint8_t typeCode; std::string unit; std::string desc; }; struct SchemaMethod { SchemaMethod(framing::Buffer& buffer); ~SchemaMethod(); std::string name; std::string desc; std::vector<SchemaArgument*> arguments; }; struct SchemaClass { static const uint8_t KIND_TABLE = 1; static const uint8_t KIND_EVENT = 2; SchemaClass(const uint8_t kind, const ClassKey& key, framing::Buffer& buffer); ~SchemaClass(); const ClassKey& getClassKey() const { return key; } const uint8_t kind; const ClassKey key; std::vector<SchemaProperty*> properties; std::vector<SchemaStatistic*> statistics; std::vector<SchemaMethod*> methods; std::vector<SchemaArgument*> arguments; }; } } #endif
27.292453
86
0.651227
[ "vector" ]
6d6754fee97aa5aa829d1d88edf250488da16fd1
2,683
h
C
src/utils/renderer.h
TcePrepK/SandPileSim
73d1033cc8aebff6cd4f094529985b71b9de7215
[ "MIT" ]
null
null
null
src/utils/renderer.h
TcePrepK/SandPileSim
73d1033cc8aebff6cd4f094529985b71b9de7215
[ "MIT" ]
null
null
null
src/utils/renderer.h
TcePrepK/SandPileSim
73d1033cc8aebff6cd4f094529985b71b9de7215
[ "MIT" ]
null
null
null
void scale(s32 valX, s32 valY); void clearScreen(u32 color); void fillPixel(u32 x, u32 y, u32 color); void fillRect(s32 x, s32 y, s32 w, s32 h, u32 color); void fillRectWithoutScale(s32 x, s32 y, s32 w, s32 h, u32 color); void strokeRect(s32 x, s32 y, s32 w, s32 h, u32 color); void fillElement(s32 x, s32 y, u32 color); Vector mouseToTile(Vector pos32); b32 inBounds(s32 x, s32 y); s32 scaleX = 1; s32 scaleY = 1; void scale(s32 valX, s32 valY) { scaleX = valX; scaleY = valY; } void clearScreen(u32 color) { for (u32 x = 0; x < globalVariables.screenWidth; x++) for (u32 y = 0; y < globalVariables.screenHeight; y++) fillPixel(x, y, color); } void fillPixel(u32 x, u32 y, u32 color) { u32 idx = x + y * globalVariables.screenWidth; globalVariables.pixels[idx] = color; } void fillRect(s32 x, s32 y, s32 w, s32 h, u32 color) { x *= scaleX; y *= scaleY; w *= scaleX; h *= scaleY; if (!inBounds(x, y)) return; w = clamp(w, 0, globalVariables.screenWidth - x); h = clamp(h, 0, globalVariables.screenHeight - y); for (s32 i = 0; i < w; i++) { for (s32 j = 0; j < h; j++) { s32 curX = x + i; s32 curY = y + j; fillPixel(curX, curY, color); } } } void fillRectWithoutScale(s32 x, s32 y, s32 w, s32 h, u32 color) { if (!inBounds(x, y)) return; w = clamp(w, 0, globalVariables.screenWidth - x); h = clamp(h, 0, globalVariables.screenHeight - y); for (s32 i = 0; i < w; i++) { for (s32 j = 0; j < h; j++) { fillPixel(x + i, y + j, color); } } } void strokeRect(s32 x, s32 y, s32 w, s32 h, u32 color) { x *= scaleX; y *= scaleY; w *= scaleX; h *= scaleY; if (!inBounds(x, y)) return; w = clamp(w, 0, globalVariables.screenWidth - x); h = clamp(h, 0, globalVariables.screenHeight - y); for (s32 i = 0; i < w; i++) { fillPixel(x + i, y, color); fillPixel(x + i, y + (h - 1), color); } for (s32 i = 0; i < h; i++) { fillPixel(x, y + i, color); fillPixel(x + (w - 1), y + i, color); } } void fillElement(s32 x, s32 y, u32 color) { x *= scaleX; y *= scaleY; if (!inBounds(x, y)) return; s32 w = scaleX; s32 h = scaleY; w = clamp(w, 0, globalVariables.screenWidth - x); h = clamp(h, 0, globalVariables.screenHeight - y); for (s32 i = 0; i < w; i++) { for (s32 j = 0; j < h; j++) { s32 curX = x + i; s32 curY = y + j; fillPixel(curX, curY, color); } } } Vector mouseToTile(Vector pos32) { Vector final = {}; s32 x = pos32.x; s32 y = pos32.y; final.x = x / scaleX; final.y = y / scaleY; return final; } b32 inBounds(s32 x, s32 y) { s32 width = globalVariables.screenWidth; s32 height = globalVariables.screenHeight; return (x >= 0 && x < width&& y >= 0 && y < height); }
20.960938
66
0.598956
[ "vector" ]
6d69473f6036c35a6b4d7fd263d04dadc990f5ab
23,707
c
C
lib/vdriver/src/vdriver.c
robinlavallee/chicken-little
4605bdc07a5a8ea7df9fb2b574241fa15a1d2dc3
[ "MIT" ]
1
2020-09-14T22:16:15.000Z
2020-09-14T22:16:15.000Z
lib/vdriver/src/vdriver.c
robinlavallee/chicken-little
4605bdc07a5a8ea7df9fb2b574241fa15a1d2dc3
[ "MIT" ]
null
null
null
lib/vdriver/src/vdriver.c
robinlavallee/chicken-little
4605bdc07a5a8ea7df9fb2b574241fa15a1d2dc3
[ "MIT" ]
1
2020-09-14T22:16:21.000Z
2020-09-14T22:16:21.000Z
/* The VDRIVER - A Classic Video Game Engine By Jake Stine and Divine Entertainment (1997-2000) Support: If you find problems with this code, send mail to: air@divent.org For additional information and updates, see our website: http://www.divent.org Disclaimer: I could put things here that would make me sound like a first-rate california prune. But I simply can't think of them right now. In other news, I reserve the right to say I wrote my code. All other rights are just abused legal tender in a world of red tape. Have fun! --------------------------------------------------- Module: vdriver.c Video driver - portable interface to hardware. This module, (and other modules in this directory, for that matter) for most practical purposes, is classifiled as "portable". These functions are the interface for the non-portable low-level drivers, which are reg- istered at the start of the program. Make sure to see VDRIVER.H for further information about the strutures used in the VDRIVER (ie, SPRITE, TILE, etc). Also, VDRIVER.DOC has a gen- eral overview of the usage of the library. Important Notes: -/- About Sprite / Tile blit and clipping: - The base unit of display for VDRIVER is the tile. A tile is very simp- le and built for speed. A tile is simply raw data of a pre-defined size (usually 32x32 pixels) with no header. - There is only a single generalized sprite blitter function. This func- tion detects the blitter type for the sprite via its header. It also handles all clipping concerns. - vd_tilewidth is in bytes and not pixels. (ie, the x size in pels * bytespp) */ #include "vdriver.h" #include <string.h> void Sprite_FreeBlitters(VD_SURFACE *vs); // ========================================================================== // World of Static! // > Local VDRIVER variable declarations static VDRIVER *vdrvbegin = (VDRIVER *)NULL; static uint vd_cpu = CPU_NONE; // ------------------------ // Mouse Rendering Shizat // (placebo functions) // ------------------------ static void (*vd_MouseRestoreBG)(void); static void (*vd_MouseDrawCursor)(int xmse, int ymse, UBYTE *mcur); static void dummy_MouseRestoreBG(void) { } static void dummy_MouseDrawCursor(int xmse, int ymse, UBYTE *mcur) { } // ===================================================================================== void VD_BuildBits(uint mask, uint *pos, uint *len) // ===================================================================================== // This is a workhorse function I made which converts the cleverly ambiguous bitfields // that directdraw offers to something far more subtantial. It takes a bitmask of the // color component and extracts from it the position and the length of the field of bits // that make up the particular color. // -- oh yea, VESA provided you with this information automatically. Vesa // was good. Directdraw is not. Imagine that. -- { int i; for(i=0, *pos=0, *len=0; i<32; i++) { if(mask & (1ul<<i)) { // bit set - inc length if(*len) (*len)++; else { *len = 1; *pos = i; } } else { // bit clear if(*len) return; } } } // ===================================================================================== static void BuildAlphaMasks(VD_SURFACE *vs) // ===================================================================================== // Constructs the alpha masks which are used by the alpha blitters. There are several // masks which the game uses, so we simply build a table of them, ragning from 1 bit mask // to 8 bit mask. { uint t; ULONG mask; for(t=0, mask=1; t<7; t++) { vs->alphamask[t] = (vs->mask.red & ((~mask) << vs->fieldpos.red)) | (vs->mask.green & ((~mask) << vs->fieldpos.green)) | (vs->mask.blue & ((~mask) << vs->fieldpos.blue)); mask = (mask<<1) | 1; // progress the mask.. shift then set the low bit. } } // ===================================================================================== void VD_SetClipper(VD_SURFACE *surface, const VRECT *rect) // ===================================================================================== { if(!surface) return; if(rect) { int weetop; weetop = (rect->top - surface->clipper.top); if(weetop > (int)surface->yreal) return; // invisible surfaces are bad if(weetop < 0) weetop = 0; surface->clipmem = &surface->vidmem[(weetop * surface->bytewidth) + ((rect->left - surface->clipper.left) * surface->bytespp)]; surface->clipper = *rect; surface->clipper.bottom = _mm_boundscheck(surface->clipper.bottom, 0, (int)(surface->yreal-1)); surface->clipper.top = _mm_boundscheck(surface->clipper.top, 0, (int)(surface->yreal-1)); surface->xsize = ((rect->right <= 0) ? 0 : rect->right) - rect->left; surface->ysize = surface->clipper.bottom - surface->clipper.top; surface->physheight = surface->ysize + (surface->realheight - surface->yreal); } else { surface->clipper.top = surface->clipper.left = 0; surface->xsize = surface->clipper.right = surface->xreal; surface->ysize = surface->clipper.bottom = surface->yreal; surface->physheight = surface->realheight; surface->clipmem = surface->vidmem; } } // ===================================================================================== VD_SURFACE *VD_CreateClipSurface(const VD_SURFACE *surface, const VRECT *rect) // ===================================================================================== { VD_SURFACE *cs; if(!surface || !rect) return NULL; cs = (VD_SURFACE *)_mm_malloc(sizeof(VD_SURFACE)); *cs = *surface; cs->vidmem = &surface->vidmem[(rect->top * surface->bytewidth) + (rect->left * surface->bytespp)]; return cs; } // ===================================================================================== static void InitColorConversion(VD_SURFACE *surface) // ===================================================================================== { int i; // Make a lookup table for color conversions. for(i=0; i<256; i++) { surface->masktable_red[i] = ((surface->mask.red * i) / 255) & surface->mask.red; surface->masktable_green[i] = ((surface->mask.green * i) / 255) & surface->mask.green; surface->masktable_blue[i] = ((surface->mask.blue * i) / 255) & surface->mask.blue; } } static CHAR errmsg_vidfail[] = "Video Initialization Failure!\r\nPlease check the log file for details."; // ===================================================================================== VD_RENDERER *VD_InitRenderer(int driver) // ===================================================================================== // Inializes a driver, and creates a 'rendering device' through which to // access it. Depending on the driver. After the rendering device is cre- // ated, use VD_SetMode to assign the bitdepth, mode of access, and other // such properties. // // Parameters: // driver - driver to initialize, or -1 (VD_AUTODETECT) for autodetection. // Returns: // On failure, returns NULL. On success, returns the VD_RENDERER struct, // filled and happy! { VDRIVER *l = vdrvbegin; VD_RENDERER *vr; if(driver != VDRIVER_AUTODETECT) { int t = 0; while((t < driver) && l) { l = l->next; t++; } } else { while(l && l->Detect && !l->Detect()) { l = l->next; } } if(!l) { _mmlog("Video > Detection Failed!"); return NULL; } _mmlog("Video > Initializing %s driver.", l->name); vr = _mm_calloc(1, sizeof(VD_RENDERER)); vr->vdriver = *l; if(l->Init && !l->Init(vr)) { _mmlog("Video > Initialization Failed!"); _mmerr_set(MMERR_INITIALIZING_DEVICE,errmsg_vidfail); return NULL; } // Set up some things in the surface that are the same for all drivers always // (ie, these are precaculated thingies using the hardware-specific information // already available to us) // Configure Shift-formats (used for additive blending and alpha channels) //vs->shiftfmt1.shiftmask = vs->fieldpos return vr; } // =========================================================================== VD_SURFACE *VD_SetMode(VD_RENDERER *vr, int *xres, int *yres, int *bytespp, uint flags) // =========================================================================== // Initializing the DirectDraw driver in fullscreen mode will automatically // set the video display to the requested size and bitdepth. Attaching a // 'windowed' mode renderer to a window will do nothing more than refresh // that wondow/object when it is visible. // // Parameters: // xres/yres/bytespp // Arrays of appropriate values. They are searched in order, together, // when detecting an appropriate video mode. // // flags - See 'VMODE_*' flagset in vdriver.h. { if(!vr) return NULL; VD_ExitMode(vr); if(vr->vdriver.SetMode && !vr->vdriver.SetMode(vr, xres, yres, bytespp, flags)) { _mmlog("Video > Could not set a video mode!"); _mmerr_set(MMERR_INITIALIZING_DEVICE,errmsg_vidfail); return NULL; } _mmlog("Vdriver > Video Modeset Successful!"); _mmlog(" > xres: %d yres: %d bytespp: %d",vr->surface.xsize, vr->surface.ysize, vr->surface.bytespp); InitColorConversion(&vr->surface); BuildAlphaMasks(&vr->surface); vr->surface.xreal = vr->surface.xsize; vr->surface.yreal = vr->surface.ysize; vr->surface.realheight = vr->surface.physheight; vr->surface.setclipper(&vr->surface, NULL); // Throw the surface change event VD_ThrowEvent(vr, VDEVT_SURFACE_CHANGE); vr->visible = 1; vr->initialized = 1; return &vr->surface; } // =========================================================================== void VD_SetEvent(VD_RENDERER *vr, int event, void *data, BOOL (*eventproc)(VD_RENDERER *vr, void *data)) // =========================================================================== { if(!eventproc) return; // bah, silly nulls. vr->event[event].data = data; vr->event[event].proc = eventproc; } // =========================================================================== void VD_ThrowEvent(VD_RENDERER *vr, int event) // =========================================================================== { if(vr && vr->event[event].proc) vr->event[event].proc(vr, vr->event[event].data); } // =========================================================================== BOOL VD_CreateSurface_System(int xres, int yres, int bytespp) // =========================================================================== // Create a surface in system ram. This surface will rely on software render- // ing only, and hence can take full advantage of all RLE sprites and tiles. // This surface can have any bitdepth and be rendered to any VD_RENDERER (as // long as any needed color-conversion info has been properly initialized). { return 0; } /*BOOL VD_CreateSurface(VD_RENDERER *vr, int xres, int yres, uint mode) // Creates a working surface area for the given renderer. All surfaces // attached to a renderer must be fo the same bitdepth as the renderer itself. // // mode - can be: VDSURFACE_AUTODETECT, VDSURFACE_VIDMEM, VDSURFACE_SYSMEM. // AUTODETECT : will automagically be located in either the video // memory or in system memory, depending on the acceleration capabilities // of the video hardware and drivers. { int t = 0; vd_physwidth = l->xres; vd_tilewidth = DEFAULT_TILE_WIDTH * l->bytespp; vd_physheight = l->yres; vd_tileheight = DEFAULT_TILE_HEIGHT; vd_bytespp = l->bytespp; vd_tilesize = vd_tilewidth * DEFAULT_TILE_HEIGHT; vd_ptilewidth = DEFAULT_TILE_WIDTH; vd_ptilesize = DEFAULT_TILE_WIDTH * DEFAULT_TILE_HEIGHT; vd_bytewidth = vd_physwidth * vd_bytespp; vd_bytesize = vd_bytewidth * vd_physheight; vd_physsize = vd_physwidth * vd_physheight; vd_nextpage = l->NextPage; vd_nextrect = l->NextRect; vd_clearscreen = l->ClearScreen; vd_GetPalette = l->GetPalette; vd_SetPalette = l->SetPalette; vd_FastFadeInit = l->FastFadeInit; vd_FastFade = l->FastFade; vd_MouseRestoreBG = (l->MouseRestoreBG) ? l->MouseRestoreBG : dummy_MouseRestoreBG; vd_MouseDrawCursor = (l->MouseDrawCursor) ? l->MouseDrawCursor : dummy_MouseDrawCursor; v_line = l->vLine; h_line = l->hLine; line = l->Line; rect = l->Rect; box = l->Box; fillbox = l->FillBox; vd_spriteblitter = l->SpriteBlitter; vd_tileopaque = l->TileOpaque; vd_tiletrans = l->TileTrans; vd_tilefunky = l->TileFunky; vd_red_fieldpos = l->FieldPosRed; vd_red_fieldsize = l->FieldSizeRed; vd_red_maxvalue = (1 << vd_red_fieldsize); vd_green_fieldpos = l->FieldPosGreen; vd_green_fieldsize = l->FieldSizeGreen; vd_green_maxvalue = (1 << vd_green_fieldsize); vd_blue_fieldpos = l->FieldPosBlue; vd_blue_fieldsize = l->FieldSizeBlue; vd_blue_maxvalue = (1 << vd_blue_fieldsize); vd_driver = l; printlog("Video > Mode selected: %dx%dx%d.",vd_physwidth,vd_physheight,vd_bytespp); // Allocate off-screen memory [if not already allocated] if(vd_allocflag && vd_vidmem==NULL) { if((vd_vidmem = (UBYTE *)_mm_malloc(vd_bytewidth * vd_physheight)) == NULL) return 1; printlog("Video > Off-screen buffer allocated."); } // Allocate y-scan index chart [if not already allocated] if(vd_scrtable == NULL) { if((vd_scrtable = (UBYTE **)_mm_malloc(vd_physheight * sizeof(UBYTE *))) == NULL) return 1; VD_InitScrTable(vd_vidmem,vd_bytewidth,vd_physheight,vd_bytespp); printlog("Video > Lookup table allocated and initialized."); } VD_SetMouseColor(255, 255, 255); return 0; }*/ /*void VD_InfoDriver(void) { int t; VDRIVER *l; for(t=1,l=vdrvbegin; l!=NULL; l=l->next, t++); printf("%d. %s\n",t,l->version); }*/ // =========================================================================== void VD_RegisterDriver(VDRIVER *drv) // =========================================================================== { VDRIVER *cruise = vdrvbegin; if(cruise) { while(cruise->next) cruise = cruise->next; cruise->next = drv; } else vdrvbegin = drv; } // =========================================================================== void VD_Exit(VD_RENDERER *vr) // =========================================================================== { if(vr) { _mmlogd("vdrive > Deinitializing renderer..."); if(vr->initialized && vr->vdriver.ExitMode) vr->vdriver.ExitMode(vr); if(vr->vdriver.Exit) vr->vdriver.Exit(vr); _mmlogd(" > Unregistering blitters..."); Sprite_FreeBlitters(&vr->surface); _mm_free(vr, "Done!"); } } // =========================================================================== void VD_ExitMode(VD_RENDERER *vr) // =========================================================================== { if(vr) { vr->visible = 0; if(vr->initialized && vr->vdriver.ExitMode) vr->vdriver.ExitMode(vr); Sprite_FreeBlitters(&vr->surface); vr->initialized = 0; } } /*void VD_InitScrTable(UBYTE *base, int scrnwidth, int scrnheight, int bytespp) { int i; for(i=0; i<scrnheight; i++, base+=scrnwidth) vd_scrtable[i] = base; } */ /*void VD_SetIntensity(int intensity) { vd_intensity = intensity; } void VD_AllocateBuffer(BOOL val) { vd_allocflag = val; } */ /*void VD_SetTileSize(int xsize, int ysize) { vd_ptilesize = (vd_ptilewidth = xsize) * ysize; vd_tilesize = (vd_tilewidth = xsize * vd_bytespp) * (vd_tileheight = ysize); } */ // ==================================================================================== static SPR_BLITTER *spr_structdup(VD_SURFACE *vs, SPR_BLITTER *sprdrv) // ==================================================================================== { // Duplicate the sprite structure list that we are given. SPR_BLITTER *weenie; if(!sprdrv) return NULL; if((sprdrv->bytespp == vs->bytespp) && ((sprdrv->cpu == vd_cpu) || (sprdrv->cpu == CPU_NONE)) && ((sprdrv->fieldpos.red == SPRBLT_UNUSED) || !memcmp(&sprdrv->fieldpos, &vs->fieldpos, sizeof(vs->fieldpos)))) { weenie = (SPR_BLITTER *)_mm_structdup(sprdrv, sizeof(SPR_BLITTER)); if(weenie) weenie->next = spr_structdup(vs, sprdrv->next); } else weenie = spr_structdup(vs, sprdrv->next); return weenie; } // ==================================================================================== void Sprite_RegisterBlitterList(VD_SURFACE *vs, SPR_BLITTER *sprlst[]) // ==================================================================================== { if(sprlst) { uint i; for(i=0; i<16, sprlst[i]; i++) Sprite_RegisterBlitter(vs, sprlst[i]); } } // ==================================================================================== void Sprite_RegisterBlitter(VD_SURFACE *vs, SPR_BLITTER *sprdrv) // ==================================================================================== { SPR_BLITTER *cruise; if(vs->sprdrv) { cruise = vs->sprdrv; while(cruise->next) cruise = cruise->next; cruise->next = spr_structdup(vs, sprdrv); } else vs->sprdrv = spr_structdup(vs, sprdrv); } // ==================================================================================== void Sprite_FreeBlitters(VD_SURFACE *vs) // ==================================================================================== { SPR_BLITTER *cruise; cruise = vs->sprdrv; while(cruise) { SPR_BLITTER *ftmp = cruise; cruise = cruise->next; free(ftmp); } vs->sprdrv = NULL; } // ==================================================================================== static SPR_BLITTER *configsprite(const VD_SURFACE *vs, uint flags, uint opacity) // ==================================================================================== { SPR_BLITTER *cruise, *goodblt; uint goodone; // Find a driver that is suitable for this sample cruise = vs->sprdrv; goodone = 1; // set to one, so that we fail if no good matches goodblt = NULL; while(cruise) { // Check for: // (a) blit flag match. // (b) surface prebuffer and alignment are greater than or equal to sprite's // (c) sprite align is a factor of surface alignment (to make sure they are compat) //_mmlog("opacity: %d, %d; prebuf: %d, %d; align %d, %d;",cruise->opacity,opacity,cruise->prebuf, vs->prebuffer, cruise->align, vs->alignment); if((cruise->opacity == opacity) && (cruise->prebuf <= vs->prebuffer) && (cruise->align <= vs->alignment) && !(vs->alignment % cruise->align)) { uint weight = 0; // Check for non-critials: CPU and alpha blit flag compatability if((cruise->flags == flags) && (cruise->cpu == vd_cpu)) return cruise; // weigh the 'matchability' of this driver. Generally, we are // looking for the fastest and/or best quality driver. This // makes the assumptions that any driver that requires special // CPUs is probably pretty fast. if(flags != cruise->flags) { // we know that cruise->cpu == vd_cpu. if(!cruise->flags) { weight += 40; if(cruise->cpu != CPU_NONE) weight += 30; } } else if(cruise->cpu == CPU_NONE) weight += 50; if(weight > goodone) { goodone = weight; goodblt = cruise; } } cruise = cruise->next; } if(goodblt) { return goodblt; } else { //woops, we can't blit this sprite! _mmlog("vdriver > configsprite > Attempted to configure sprite, but no suitable blit was available!"); return NULL; } } // =========================================================================== void spralpha_placebo(const SPRITE *spr, int xloc, int yloc, uint alpha) // =========================================================================== { } // =========================================================================== void sprcross_placebo(const SPRITE *spra, const SPRITE *sprb, int xloc, int yloc, uint alpha) // =========================================================================== { } // =========================================================================== void sprblit_placebo(const SPRITE *spr, int xloc, int yloc) // =========================================================================== { } // ==================================================================================== BOOL Sprite_Init(VD_SURFACE *vs, SPRITE *dest, int xsize, int ysize, uint flags, uint opacity) // ==================================================================================== { SPR_BLITTER *sprdrv = NULL; memset(dest,0,sizeof(SPRITE)); if(xsize && ysize) sprdrv = configsprite(vs, flags, opacity); if(sprdrv) { // Set up stuff based on the driver... dest->api.blit = sprdrv->api.blit ? sprdrv->api.blit : sprblit_placebo; dest->api.alphablit = sprdrv->api.alphablit ? sprdrv->api.alphablit : spralpha_placebo; dest->api.blackfade = sprdrv->api.blackfade ? sprdrv->api.blackfade : spralpha_placebo; dest->api.fastshadow = sprdrv->api.fastshadow ? sprdrv->api.fastshadow : sprblit_placebo; dest->physwidth = (xsize + vs->prebuffer + vs->alignment) & ~(vs->alignment-1); // Note: We only allocate crap if we're not dealing with RLE sprites. // Otherwise, it is up to the end user to allocate shizat. if(!(dest->opacity == SPR_FUNKY)) { dest->bitalloc = _mm_calloc(dest->physwidth*vs->bytespp, ysize); if(!dest->bitalloc) { _mmlog("Vdriver > SpriteInit > Could not create sprite bitmap!"); return 0; } dest->bitmap = dest->bitalloc + (vs->bytespp * vs->prebuffer); // tack on the prebuffer. } } else { dest->api.blit = sprblit_placebo; dest->api.alphablit = spralpha_placebo; dest->api.blackfade = spralpha_placebo; dest->api.fastshadow = sprblit_placebo; } // Configure givens (independent of platform/driver) dest->vs = vs; dest->xsize = xsize; dest->ysize = ysize; dest->opacity = opacity; //dest->flags = flags; dest->flags = flags; return 1; } // ==================================================================================== void Sprite_Free(SPRITE *sprite) // ==================================================================================== { if(sprite && sprite->bitalloc) _mm_free(sprite->bitalloc, NULL); } // Crossfading works on opaque sprites only (for now). void (*sprblit_crossfade)(const struct SPRITE *spra, const struct SPRITE *sprb, int xloc, int yloc, uint alpha);
34.012912
178
0.524402
[ "render", "object" ]
cd0d76cecd53e5a8e19c9a4222b67082c4e98ec8
3,919
h
C
palmos/dictate/Diploma/Diploma/Select.h
bschau/Portfolio
326e298322d7ca60b1c5198869fb6e7ea2a38e74
[ "MIT" ]
null
null
null
palmos/dictate/Diploma/Diploma/Select.h
bschau/Portfolio
326e298322d7ca60b1c5198869fb6e7ea2a38e74
[ "MIT" ]
null
null
null
palmos/dictate/Diploma/Diploma/Select.h
bschau/Portfolio
326e298322d7ca60b1c5198869fb6e7ea2a38e74
[ "MIT" ]
1
2020-03-28T18:25:41.000Z
2020-03-28T18:25:41.000Z
#pragma once namespace Diploma { using namespace System; using namespace System::ComponentModel; using namespace System::Collections; using namespace System::Windows::Forms; using namespace System::Data; using namespace System::Drawing; /// <summary> /// Summary for Select /// /// WARNING: If you change the name of this class, you will need to change the /// 'Resource File Name' property for the managed resource compiler tool /// associated with all .resx files this class depends on. Otherwise, /// the designers will not be able to interact properly with localized /// resources associated with this form. /// </summary> public __gc class Select : public System::Windows::Forms::Form { public: Select(void) { InitializeComponent(); idxSelected=-1; } protected: void Dispose(Boolean disposing) { if (disposing && components) { components->Dispose(); } __super::Dispose(disposing); } private: System::Windows::Forms::Label * label1; public: System::Windows::Forms::ListBox * lbScores; int idxSelected; void ClearList(void) { lbScores->Items->Clear(); } void AddItem(String *s) { lbScores->Items->Add(s); } private: System::Windows::Forms::Button * bPrint; private: System::Windows::Forms::Button * bCancel; private: /// <summary> /// Required designer variable. /// </summary> System::ComponentModel::Container* components; /// <summary> /// Required method for Designer support - do not modify /// the contents of this method with the code editor. /// </summary> void InitializeComponent(void) { this->label1 = new System::Windows::Forms::Label(); this->lbScores = new System::Windows::Forms::ListBox(); this->bPrint = new System::Windows::Forms::Button(); this->bCancel = new System::Windows::Forms::Button(); this->SuspendLayout(); // // label1 // this->label1->Location = System::Drawing::Point(8, 8); this->label1->Name = S"label1"; this->label1->Size = System::Drawing::Size(192, 32); this->label1->TabIndex = 0; this->label1->Text = S"There are multiple scores in this file. Please select the score to print:"; // // lbScores // this->lbScores->Location = System::Drawing::Point(8, 40); this->lbScores->Name = S"lbScores"; this->lbScores->Size = System::Drawing::Size(184, 95); this->lbScores->TabIndex = 1; // // bPrint // this->bPrint->Location = System::Drawing::Point(8, 144); this->bPrint->Name = S"bPrint"; this->bPrint->TabIndex = 2; this->bPrint->Text = S"Print"; this->bPrint->Click += new System::EventHandler(this, bPrint_Click); // // bCancel // this->bCancel->DialogResult = System::Windows::Forms::DialogResult::Cancel; this->bCancel->Location = System::Drawing::Point(118, 144); this->bCancel->Name = S"bCancel"; this->bCancel->TabIndex = 3; this->bCancel->Text = S"Cancel"; this->bCancel->Click += new System::EventHandler(this, bCancel_Click); // // Select // this->AcceptButton = this->bPrint; this->AutoScaleBaseSize = System::Drawing::Size(5, 13); this->CancelButton = this->bCancel; this->ClientSize = System::Drawing::Size(200, 174); this->ControlBox = false; this->Controls->Add(this->bCancel); this->Controls->Add(this->bPrint); this->Controls->Add(this->lbScores); this->Controls->Add(this->label1); this->FormBorderStyle = System::Windows::Forms::FormBorderStyle::FixedDialog; this->Name = S"Select"; this->Text = S"Select Score To Print"; this->ResumeLayout(false); } private: System::Void bCancel_Click(System::Object * sender, System::EventArgs * e) { Close(); } private: System::Void bPrint_Click(System::Object * sender, System::EventArgs * e) { idxSelected=lbScores->SelectedIndex; Close(); } }; }
29.02963
101
0.650421
[ "object" ]
cd10436f526063c67b429e1cf0522582ba8cd3b6
19,121
h
C
src/cache_manager/CacheManager.h
jcarreira/cirrus-kv
a44099185e02859385997956333b364ae836fee5
[ "Apache-2.0" ]
8
2018-07-18T22:13:36.000Z
2021-08-24T12:28:42.000Z
src/cache_manager/CacheManager.h
jcarreira/ddc
a44099185e02859385997956333b364ae836fee5
[ "Apache-2.0" ]
7
2016-11-22T11:07:14.000Z
2016-12-17T22:49:23.000Z
src/cache_manager/CacheManager.h
jcarreira/ddc
a44099185e02859385997956333b364ae836fee5
[ "Apache-2.0" ]
null
null
null
#ifndef SRC_CACHE_MANAGER_CACHEMANAGER_H_ #define SRC_CACHE_MANAGER_CACHEMANAGER_H_ #include <unordered_map> #include <vector> #include <functional> #include <algorithm> #include <iostream> #include "object_store/ObjectStore.h" #include "cache_manager/EvictionPolicy.h" #include "cache_manager/PrefetchPolicy.h" #include "object_store/FullBladeObjectStore.h" #include "common/Exception.h" #include "utils/logging.h" namespace cirrus { using ObjectID = uint64_t; const uint64_t HIGH_PEND = 50; /** * A class that manages the cache and interfaces with the store. */ template<class T> class CacheManager { public: /** * This enum defines different prefetch modes for the cache manager. * The default is no prefetching. */ enum PrefetchMode { kNone = 0, /**< The cache manager will not automatically prefetch. */ kOrdered, /**< The cache manager will prefetch a few items ahead. */ kCustom /**< The cache will prefetch in a user defined fashion. */ }; CacheManager(cirrus::ostore::FullBladeObjectStoreTempl<T> *store, cirrus::EvictionPolicy *eviction_policy, uint64_t cache_size, bool defer_writes = false); T get(ObjectID oid); void put(ObjectID oid, const T& obj); void prefetch(ObjectID oid); void remove(ObjectID oid); void removeBulk(ObjectID first, ObjectID last); void prefetchBulk(ObjectID first, ObjectID last); void get_bulk(ObjectID start, ObjectID last, T* data); void put_bulk(ObjectID start, ObjectID last, T* data); void setMode(PrefetchMode mode, cirrus::PrefetchPolicy<T> *policy = nullptr); void setMode(PrefetchMode mode, ObjectID first, ObjectID last, uint64_t read_ahead); private: /** * A prefetch policy that does not perform any prefetching. */ class OffPolicy :public cirrus::PrefetchPolicy<T> { public: /** * Return an empty vector to indicate no prefetching. */ std::vector<ObjectID> get(const ObjectID& /* id */, const T& /* obj */) override { return std::vector<ObjectID>(); } }; /** * A prefetch policy that fetches the next k items when one is fetched. * Store cannot be modified while this policy is in use. */ class OrderedPolicy :public cirrus::PrefetchPolicy<T> { public: /** * Counterpart to the CacheManager's get method. Returns a list of items * to prefetch. * @param id the ObjectID being retrieved. * @param obj unused * @return a vector of ObjectIDs to be prefetched. */ std::vector<ObjectID> get(const ObjectID& id, const T& /* obj */) override { if (id < first || id > last) { throw cirrus::Exception("Attempting to get id outside of " "continuous range present at time of prefetch mode " "specification."); } std::vector<ObjectID> to_return; to_return.reserve(read_ahead); for (uint64_t i = 1; i <= read_ahead; i++) { // Math to make sure that prefetching loops back around // Formula is: // val = ((oid + i) - first) % (last - first + 1)) + first ObjectID tentative_fetch = id + i; ObjectID shifted = tentative_fetch - first; ObjectID modded = shifted % (last - first + 1); ObjectID to_prefetch = modded + first; // If attempting to prefetch the id that was just retrieved, // then a full circle has been completed, so no further // prefetching is necessary if (to_prefetch == id) { break; } to_return.push_back(to_prefetch); } return to_return; } /** * Sets the range that this policy will use. * @param first_ first objectID in a continuous range * @param last_ last objectID that will be used */ void setRange(ObjectID first_, ObjectID last_) { first = first_; last = last_; } /** * Sets the readahead for this prefetch policy. * @param read_ahead_ how many items ahead the cache should prefetch. */ void setReadAhead(uint64_t read_ahead_) { read_ahead = read_ahead_; } private: /** How many objects to prefetch ahead. */ uint64_t read_ahead = 5; /** First continuous oid. */ ObjectID first; /** Last continuous oid. */ ObjectID last; }; void evict_vector(const std::vector<ObjectID>& to_remove); void evict(ObjectID oid); /** * Struct that is stored within the cache. Contains a copy of an object * of the type that the cache is storing. */ struct cache_entry { /** Boolean indicating whether this item is in the cache. */ bool cached = true; /** * Boolean indicating whether this entry is up to date with the remote. */ bool dirty = false; /** Object that will be retrieved by a get() operation. */ T obj; /** Future indicating status of operation */ typename cirrus::ObjectStore<T>::ObjectStoreGetFuture future; }; /** * A pointer to a store that contains the same type of object as the * cache. This is the store that the cache manager interfaces with in order * to access the remote store. */ cirrus::ObjectStore<T> *store; /** * The map that serves as the actual cache. Maps ObjectIDs to cache * entries. */ std::unordered_map<ObjectID, struct cache_entry> cache; /** Map used to keep track of asynchronously evicted items. */ std::unordered_map<ObjectID, typename cirrus::ObjectStore<T>::ObjectStorePutFuture> pending_writes; /** * The maximum capacity of the cache. Will never be exceeded. Set * at time of instantiation. */ uint64_t max_size; /** * EvictionPolicy used for all calls to the eviction policy. Call made * before each operation that the cache manager makes. */ cirrus::EvictionPolicy *eviction_policy; /** * PrefetchPolicy used to determine prefetch operations. */ cirrus::PrefetchPolicy<T> *prefetch_policy; // Policies to use if specified /** An instance of an off policy. */ OffPolicy off_policy; /** An instance of an ordered policy. */ OrderedPolicy ordered_policy; /** Boolean indicating whether writes should be deferred until eviction. */ bool defer_writes; }; /** * Constructor for the CacheManager class. Any object added to the cache * needs to have a default constructor. Prefetching is off by default. * @param store a pointer to the ObjectStore that the CacheManager will * interact with. This is where all objects will be stored and retrieved * from. * @param cache_size the maximum number of objects that the cache should * hold. Must be at least one. * @param defer_writes whether calls to put should write immediately to the * remote store or if no write should occur until eviction. Should be set * to true in order to defer writes. */ template<class T> CacheManager<T>::CacheManager( cirrus::ostore::FullBladeObjectStoreTempl<T> *store, cirrus::EvictionPolicy *eviction_policy, uint64_t cache_size, bool defer_writes) : store(store), max_size(cache_size), eviction_policy(eviction_policy), defer_writes(defer_writes) { if (cache_size < 1) { throw cirrus::CacheCapacityException( "Cache capacity must be at least one."); } prefetch_policy = &off_policy; } /** * A function that returns an object stored under a given ObjectID. * If no object is stored under that ObjectID, throws a cirrus::Exception. * @param oid the ObjectID that the object you wish to retrieve is stored * under. * @return a copy of the object stored on the server. */ template<class T> T CacheManager<T>::get(ObjectID oid) { std::vector<ObjectID> to_remove = eviction_policy->get(oid); evict_vector(to_remove); // check if entry exists for the oid in cache struct cache_entry *entry; if (defer_writes) { // If attempting to get an item that was evicted, ensure that // the asynchronous write has completed before attempting to access it auto it = pending_writes.find(oid); if (it != pending_writes.end()) { auto future = it->second; // wait for completion future.wait(); // Remove the entry as the operation has completed. pending_writes.erase(it); } } LOG<INFO>("Cache get called on oid: ", oid); auto cache_iterator = cache.find(oid); if (cache_iterator != cache.end()) { LOG<INFO>("Entry exists for oid: ", oid); // entry exists for the oid // Call future's get method if the object is not cached entry = &(cache_iterator->second); if (!entry->cached) { LOG<INFO>("oid was prefetched"); // TODO(Tyler): Should we return the result of the get directly // and avoid a potential extra copy? Tradeoff is copy now vs // copy in the future in case of repeated access. entry->obj = entry->future.get(); entry->cached = true; } } else { // entry does not exist. // set up entry, pull synchronously // TODO(Tyler): Do we save to the cache in this case? if (cache.size() == max_size) { throw cirrus::CacheCapacityException("Get operation would put cache " "over capacity."); } entry = &cache[oid]; entry->obj = store->get(oid); } std::vector<ObjectID> to_prefetch = prefetch_policy->get(oid, entry->obj); for (auto const& id_to_prefetch : to_prefetch) { prefetch(id_to_prefetch); } return entry->obj; } /** * A function that stores an object obj in the remote store under ObjectID oid. * Calls the put() method in FullBladeObjectstore.h and stores cached copy * of object locally. * @param oid the ObjectID to store under. * @param obj the object to store on the server * @see FullBladeObjectstore */ template<class T> void CacheManager<T>::put(ObjectID oid, const T& obj) { std::vector<ObjectID> to_remove = eviction_policy->put(oid); evict_vector(to_remove); struct cache_entry *entry; LOG<INFO>("Cache put called on oid: ", oid); auto cache_iterator = cache.find(oid); if (cache_iterator != cache.end()) { LOG<INFO>("Entry exists for oid: ", oid); // entry exists for the oid entry = &(cache_iterator->second); // replace existing entry entry->obj = obj; entry->dirty = true; } else { // entry does not exist. // set up entry and fill it if (cache.size() == max_size) { throw cirrus::CacheCapacityException("Put operation would put cache " "over capacity."); } entry = &cache[oid]; entry->obj = obj; entry->dirty = true; } if (!defer_writes) { store->put(oid, obj); } } /** * Gets many objects from the remote store at once. These items will be written * into the c style array pointed to by data. * @param start the first objectID that should be pulled from the store. * @param the last objectID that should be pulled from the store. * @param data a pointer to a c style array that will be filled from the * remote store. */ template<class T> void CacheManager<T>::get_bulk(ObjectID start, ObjectID last, T* data) { if (last < start) { throw cirrus::Exception("Last objectID for get_bulk must be greater " "than start objectID."); } const int numObjects = last - start + 1; for (int i = 0; i < numObjects; i++) { data[i] = get(start + i); } } /** * Puts many objects to the remote store at once. * @param start the objectID that should be assigned to the first object * @param the objectID that should be assigned to the last object * @param data a pointer the first object in a c style array that will * be put to the remote store. */ template<class T> void CacheManager<T>::put_bulk(ObjectID start, ObjectID last, T* data) { if (last < start) { throw cirrus::Exception("Last objectID for put_bulk must be greater " "than start objectID."); } const int numObjects = last - start + 1; for (int i = 0; i < numObjects; i++) { put(start + i, data[i]); } } /** * A function that fetches an object from the remote server and stores it in * the cache, but does not return the object. Should be called in advance of * the object being accessed in order to reduce latency. If object is already * in the cache, no call will be made to the remote server. * @param oid the ObjectID that the object you wish to retrieve is stored * under. */ template<class T> void CacheManager<T>::prefetch(ObjectID oid) { std::vector<ObjectID> to_remove = eviction_policy->prefetch(oid); evict_vector(to_remove); LOG<INFO>("Prefetching oid: ", oid); // Check if it exists locally before calling the store method if (cache.find(oid) == cache.end()) { struct cache_entry& entry = cache[oid]; entry.cached = false; entry.future = store->get_async(oid); } } /** * Removes the cache entry corresponding to oid from the cache. * Throws an error if it is not present. * @param oid the ObjectID corresponding to the object to remove. */ template<class T> void CacheManager<T>::remove(ObjectID oid) { // Call remove on store first. Exception will be thrown if oid nonexistent. store->remove(oid); auto it = cache.find(oid); if (it != cache.end()) { cache.erase(it); } eviction_policy->remove(oid); } /** * Prefetches a range of objects. * @param first the first ObjectID to prefetch * @param last the last ObjectID to prefetch */ template<class T> void CacheManager<T>::prefetchBulk(ObjectID first, ObjectID last) { if (first > last) { throw cirrus::Exception("Last ObjectID to prefetch must be leq first."); } for (unsigned int oid = first; oid <= last; oid++) { prefetch(oid); } } /** * Removes a range of objects from the cache. * @param first the first continuous ObjectID to be removed from the cache * @param last the last ObjectID to be removed */ template<class T> void CacheManager<T>::removeBulk(ObjectID first, ObjectID last) { if (first > last) { throw cirrus::Exception("Last ObjectID to remove must be leq first."); } for (unsigned int oid = first; oid <= last; oid++) { remove(oid); } } /** * Removes the cache entry corresponding to oid from the cache. * Throws an error if it is not present. * @param oid the ObjectID corresponding to the object to remove. */ template<class T> void CacheManager<T>::evict(ObjectID oid) { auto it = cache.find(oid); if (it == cache.end()) { throw cirrus::Exception("Attempted to remove item not in cache."); } else { if (defer_writes) { // If the entry is dirty, write it to the store asynchronously // and keep track of the future. auto entry = it->second; if (entry.dirty) { pending_writes[oid] = store->put_async(oid, entry.obj); } // Clean the pending writes map if too full by // removing all operations that have completed if (pending_writes.size() > HIGH_PEND) { for (auto it = pending_writes.begin(); it != pending_writes.end(); it++) { auto future = it->second; if (future.try_wait()) { it = pending_writes.erase(it); } } } } cache.erase(it); } } /** * Removes the cache entry corresponding to each oid in the vector passed in. * @param to_remove an std::vector of ids corresponding to the objects * to remove. */ template<class T> void CacheManager<T>::evict_vector(const std::vector<ObjectID>& to_remove) { for (auto const& oid : to_remove) { evict(oid); } } /** * Sets the prefetching mode for the cache. The default is no prefetching. * Note: Ordered prefetching can only be used if all objectIDs are sequential. * Using ordered prefetching when IDs are not sequential will result in errors. * Note: Cache/Store contents should not be modified (no put or remove) while * the ordered iterator is in use as this could cause issues. Disable the * iterator before making changes. */ template<class T> void CacheManager<T>::setMode(CacheManager::PrefetchMode mode, cirrus::PrefetchPolicy<T> *policy) { // Set the mode switch (mode) { case CacheManager::PrefetchMode::kNone: { // Set policy to the off policy prefetch_policy = &off_policy; break; } case CacheManager::PrefetchMode::kOrdered: { throw cirrus::Exception("Ordered prefetching " "specified without a range and read ahead."); } case CacheManager::PrefetchMode::kCustom: { if (policy == nullptr) { throw cirrus::Exception("Custom mode specified without a policy."); } prefetch_policy = policy; break; } default: { throw cirrus::Exception("Unrecognized prefetch mode during setMode()."); } } } /** * Variant of setMode that is only used for switching to Ordered mode. * @param mode the mode to switch to. This should be kOrdered. * @param first the first continuous objectID in a range that prefetching will * loop over. * @param last the last continuous objectID in the above range. * @param read_ahead how many items ahead the cache should prefetch. */ template<class T> void CacheManager<T>::setMode(CacheManager::PrefetchMode mode, ObjectID first, ObjectID last, uint64_t read_ahead) { switch (mode) { case CacheManager::PrefetchMode::kOrdered: { if (first > last) { throw cirrus::Exception("Last oid must be >= first"); } ordered_policy.setRange(first, last); ordered_policy.setReadAhead(read_ahead); prefetch_policy = &ordered_policy; break; } default: { throw cirrus::Exception("First/last/read_ahead arguments passed for " "nonordered policy."); } } } } // namespace cirrus #endif // SRC_CACHE_MANAGER_CACHEMANAGER_H_
34.702359
80
0.620104
[ "object", "vector" ]
cd17e846a63bbd95ebf8b9f65f9f3d4826b4d6fa
4,978
h
C
Code/Components/Services/ingest/current/ingestpipeline/simplemonitortask/SimpleMonitorTask.h
rtobar/askapsoft
6bae06071d7d24f41abe3f2b7f9ee06cb0a9445e
[ "BSL-1.0", "Apache-2.0", "OpenSSL" ]
1
2020-06-18T08:37:43.000Z
2020-06-18T08:37:43.000Z
Code/Components/Services/ingest/current/ingestpipeline/simplemonitortask/SimpleMonitorTask.h
ATNF/askapsoft
d839c052d5c62ad8a511e58cd4b6548491a6006f
[ "BSL-1.0", "Apache-2.0", "OpenSSL" ]
null
null
null
Code/Components/Services/ingest/current/ingestpipeline/simplemonitortask/SimpleMonitorTask.h
ATNF/askapsoft
d839c052d5c62ad8a511e58cd4b6548491a6006f
[ "BSL-1.0", "Apache-2.0", "OpenSSL" ]
null
null
null
/// @file SimpleMonitorTask.cc /// /// @copyright (c) 2010 CSIRO /// Australia Telescope National Facility (ATNF) /// Commonwealth Scientific and Industrial Research Organisation (CSIRO) /// PO Box 76, Epping NSW 1710, Australia /// atnf-enquiries@csiro.au /// /// This file is part of the ASKAP software distribution. /// /// The ASKAP software distribution is free software: you can redistribute it /// and/or modify it under the terms of the GNU General Public License as /// published by the Free Software Foundation; either version 2 of the License, /// or (at your option) any later version. /// /// This program is distributed in the hope that it will be useful, /// but WITHOUT ANY WARRANTY; without even the implied warranty of /// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the /// GNU General Public License for more details. /// /// You should have received a copy of the GNU General Public License /// along with this program; if not, write to the Free Software /// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA /// /// @author Max Voronkov <maxim.voronkov@csiro.au> #ifndef ASKAP_CP_INGEST_SIMPLEMONITORTASK_H #define ASKAP_CP_INGEST_SIMPLEMONITORTASK_H // ASKAPsoft includes #include "Common/ParameterSet.h" #include "cpcommon/VisChunk.h" #include "utils/DelayEstimator.h" // casa includes #include <casacore/casa/Arrays/Matrix.h> // Local package includes #include "ingestpipeline/ITask.h" #include "configuration/Configuration.h" // Includes all configuration attributes too #include "configuration/BaselineMap.h" // std includes #include <fstream> #include <string> namespace askap { namespace cp { namespace ingest { /// @brief task for monitoring average data properties /// @details This task is intended to be used in early commissioning experiments. /// It is an alternative diagnostics to check the average amplitude, phase and /// delay for the subset of data managed by this particular rank (in the way /// similar to software correlator). This class is not intended to survive /// in its current form in the long term. class SimpleMonitorTask : public askap::cp::ingest::ITask { public: /// @brief Constructor /// @param[in] parset the configuration parameter set. /// @param[in] config configuration SimpleMonitorTask(const LOFAR::ParameterSet& parset, const Configuration& config); /// @brief destructor ~SimpleMonitorTask(); /// @brief Extract required information from visibilities in the specified VisChunk. /// @details There is no modification of the data, just internal buffers are updated. /// /// @param[in,out] chunk the instance of VisChunk for which the /// phase factors will be applied. virtual void process(askap::cp::common::VisChunk::ShPtr& chunk); protected: /// @details Process one row of data. /// @param[in] vis vis spectrum for the given baseline/pol index to work with /// @param[in] flag flag spectrum for the given baseline/pol index to work with /// @param[in] baseline baseline ID /// @param[in] beam beam ID void processRow(const casa::Vector<casa::Complex> &vis, const casa::Vector<casa::Bool> &flag, const casa::uInt baseline, const casa::uInt beam); /// @brief Publish the buffer void publishBuffer(); private: /// @brief time corresponding to the active buffer double itsCurrentTime; /// @brief time of the first data point (or a negative value upon initialisation) double itsStartTime; /// @brief buffer for averaged visibility for each baseline/polarisation index and beam casa::Matrix<casa::Complex> itsVisBuffer; /// @brief buffer for delay for each baseline/polarisation index and beam casa::Matrix<casa::Double> itsDelayBuffer; /// @brief baselines/polarisation indices to monitor /// @details One can setup a subset of baselines to monitor. In particular, /// the current form of monitoring is not very suitable for cross-pols. /// The mapping is setup the same way as for the main baseline map, but /// parset prefixes are different, for example: /// /// tasks.SimpleMonitor.params.baselineids = [0] /// tasks.SimpleMonitor.params.0 = [1,2,XX] /// BaselineMap itsBaselineMap; /// @brief delay estimator scimath::DelayEstimator itsDelayEstimator; /// @brief output file stream for time series std::ofstream itsOStream; /// @brief output file name std::string itsFileName; /// @brief rank of this ingest process int itsRank; }; // PhaseTrackTask class } // ingest } // cp } // askap #endif // #ifndef ASKAP_CP_INGEST_SIMPLEMONITORTASK_H
37.428571
95
0.675372
[ "vector" ]
cd1e1b9b102f7f8048cc4770ebb3b05723472fda
832
h
C
Pods/LRMocky/Classes/LRMocky/LRPerformBlockArgumentAction.h
sger/Tinylog-iOS
7688935cbca0eb32b0cc5f13f77776ffea3ce828
[ "MIT" ]
33
2016-01-15T18:12:09.000Z
2022-02-10T16:50:39.000Z
Pods/LRMocky/Classes/LRMocky/LRPerformBlockArgumentAction.h
sger/Tinylog-iOS
7688935cbca0eb32b0cc5f13f77776ffea3ce828
[ "MIT" ]
2
2016-04-19T00:28:12.000Z
2021-01-02T18:52:28.000Z
Pods/LRMocky/Classes/LRMocky/LRPerformBlockArgumentAction.h
sger/Tinylog-iOS
7688935cbca0eb32b0cc5f13f77776ffea3ce828
[ "MIT" ]
17
2016-03-11T17:58:23.000Z
2022-02-10T16:50:44.000Z
// // LRPerformBlockArgumentAction.h // Mocky // // Created by Luke Redpath on 30/08/2010. // Copyright 2010 LJR Software Limited. All rights reserved. // #import <Foundation/Foundation.h> #import "LRExpectationAction.h" @interface LRPerformBlockArgumentAction : NSObject <LRExpectationAction> { id object; } - (id)initWithObject:(id)anObject; @end LRPerformBlockArgumentAction *LRA_performBlockArguments(); LRPerformBlockArgumentAction *LRA_performBlockArgumentsWithObject(id object); #ifdef LRMOCKY_SHORTHAND #define performBlockArguments LRA_performBlockArguments() #define performsBlockArguments LRA_performBlockArguments() #define performBlockArgumentsWithObject(object) LRA_performBlockArgumentsWithObject(object) #define performsBlockArgumentsWithObject(object) LRA_performBlockArgumentsWithObject(object) #endif
29.714286
92
0.830529
[ "object" ]
cd282b2ef98345d6f0ba201d20e57fa548478814
2,035
h
C
MelodiUS/include/recorder.h
Solide-Performance/MelodiUS
dd1cd1cae5886bd94e2ff6db4a5e8e42bfdeb830
[ "Beerware" ]
2
2021-02-13T19:33:30.000Z
2021-07-29T14:50:19.000Z
MelodiUS/include/recorder.h
Solide-Performance/MelodiUS
dd1cd1cae5886bd94e2ff6db4a5e8e42bfdeb830
[ "Beerware" ]
1
2021-04-07T16:56:53.000Z
2021-04-07T22:41:14.000Z
MelodiUS/include/recorder.h
Solide-Performance/MelodiUS
dd1cd1cae5886bd94e2ff6db4a5e8e42bfdeb830
[ "Beerware" ]
1
2021-02-13T19:34:23.000Z
2021-02-13T19:34:23.000Z
#pragma once /*****************************************************************************/ /* Includes ---------------------------------------------------------------- */ #include "globaldef.h" #include "recording.h" /*****************************************************************************/ /* Constants --------------------------------------------------------------- */ constexpr size_t SAMPLE_RATE = 44100; constexpr size_t FRAMES_PER_BUFFER = 512; constexpr size_t NUM_CHANNELS = 2; constexpr size_t NUM_SECONDS = 60; /* #define DITHER_FLAG (paDitherOff) */ constexpr bool DITHER_FLAG = false; /* clang-format off */ static std::function<bool()> EMPTY_STOP_POLICY{}; static std::function<bool()> TRUE_STOP_POLICY{[]{ return true; }}; /* clang-format on */ /*****************************************************************************/ /* Type definitions -------------------------------------------------------- */ using recorderException = std::exception; struct paTestData { size_t frameIndex; /* Index into sample array. */ size_t maxFrameIndex; SAMPLE* recordedSamples; }; /*****************************************************************************/ /* Function declarations --------------------------------------------------- */ [[nodiscard]] Recording Record(size_t numSeconds = NUM_SECONDS, size_t sampleRate = SAMPLE_RATE, size_t framesPerBuffer = FRAMES_PER_BUFFER, size_t numChannels = NUM_CHANNELS); void Recording_SetStopPolicy(const std::function<bool()>& newPolicy); [[nodiscard]] std::vector<short> Samples_FloatToShort(const std::vector<float>& inVec); [[nodiscard]] std::vector<float> Samples_ShortToFloat(const std::vector<short>& inVec); /*****************************************************************************/ /* END OF FILE ------------------------------------------------------------- */
40.7
88
0.42113
[ "vector" ]