hexsha stringlengths 40 40 | size int64 7 1.05M | ext stringclasses 13 values | lang stringclasses 1 value | max_stars_repo_path stringlengths 4 269 | max_stars_repo_name stringlengths 5 108 | max_stars_repo_head_hexsha stringlengths 40 40 | max_stars_repo_licenses listlengths 1 9 | max_stars_count float64 1 191k ⌀ | max_stars_repo_stars_event_min_datetime stringlengths 24 24 ⌀ | max_stars_repo_stars_event_max_datetime stringlengths 24 24 ⌀ | max_issues_repo_path stringlengths 4 269 | max_issues_repo_name stringlengths 5 116 | max_issues_repo_head_hexsha stringlengths 40 40 | max_issues_repo_licenses listlengths 1 9 | max_issues_count float64 1 77k ⌀ | max_issues_repo_issues_event_min_datetime stringlengths 24 24 ⌀ | max_issues_repo_issues_event_max_datetime stringlengths 24 24 ⌀ | max_forks_repo_path stringlengths 4 269 | max_forks_repo_name stringlengths 5 116 | max_forks_repo_head_hexsha stringlengths 40 40 | max_forks_repo_licenses listlengths 1 9 | max_forks_count float64 1 105k ⌀ | max_forks_repo_forks_event_min_datetime stringlengths 24 24 ⌀ | max_forks_repo_forks_event_max_datetime stringlengths 24 24 ⌀ | content stringlengths 7 1.05M | avg_line_length float64 1.21 653k | max_line_length int64 6 990k | alphanum_fraction float64 0.01 1 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
af3684c70243779d4f462636a73078db6e072682 | 2,950 | cpp | C++ | Common/zoneview.cpp | dcliche/studioengine | 1a18d373b26575b040d014ae2650a1aaeb208a89 | [
"Apache-2.0"
] | null | null | null | Common/zoneview.cpp | dcliche/studioengine | 1a18d373b26575b040d014ae2650a1aaeb208a89 | [
"Apache-2.0"
] | null | null | null | Common/zoneview.cpp | dcliche/studioengine | 1a18d373b26575b040d014ae2650a1aaeb208a89 | [
"Apache-2.0"
] | null | null | null | //
// zoneview.cpp
// MelobaseStation
//
// Created by Daniel Cliche on 2016-02-08.
// Copyright (c) 2016-2021 Daniel Cliche. All rights reserved.
//
#include "zoneview.h"
using namespace MDStudio;
// ---------------------------------------------------------------------------------------------------------------------
ZoneView::ZoneView(std::string name, void* owner, int zone) : View(name, owner) {
_channel = zone;
std::vector<Any> items;
for (int i = 0; i < STUDIO_MAX_CHANNELS; ++i) items.push_back(std::to_string(i + 1));
_channelSegmentedControl = std::make_shared<MDStudio::SegmentedControl>("channelSegmentedControl", this, items);
_channelSegmentedControl->setFont(SystemFonts::sharedInstance()->semiboldFontSmall());
addSubview(_channelSegmentedControl);
_channelSegmentedControl->setSelectedSegment(_channel);
_transposeLabelImage = std::make_shared<Image>("TransposeLabel@2x.png");
_transposeLabelImageView = std::make_shared<ImageView>("transposeLabelImageView", this, _transposeLabelImage);
_transposeBoxView = std::make_shared<BoxView>("transposeBoxView", this);
_transposeLabelView = std::make_shared<LabelView>("transposeLabelView", this, "0");
_transposeStepper = std::make_shared<Stepper>("transposeStepper", this, 12, -48, 48, 0);
_studioChannelView = std::make_shared<StudioChannelView>("studioChannelView", this, _channel);
addSubview(_studioChannelView);
addSubview(_transposeBoxView);
addSubview(_transposeLabelView);
addSubview(_transposeStepper);
addSubview(_transposeLabelImageView);
}
// ---------------------------------------------------------------------------------------------------------------------
ZoneView::~ZoneView() {}
// ---------------------------------------------------------------------------------------------------------------------
void ZoneView::setFrame(Rect aRect) {
View::setFrame(aRect);
MDStudio::Rect r = bounds();
r.origin.x = 60.0f;
r.origin.y = r.size.height - 18.0f;
r.size.height = 16.0f;
r.size.width -= 60.0f;
r = MDStudio::makeCenteredRectInRect(r, STUDIO_MAX_CHANNELS * 20.0f, 16.0f);
_channelSegmentedControl->setFrame(r);
MDStudio::Rect r2 = MDStudio::makeCenteredRectInRect(
makeRect(0.0f, 0.0f, bounds().size.width, bounds().size.height - r.size.height), 440.0f, 140.0f);
auto r3 = r2;
if (r3.origin.x < 0.0f) r3.origin.x = 0.0f;
_transposeStepper->setFrame(makeRect(r3.origin.x + 0.0f, r3.origin.y + 40.0f, 20.0f, 30.0f));
_transposeBoxView->setFrame(makeRect(r3.origin.x + 20.0f, r3.origin.y + 40.0f, 40.0f, 30.0f));
_transposeLabelView->setFrame(makeInsetRect(_transposeBoxView->frame(), 5, 5));
_transposeLabelImageView->setFrame(makeRect(r3.origin.x, r3.origin.y + 30.0f + 40.0f, 60.0f, 20.0f));
_studioChannelView->setFrame(makeRect(r2.origin.x + 60.0f, r2.origin.y, r2.size.width - 60.0f, r2.size.height));
}
| 42.142857 | 120 | 0.622034 |
af36e438fb8bc750c09a5beb82ddfcc6c7a64cac | 3,668 | cpp | C++ | 3rdparty/webkit/Source/WebCore/platform/graphics/cairo/GradientCairo.cpp | mchiasson/PhaserNative | f867454602c395484bf730a7c43b9c586c102ac2 | [
"MIT"
] | 1 | 2020-05-25T16:06:49.000Z | 2020-05-25T16:06:49.000Z | WebLayoutCore/Source/WebCore/platform/graphics/cairo/GradientCairo.cpp | gubaojian/trylearn | 74dd5c6c977f8d867d6aa360b84bc98cb82f480c | [
"MIT"
] | null | null | null | WebLayoutCore/Source/WebCore/platform/graphics/cairo/GradientCairo.cpp | gubaojian/trylearn | 74dd5c6c977f8d867d6aa360b84bc98cb82f480c | [
"MIT"
] | 1 | 2018-07-10T10:53:18.000Z | 2018-07-10T10:53:18.000Z | /*
* Copyright (C) 2006, 2007, 2008 Apple Inc. All rights reserved.
* Copyright (C) 2007 Alp Toker <alp@atoker.com>
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY APPLE INC. ``AS IS'' AND ANY
* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
* PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR
* CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
* EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
* PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
* PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
* OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#include "config.h"
#include "Gradient.h"
#if USE(CAIRO)
#include "CairoOperations.h"
#include "CairoUtilities.h"
#include "GraphicsContext.h"
#include "PlatformContextCairo.h"
namespace WebCore {
void Gradient::platformDestroy()
{
}
cairo_pattern_t* Gradient::createPlatformGradient(float globalAlpha)
{
cairo_pattern_t* gradient = WTF::switchOn(m_data,
[&] (const LinearData& data) -> cairo_pattern_t* {
return cairo_pattern_create_linear(data.point0.x(), data.point0.y(), data.point1.x(), data.point1.y());
},
[&] (const RadialData& data) -> cairo_pattern_t* {
return cairo_pattern_create_radial(data.point0.x(), data.point0.y(), data.startRadius, data.point1.x(), data.point1.y(), data.endRadius);
}
);
for (const auto& stop : m_stops) {
if (stop.color.isExtended()) {
cairo_pattern_add_color_stop_rgba(gradient, stop.offset, stop.color.asExtended().red(), stop.color.asExtended().green(), stop.color.asExtended().blue(),
stop.color.asExtended().alpha() * globalAlpha);
} else {
float r, g, b, a;
stop.color.getRGBA(r, g, b, a);
cairo_pattern_add_color_stop_rgba(gradient, stop.offset, r, g, b, a * globalAlpha);
}
}
switch (m_spreadMethod) {
case SpreadMethodPad:
cairo_pattern_set_extend(gradient, CAIRO_EXTEND_PAD);
break;
case SpreadMethodReflect:
cairo_pattern_set_extend(gradient, CAIRO_EXTEND_REFLECT);
break;
case SpreadMethodRepeat:
cairo_pattern_set_extend(gradient, CAIRO_EXTEND_REPEAT);
break;
}
cairo_matrix_t matrix = toCairoMatrix(m_gradientSpaceTransformation);
cairo_matrix_invert(&matrix);
cairo_pattern_set_matrix(gradient, &matrix);
return gradient;
}
void Gradient::fill(GraphicsContext& context, const FloatRect& rect)
{
ASSERT(context.hasPlatformContext());
auto& platformContext = *context.platformContext();
RefPtr<cairo_pattern_t> platformGradient = adoptRef(createPlatformGradient(1.0));
Cairo::save(platformContext);
Cairo::fillRect(platformContext, rect, platformGradient.get());
Cairo::restore(platformContext);
}
} // namespace WebCore
#endif // USE(CAIRO)
| 37.428571 | 164 | 0.709378 |
af3c5d944ca4f879ea6d4365e1365e221f69cde7 | 45,136 | cpp | C++ | amd_femfx/src/FindContacts/FEMFXMeshCollision.cpp | UnifiQ/FEMFX | 95cf656731a2465ae1d400138170af2d6575b5bb | [
"MIT"
] | 418 | 2019-12-16T10:36:42.000Z | 2022-03-27T02:46:08.000Z | amd_femfx/src/FindContacts/FEMFXMeshCollision.cpp | UnifiQ/FEMFX | 95cf656731a2465ae1d400138170af2d6575b5bb | [
"MIT"
] | 15 | 2019-12-16T15:39:29.000Z | 2021-12-02T15:45:21.000Z | amd_femfx/src/FindContacts/FEMFXMeshCollision.cpp | UnifiQ/FEMFX | 95cf656731a2465ae1d400138170af2d6575b5bb | [
"MIT"
] | 54 | 2019-12-16T12:33:18.000Z | 2022-02-27T16:33:28.000Z | /*
MIT License
Copyright (c) 2019 Advanced Micro Devices, Inc.
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.
*/
//---------------------------------------------------------------------------------------
// BVH traversal operations to find contacts between FEM surface-triangle meshes, and
// operations to test for nearest or intersected tets of rest-state meshes
//---------------------------------------------------------------------------------------
#include "AMD_FEMFX.h"
#include "FEMFXBvhBuild.h"
#include "FEMFXTetMesh.h"
#include "FEMFXTriCcd.h"
#include "FEMFXTriIntersection.h"
#include "FEMFXCollisionPairData.h"
#include "FEMFXFindContacts.h"
namespace AMD
{
struct FmClosestTetResult;
struct FmConstraintsBuffer;
void FmFitLeafAabbs(FmTetMesh* tetMesh, float timestep, float padding)
{
FmBvh& bvh = tetMesh->bvh;
uint numExteriorFaces = tetMesh->numExteriorFaces;
bvh.numPrims = numExteriorFaces;
if (numExteriorFaces == 0)
{
return;
}
FmVector3 minPosition = tetMesh->vertsPos[0];
FmVector3 maxPosition = tetMesh->vertsPos[0];
for (uint exteriorFaceId = 0; exteriorFaceId < numExteriorFaces; exteriorFaceId++)
{
FmExteriorFace& exteriorFace = tetMesh->exteriorFaces[exteriorFaceId];
FmTetVertIds tetVerts = tetMesh->tetsVertIds[exteriorFace.tetId];
FmFaceVertIds faceVerts;
FmGetFaceVertIds(&faceVerts, exteriorFace.faceId, tetVerts);
FmVector3 pos0 = tetMesh->vertsPos[faceVerts.ids[0]];
FmVector3 pos1 = tetMesh->vertsPos[faceVerts.ids[1]];
FmVector3 pos2 = tetMesh->vertsPos[faceVerts.ids[2]];
FmVector3 vel0 = tetMesh->vertsVel[faceVerts.ids[0]];
FmVector3 vel1 = tetMesh->vertsVel[faceVerts.ids[1]];
FmVector3 vel2 = tetMesh->vertsVel[faceVerts.ids[2]];
minPosition = min(minPosition, pos0);
maxPosition = max(maxPosition, pos0);
minPosition = min(minPosition, pos1);
maxPosition = max(maxPosition, pos1);
minPosition = min(minPosition, pos2);
maxPosition = max(maxPosition, pos2);
FmTri tri;
tri.pos0 = pos0;
tri.pos1 = pos1;
tri.pos2 = pos2;
tri.vel0 = vel0;
tri.vel1 = vel1;
tri.vel2 = vel2;
FmAabb aabb = FmComputeTriAabb(tri, timestep, padding);
bvh.primBoxes[exteriorFaceId] = aabb;
}
tetMesh->minPosition = minPosition;
tetMesh->maxPosition = maxPosition;
}
// For CCD, must build after integration computes new velocities.
void FmBuildHierarchy(FmTetMesh* tetMesh, float timestep, float gap)
{
FM_TRACE_SCOPED_EVENT(REBUILD_BVH);
FmFitLeafAabbs(tetMesh, timestep, gap);
FmBuildBvhOnLeaves(&tetMesh->bvh, tetMesh->minPosition, tetMesh->maxPosition);
}
// Fit leaves on rest position tets of a constructed TetMesh
void FmFitLeafAabbsOnRestTets(FmBvh* outBvh, FmVector3* tetMeshMinPos, FmVector3* tetMeshMaxPos, const FmTetMesh& tetMesh)
{
FmBvh& bvh = *outBvh;
uint numTets = tetMesh.numTets;
bvh.numPrims = numTets;
if (numTets == 0)
{
*tetMeshMinPos = FmInitVector3(0.0);
*tetMeshMaxPos = FmInitVector3(0.0);
return;
}
FmVector3 meshMinPos = tetMesh.vertsRestPos[0];
FmVector3 meshMaxPos = tetMesh.vertsRestPos[0];
for (uint tetId = 0; tetId < numTets; tetId++)
{
FmTetVertIds tetVerts = tetMesh.tetsVertIds[tetId];
FmVector3 pos0 = tetMesh.vertsRestPos[tetVerts.ids[0]];
FmVector3 pos1 = tetMesh.vertsRestPos[tetVerts.ids[1]];
FmVector3 pos2 = tetMesh.vertsRestPos[tetVerts.ids[2]];
FmVector3 pos3 = tetMesh.vertsRestPos[tetVerts.ids[3]];
FmVector3 minPos = pos0;
FmVector3 maxPos = pos0;
minPos = min(minPos, pos1);
maxPos = max(maxPos, pos1);
minPos = min(minPos, pos2);
maxPos = max(maxPos, pos2);
minPos = min(minPos, pos3);
maxPos = max(maxPos, pos3);
meshMinPos = min(meshMinPos, pos0);
meshMaxPos = max(meshMaxPos, pos0);
meshMinPos = min(meshMinPos, pos1);
meshMaxPos = max(meshMaxPos, pos1);
meshMinPos = min(meshMinPos, pos2);
meshMaxPos = max(meshMaxPos, pos2);
meshMinPos = min(meshMinPos, pos3);
meshMaxPos = max(meshMaxPos, pos3);
FmAabb aabb;
aabb.pmin = minPos;
aabb.pmax = maxPos;
aabb.vmin = FmInitVector3(0.0f);
aabb.vmax = FmInitVector3(0.0f);
bvh.primBoxes[tetId] = aabb;
}
*tetMeshMinPos = meshMinPos;
*tetMeshMaxPos = meshMaxPos;
}
// Fit leaves on rest position tets provided as array of positions and tet vertex ids.
void FmFitLeafAabbsOnRestTets(
FmBvh* outBvh, FmVector3* tetMeshMinPos, FmVector3* tetMeshMaxPos,
const FmVector3* vertRestPositions, const FmTetVertIds* tetVertIds, uint numTets)
{
FmBvh& bvh = *outBvh;
bvh.numPrims = numTets;
FmVector3 meshMinPos = vertRestPositions[0];
FmVector3 meshMaxPos = vertRestPositions[0];
for (uint tetId = 0; tetId < numTets; tetId++)
{
FmTetVertIds tetVerts = tetVertIds[tetId];
FmVector3 pos0 = vertRestPositions[tetVerts.ids[0]];
FmVector3 pos1 = vertRestPositions[tetVerts.ids[1]];
FmVector3 pos2 = vertRestPositions[tetVerts.ids[2]];
FmVector3 pos3 = vertRestPositions[tetVerts.ids[3]];
FmVector3 minPos = pos0;
FmVector3 maxPos = pos0;
minPos = min(minPos, pos1);
maxPos = max(maxPos, pos1);
minPos = min(minPos, pos2);
maxPos = max(maxPos, pos2);
minPos = min(minPos, pos3);
maxPos = max(maxPos, pos3);
meshMinPos = min(meshMinPos, pos0);
meshMaxPos = max(meshMaxPos, pos0);
meshMinPos = min(meshMinPos, pos1);
meshMaxPos = max(meshMaxPos, pos1);
meshMinPos = min(meshMinPos, pos2);
meshMaxPos = max(meshMaxPos, pos2);
meshMinPos = min(meshMinPos, pos3);
meshMaxPos = max(meshMaxPos, pos3);
FmAabb aabb;
aabb.pmin = minPos;
aabb.pmax = maxPos;
aabb.vmin = FmInitVector3(0.0f);
aabb.vmax = FmInitVector3(0.0f);
bvh.primBoxes[tetId] = aabb;
}
*tetMeshMinPos = meshMinPos;
*tetMeshMaxPos = meshMaxPos;
}
// Build BVH over rest mesh tetrahedra for nearest tetrahedron query.
// bvh expected to be preallocated for tetMesh->numTets leaves.
void FmBuildRestMeshTetBvh(FmBvh* bvh, const FmTetMesh& tetMesh)
{
FmVector3 meshMinPos, meshMaxPos;
FmFitLeafAabbsOnRestTets(bvh, &meshMinPos, &meshMaxPos, tetMesh);
FmBuildBvhOnLeaves(bvh, meshMinPos, meshMaxPos);
}
// Build BVH over rest mesh tetrahedra for nearest tetrahedron query.
// bvh expected to be preallocated for tetMesh->numTets leaves.
void FmBuildRestMeshTetBvh(FmBvh* bvh, const FmVector3* vertRestPositions, const FmTetVertIds* tetVertIds, uint numTets)
{
FmVector3 meshMinPos, meshMaxPos;
FmFitLeafAabbsOnRestTets(bvh, &meshMinPos, &meshMaxPos, vertRestPositions, tetVertIds, numTets);
FmBuildBvhOnLeaves(bvh, meshMinPos, meshMaxPos);
}
struct FmClosestTetQueryState
{
const FmTetMesh* tetMesh; // if NULL uses vertRestPositions and tetVertIds
const FmVector3* vertRestPositions;
const FmTetVertIds* tetVertIds;
const FmBvh* bvh;
FmVector3 queryPoint;
FmVector3 closestPoint;
uint closestTetId;
uint closestFaceId;
float closestDistance;
bool insideTet;
};
static FM_FORCE_INLINE float FmPointBoxDistance(const FmVector3& queryPoint, const FmAabb& box)
{
float maxGapX = FmMaxFloat(FmMaxFloat(queryPoint.x - box.pmax.x, box.pmin.x - queryPoint.x), 0.0f);
float maxGapY = FmMaxFloat(FmMaxFloat(queryPoint.y - box.pmax.y, box.pmin.y - queryPoint.y), 0.0f);
float maxGapZ = FmMaxFloat(FmMaxFloat(queryPoint.z - box.pmax.z, box.pmin.z - queryPoint.z), 0.0f);
float distance = sqrtf(maxGapX*maxGapX + maxGapY*maxGapY + maxGapZ*maxGapZ);
return distance;
}
void FmFindClosestTetRecursive(FmClosestTetQueryState& queryState, uint idx)
{
const FmTetMesh* tetMesh = queryState.tetMesh;
const FmVector3* vertRestPositions = queryState.vertRestPositions;
const FmTetVertIds* tetVertIds = queryState.tetVertIds;
const FmBvh* hierarchy = queryState.bvh;
FmVector3 queryPoint = queryState.queryPoint;
FmBvhNode* nodes = hierarchy->nodes;
int lc = nodes[idx].left;
int rc = nodes[idx].right;
if (lc == rc)
{
// Leaf, find nearest position of tet
uint tetId = (uint)lc;
FmVector3 tetPos[4];
if (tetMesh)
{
FmTetVertIds tetVerts = tetMesh->tetsVertIds[tetId];
tetPos[0] = tetMesh->vertsRestPos[tetVerts.ids[0]];
tetPos[1] = tetMesh->vertsRestPos[tetVerts.ids[1]];
tetPos[2] = tetMesh->vertsRestPos[tetVerts.ids[2]];
tetPos[3] = tetMesh->vertsRestPos[tetVerts.ids[3]];
}
else
{
FmTetVertIds tetVerts = tetVertIds[tetId];
tetPos[0] = vertRestPositions[tetVerts.ids[0]];
tetPos[1] = vertRestPositions[tetVerts.ids[1]];
tetPos[2] = vertRestPositions[tetVerts.ids[2]];
tetPos[3] = vertRestPositions[tetVerts.ids[3]];
}
int intersectionVal = FmIntersectionX03(queryPoint, tetPos[0], tetPos[1], tetPos[2], tetPos[3]);
if (intersectionVal)
{
// Query point inside tet, can return
queryState.closestPoint = queryPoint;
queryState.closestTetId = tetId;
queryState.closestDistance = 0.0f;
queryState.insideTet = true;
return;
}
else
{
// Check tet faces for points nearer than current result
for (uint faceId = 0; faceId < 4; faceId++)
{
FmFaceVertIds tetCorners;
FmGetFaceTetCorners(&tetCorners, faceId);
FmVector3 triPos0 = tetPos[tetCorners.ids[0]];
FmVector3 triPos1 = tetPos[tetCorners.ids[1]];
FmVector3 triPos2 = tetPos[tetCorners.ids[2]];
FmDistanceResult distResult;
FmPointTriangleDistance(&distResult, queryPoint, triPos0, triPos1, triPos2, 0, 0, 1, 2);
if (distResult.distance < queryState.closestDistance)
{
queryState.closestPoint = distResult.posj;
queryState.closestTetId = tetId;
queryState.closestFaceId = faceId;
queryState.closestDistance = distResult.distance;
}
}
}
}
else
{
FmAabb& lbox = hierarchy->nodes[lc].box;
FmAabb& rbox = hierarchy->nodes[rc].box;
float ldistance = FmPointBoxDistance(queryPoint, lbox);
float rdistance = FmPointBoxDistance(queryPoint, rbox);
if (ldistance < rdistance)
{
if (ldistance < queryState.closestDistance)
{
FmFindClosestTetRecursive(queryState, (uint)lc);
}
if (rdistance < queryState.closestDistance)
{
FmFindClosestTetRecursive(queryState, (uint)rc);
}
}
else
{
if (rdistance < queryState.closestDistance)
{
FmFindClosestTetRecursive(queryState, (uint)rc);
}
if (ldistance < queryState.closestDistance)
{
FmFindClosestTetRecursive(queryState, (uint)lc);
}
}
}
}
// Find the nearest tetrahedron and nearest point and face to the query point,
// given tet mesh and BVH built with FmBuildRestMeshTetBvh.
void FmFindClosestTet(FmClosestTetResult* closestTet, const FmTetMesh* tetMesh, const FmBvh* bvh, const FmVector3& queryPoint)
{
FmClosestTetQueryState queryState;
queryState.tetMesh = tetMesh;
queryState.vertRestPositions = NULL;
queryState.tetVertIds = NULL;
queryState.bvh = bvh;
queryState.queryPoint = queryPoint;
queryState.closestPoint = FmInitVector3(0.0f);
queryState.closestDistance = FLT_MAX;
queryState.closestTetId = FM_INVALID_ID;
queryState.closestFaceId = FM_INVALID_ID;
queryState.insideTet = false;
FmFindClosestTetRecursive(queryState, 0);
closestTet->position = queryState.closestPoint;
closestTet->distance = queryState.closestDistance;
closestTet->tetId = queryState.closestTetId;
closestTet->faceId = queryState.closestFaceId;
closestTet->insideTet = queryState.insideTet;
if (queryState.closestTetId == FM_INVALID_ID)
{
FM_PRINT(("FindClosestTet: invalid mesh or hierarchy\n"));
}
else
{
FmVector4 barycentrics = mul(tetMesh->tetsShapeParams[queryState.closestTetId].baryMatrix, FmVector4(queryState.closestPoint, 1.0f));
closestTet->posBary[0] = barycentrics.x;
closestTet->posBary[1] = barycentrics.y;
closestTet->posBary[2] = barycentrics.z;
closestTet->posBary[3] = barycentrics.w;
}
}
// Find the closest tetrahedron, point and face to the query point,
// given tet mesh and BVH built with FmBuildRestMeshTetBvh.
void FmFindClosestTet(
FmClosestTetResult* closestTet,
const FmVector3* vertRestPositions, const FmTetVertIds* tetVertIds, const FmBvh* bvh,
const FmVector3& queryPoint)
{
FmClosestTetQueryState queryState;
queryState.tetMesh = NULL;
queryState.vertRestPositions = vertRestPositions;
queryState.tetVertIds = tetVertIds;
queryState.bvh = bvh;
queryState.queryPoint = queryPoint;
queryState.closestPoint = FmInitVector3(0.0f);
queryState.closestDistance = FLT_MAX;
queryState.closestTetId = FM_INVALID_ID;
queryState.closestFaceId = FM_INVALID_ID;
queryState.insideTet = false;
FmFindClosestTetRecursive(queryState, 0);
closestTet->position = queryState.closestPoint;
closestTet->distance = queryState.closestDistance;
closestTet->tetId = queryState.closestTetId;
closestTet->faceId = queryState.closestFaceId;
closestTet->insideTet = queryState.insideTet;
if (queryState.closestTetId == FM_INVALID_ID)
{
FM_PRINT(("FindClosestTet: invalid mesh or hierarchy\n"));
}
else
{
FmMatrix4 baryMatrix = FmComputeTetBarycentricMatrix(vertRestPositions, tetVertIds[closestTet->tetId]);
FmVector4 barycentrics = mul(baryMatrix, FmVector4(queryState.closestPoint, 1.0f));
closestTet->posBary[0] = barycentrics.x;
closestTet->posBary[1] = barycentrics.y;
closestTet->posBary[2] = barycentrics.z;
closestTet->posBary[3] = barycentrics.w;
}
}
void FmFindIntersectedTetRecursive(FmClosestTetQueryState& queryState, uint idx)
{
const FmTetMesh* tetMesh = queryState.tetMesh;
const FmVector3* vertRestPositions = queryState.vertRestPositions;
const FmTetVertIds* tetVertIds = queryState.tetVertIds;
const FmBvh* hierarchy = queryState.bvh;
FmVector3 queryPoint = queryState.queryPoint;
FmBvhNode* nodes = hierarchy->nodes;
FmAabb& box = hierarchy->nodes[idx].box;
if (queryPoint.x < box.pmin.x || queryPoint.x > box.pmax.x
|| queryPoint.y < box.pmin.y || queryPoint.y > box.pmax.y
|| queryPoint.z < box.pmin.z || queryPoint.z > box.pmax.z)
{
return;
}
int lc = nodes[idx].left;
int rc = nodes[idx].right;
if (lc == rc)
{
// Leaf, test intersection
uint tetId = (uint)lc;
FmVector3 tetPos[4];
if (tetMesh)
{
FmTetVertIds tetVerts = tetMesh->tetsVertIds[tetId];
tetPos[0] = tetMesh->vertsRestPos[tetVerts.ids[0]];
tetPos[1] = tetMesh->vertsRestPos[tetVerts.ids[1]];
tetPos[2] = tetMesh->vertsRestPos[tetVerts.ids[2]];
tetPos[3] = tetMesh->vertsRestPos[tetVerts.ids[3]];
}
else
{
FmTetVertIds tetVerts = tetVertIds[tetId];
tetPos[0] = vertRestPositions[tetVerts.ids[0]];
tetPos[1] = vertRestPositions[tetVerts.ids[1]];
tetPos[2] = vertRestPositions[tetVerts.ids[2]];
tetPos[3] = vertRestPositions[tetVerts.ids[3]];
}
int intersectionVal = FmIntersectionX03(queryPoint, tetPos[0], tetPos[1], tetPos[2], tetPos[3]);
if (intersectionVal)
{
// Query point inside tet, can return
queryState.closestPoint = queryPoint;
queryState.closestTetId = tetId;
queryState.closestDistance = 0.0f;
queryState.insideTet = true;
return;
}
}
else
{
FmFindIntersectedTetRecursive(queryState, (uint)lc);
FmFindIntersectedTetRecursive(queryState, (uint)rc);
}
}
// Find the nearest tetrahedron and nearest point and face to the query point,
// given tet mesh and BVH built with FmBuildRestMeshTetBvh.
void FmFindIntersectedTet(FmClosestTetResult* closestTet, const FmTetMesh* tetMesh, const FmBvh* bvh, const FmVector3& queryPoint)
{
FmClosestTetQueryState queryState;
queryState.tetMesh = tetMesh;
queryState.vertRestPositions = NULL;
queryState.tetVertIds = NULL;
queryState.bvh = bvh;
queryState.queryPoint = queryPoint;
queryState.closestPoint = FmInitVector3(0.0f);
queryState.closestDistance = FLT_MAX;
queryState.closestTetId = FM_INVALID_ID;
queryState.closestFaceId = FM_INVALID_ID;
queryState.insideTet = false;
FmFindIntersectedTetRecursive(queryState, 0);
closestTet->position = queryState.closestPoint;
closestTet->distance = queryState.closestDistance;
closestTet->tetId = queryState.closestTetId;
closestTet->faceId = queryState.closestFaceId;
closestTet->insideTet = queryState.insideTet;
closestTet->posBary[0] = 0.0f;
closestTet->posBary[1] = 0.0f;
closestTet->posBary[2] = 0.0f;
closestTet->posBary[3] = 0.0f;
if (queryState.closestTetId != FM_INVALID_ID)
{
FmVector4 barycentrics = mul(tetMesh->tetsShapeParams[queryState.closestTetId].baryMatrix, FmVector4(queryState.closestPoint, 1.0f));
closestTet->posBary[0] = barycentrics.x;
closestTet->posBary[1] = barycentrics.y;
closestTet->posBary[2] = barycentrics.z;
closestTet->posBary[3] = barycentrics.w;
}
}
// Find the closest tetrahedron, point and face to the query point,
// given tet mesh and BVH built with FmBuildRestMeshTetBvh.
void FmFindIntersectedTet(
FmClosestTetResult* closestTet,
const FmVector3* vertRestPositions, const FmTetVertIds* tetVertIds, const FmBvh* bvh,
const FmVector3& queryPoint)
{
FmClosestTetQueryState queryState;
queryState.tetMesh = NULL;
queryState.vertRestPositions = vertRestPositions;
queryState.tetVertIds = tetVertIds;
queryState.bvh = bvh;
queryState.queryPoint = queryPoint;
queryState.closestPoint = FmInitVector3(0.0f);
queryState.closestDistance = FLT_MAX;
queryState.closestTetId = FM_INVALID_ID;
queryState.closestFaceId = FM_INVALID_ID;
queryState.insideTet = false;
FmFindIntersectedTetRecursive(queryState, 0);
closestTet->position = queryState.closestPoint;
closestTet->distance = queryState.closestDistance;
closestTet->tetId = queryState.closestTetId;
closestTet->faceId = queryState.closestFaceId;
closestTet->insideTet = queryState.insideTet;
closestTet->posBary[0] = 0.0f;
closestTet->posBary[1] = 0.0f;
closestTet->posBary[2] = 0.0f;
closestTet->posBary[3] = 0.0f;
if (queryState.closestTetId != FM_INVALID_ID)
{
FmMatrix4 baryMatrix = FmComputeTetBarycentricMatrix(vertRestPositions, tetVertIds[closestTet->tetId]);
FmVector4 barycentrics = mul(baryMatrix, FmVector4(queryState.closestPoint, 1.0f));
closestTet->posBary[0] = barycentrics.x;
closestTet->posBary[1] = barycentrics.y;
closestTet->posBary[2] = barycentrics.z;
closestTet->posBary[3] = barycentrics.w;
}
}
struct FmTetsIntersectingBoxQueryState
{
uint* tets;
uint numTets;
const FmTetMesh* tetMesh; // If NULL, use vertRestPositions and tetVertIds
const FmVector3* vertRestPositions;
const FmTetVertIds* tetVertIds;
const FmBvh* bvh;
FmVector3 boxHalfDimensions;
FmVector3 boxCenterPos;
FmMatrix3 boxRotation;
FmMatrix3 boxRotationInv;
FmVector3 boxPoints[8];
FmVector3 aabbMinPos;
FmVector3 aabbMaxPos;
};
void FmFindTetsIntersectingBoxRecursive(FmTetsIntersectingBoxQueryState& queryState, uint idx)
{
const FmTetMesh* tetMesh = queryState.tetMesh;
const FmVector3* vertRestPositions = queryState.vertRestPositions;
const FmTetVertIds* tetVertIds = queryState.tetVertIds;
const FmBvh* hierarchy = queryState.bvh;
FmBvhNode* nodes = hierarchy->nodes;
// Return if box's AABB does not intersect BVH node
FmAabb& box = hierarchy->nodes[idx].box;
if (queryState.aabbMaxPos.x < box.pmin.x || queryState.aabbMinPos.x > box.pmax.x
|| queryState.aabbMaxPos.y < box.pmin.y || queryState.aabbMinPos.y > box.pmax.y
|| queryState.aabbMaxPos.z < box.pmin.z || queryState.aabbMinPos.z > box.pmax.z)
{
return;
}
int lc = nodes[idx].left;
int rc = nodes[idx].right;
if (lc == rc)
{
// Leaf, check for intersection
uint tetId = (uint)lc;
FmVector3 tetPos[4];
if (tetMesh)
{
FmTetVertIds tetVerts = tetMesh->tetsVertIds[tetId];
tetPos[0] = tetMesh->vertsRestPos[tetVerts.ids[0]];
tetPos[1] = tetMesh->vertsRestPos[tetVerts.ids[1]];
tetPos[2] = tetMesh->vertsRestPos[tetVerts.ids[2]];
tetPos[3] = tetMesh->vertsRestPos[tetVerts.ids[3]];
}
else
{
FmTetVertIds tetVerts = tetVertIds[tetId];
tetPos[0] = vertRestPositions[tetVerts.ids[0]];
tetPos[1] = vertRestPositions[tetVerts.ids[1]];
tetPos[2] = vertRestPositions[tetVerts.ids[2]];
tetPos[3] = vertRestPositions[tetVerts.ids[3]];
}
FmVector3 tetPosBoxSpace[4];
tetPosBoxSpace[0] = mul(queryState.boxRotationInv, tetPos[0] - queryState.boxCenterPos);
tetPosBoxSpace[1] = mul(queryState.boxRotationInv, tetPos[1] - queryState.boxCenterPos);
tetPosBoxSpace[2] = mul(queryState.boxRotationInv, tetPos[2] - queryState.boxCenterPos);
tetPosBoxSpace[3] = mul(queryState.boxRotationInv, tetPos[3] - queryState.boxCenterPos);
bool intersecting = false;
// Check for box points inside tet
for (uint boxPntIdx = 0; boxPntIdx < 8; boxPntIdx++)
{
if (FmIntersectionX30(tetPosBoxSpace[0], tetPosBoxSpace[1], tetPosBoxSpace[2], tetPosBoxSpace[3], queryState.boxPoints[boxPntIdx]))
{
intersecting = true;
break;
}
}
// Check for tet points inside box
if (!intersecting)
{
FmVector3 halfDims = queryState.boxHalfDimensions;
for (uint tetPntIdx = 0; tetPntIdx < 4; tetPntIdx++)
{
if (tetPosBoxSpace[tetPntIdx].x >= -halfDims.x && tetPosBoxSpace[tetPntIdx].x <= halfDims.x
&& tetPosBoxSpace[tetPntIdx].y >= -halfDims.y && tetPosBoxSpace[tetPntIdx].y <= halfDims.y
&& tetPosBoxSpace[tetPntIdx].z >= -halfDims.z && tetPosBoxSpace[tetPntIdx].z <= halfDims.z)
{
intersecting = true;
}
}
}
// Test for edges intersecting faces
if (!intersecting)
{
for (uint tvi = 0; tvi < 4; tvi++)
{
FmVector3 intersectionPnt;
FmVector3 tetEdgePosi = tetPosBoxSpace[tvi];
for (uint tvj = tvi + 1; tvj < 4; tvj++)
{
FmVector3 tetEdgePosj = tetPosBoxSpace[tvj];
if (FmIntersectionX12(&intersectionPnt, tetEdgePosi, tetEdgePosj, queryState.boxPoints[0], queryState.boxPoints[2], queryState.boxPoints[1])) { intersecting = true; break; }
if (FmIntersectionX12(&intersectionPnt, tetEdgePosi, tetEdgePosj, queryState.boxPoints[1], queryState.boxPoints[2], queryState.boxPoints[3])) { intersecting = true; break; }
if (FmIntersectionX12(&intersectionPnt, tetEdgePosi, tetEdgePosj, queryState.boxPoints[0], queryState.boxPoints[1], queryState.boxPoints[4])) { intersecting = true; break; }
if (FmIntersectionX12(&intersectionPnt, tetEdgePosi, tetEdgePosj, queryState.boxPoints[4], queryState.boxPoints[1], queryState.boxPoints[5])) { intersecting = true; break; }
if (FmIntersectionX12(&intersectionPnt, tetEdgePosi, tetEdgePosj, queryState.boxPoints[1], queryState.boxPoints[3], queryState.boxPoints[5])) { intersecting = true; break; }
if (FmIntersectionX12(&intersectionPnt, tetEdgePosi, tetEdgePosj, queryState.boxPoints[5], queryState.boxPoints[3], queryState.boxPoints[7])) { intersecting = true; break; }
if (FmIntersectionX12(&intersectionPnt, tetEdgePosi, tetEdgePosj, queryState.boxPoints[0], queryState.boxPoints[4], queryState.boxPoints[2])) { intersecting = true; break; }
if (FmIntersectionX12(&intersectionPnt, tetEdgePosi, tetEdgePosj, queryState.boxPoints[2], queryState.boxPoints[4], queryState.boxPoints[6])) { intersecting = true; break; }
if (FmIntersectionX12(&intersectionPnt, tetEdgePosi, tetEdgePosj, queryState.boxPoints[4], queryState.boxPoints[5], queryState.boxPoints[6])) { intersecting = true; break; }
if (FmIntersectionX12(&intersectionPnt, tetEdgePosi, tetEdgePosj, queryState.boxPoints[6], queryState.boxPoints[5], queryState.boxPoints[7])) { intersecting = true; break; }
if (FmIntersectionX12(&intersectionPnt, tetEdgePosi, tetEdgePosj, queryState.boxPoints[2], queryState.boxPoints[6], queryState.boxPoints[3])) { intersecting = true; break; }
if (FmIntersectionX12(&intersectionPnt, tetEdgePosi, tetEdgePosj, queryState.boxPoints[3], queryState.boxPoints[6], queryState.boxPoints[7])) { intersecting = true; break; }
}
FmFaceVertIds tetCorners;
FmGetFaceTetCorners(&tetCorners, tvi);
FmVector3 triPos0 = tetPosBoxSpace[tetCorners.ids[0]];
FmVector3 triPos1 = tetPosBoxSpace[tetCorners.ids[1]];
FmVector3 triPos2 = tetPosBoxSpace[tetCorners.ids[2]];
if (FmIntersectionX21(&intersectionPnt, triPos0, triPos1, triPos2, queryState.boxPoints[0], queryState.boxPoints[1])) { intersecting = true; break; }
if (FmIntersectionX21(&intersectionPnt, triPos0, triPos1, triPos2, queryState.boxPoints[2], queryState.boxPoints[3])) { intersecting = true; break; }
if (FmIntersectionX21(&intersectionPnt, triPos0, triPos1, triPos2, queryState.boxPoints[4], queryState.boxPoints[5])) { intersecting = true; break; }
if (FmIntersectionX21(&intersectionPnt, triPos0, triPos1, triPos2, queryState.boxPoints[6], queryState.boxPoints[7])) { intersecting = true; break; }
if (FmIntersectionX21(&intersectionPnt, triPos0, triPos1, triPos2, queryState.boxPoints[0], queryState.boxPoints[2])) { intersecting = true; break; }
if (FmIntersectionX21(&intersectionPnt, triPos0, triPos1, triPos2, queryState.boxPoints[1], queryState.boxPoints[3])) { intersecting = true; break; }
if (FmIntersectionX21(&intersectionPnt, triPos0, triPos1, triPos2, queryState.boxPoints[4], queryState.boxPoints[6])) { intersecting = true; break; }
if (FmIntersectionX21(&intersectionPnt, triPos0, triPos1, triPos2, queryState.boxPoints[5], queryState.boxPoints[7])) { intersecting = true; break; }
if (FmIntersectionX21(&intersectionPnt, triPos0, triPos1, triPos2, queryState.boxPoints[0], queryState.boxPoints[4])) { intersecting = true; break; }
if (FmIntersectionX21(&intersectionPnt, triPos0, triPos1, triPos2, queryState.boxPoints[1], queryState.boxPoints[5])) { intersecting = true; break; }
if (FmIntersectionX21(&intersectionPnt, triPos0, triPos1, triPos2, queryState.boxPoints[2], queryState.boxPoints[6])) { intersecting = true; break; }
if (FmIntersectionX21(&intersectionPnt, triPos0, triPos1, triPos2, queryState.boxPoints[3], queryState.boxPoints[7])) { intersecting = true; break; }
}
}
if (intersecting)
{
queryState.tets[queryState.numTets] = tetId;
queryState.numTets++;
}
}
else
{
FmFindTetsIntersectingBoxRecursive(queryState, (uint)lc);
FmFindTetsIntersectingBoxRecursive(queryState, (uint)rc);
}
}
// Find all the rest mesh tetrahedra that intersect the box.
// Saves output to tetsIntersectingBox array, expected to be large enough for all tets of the mesh.
// Returns the number of intersected tets.
uint FmFindTetsIntersectingBox(
uint* tetsIntersectingBox,
const FmTetMesh* tetMesh, const FmBvh* bvh,
const FmVector3& boxHalfDimensions,
const FmVector3& boxCenterPos,
const FmMatrix3& boxRotation)
{
FmTetsIntersectingBoxQueryState queryState;
queryState.tetMesh = tetMesh;
queryState.vertRestPositions = NULL;
queryState.tetVertIds = NULL;
queryState.bvh = bvh;
queryState.boxHalfDimensions = boxHalfDimensions;
queryState.boxCenterPos = boxCenterPos;
queryState.boxRotation = boxRotation;
queryState.boxRotationInv = transpose(boxRotation);
queryState.boxPoints[0] = FmInitVector3(-boxHalfDimensions.x, -boxHalfDimensions.y, -boxHalfDimensions.z);
queryState.boxPoints[1] = FmInitVector3(boxHalfDimensions.x, -boxHalfDimensions.y, -boxHalfDimensions.z);
queryState.boxPoints[2] = FmInitVector3(-boxHalfDimensions.x, boxHalfDimensions.y, -boxHalfDimensions.z);
queryState.boxPoints[3] = FmInitVector3(boxHalfDimensions.x, boxHalfDimensions.y, -boxHalfDimensions.z);
queryState.boxPoints[4] = FmInitVector3(-boxHalfDimensions.x, -boxHalfDimensions.y, boxHalfDimensions.z);
queryState.boxPoints[5] = FmInitVector3(boxHalfDimensions.x, -boxHalfDimensions.y, boxHalfDimensions.z);
queryState.boxPoints[6] = FmInitVector3(-boxHalfDimensions.x, boxHalfDimensions.y, boxHalfDimensions.z);
queryState.boxPoints[7] = FmInitVector3(boxHalfDimensions.x, boxHalfDimensions.y, boxHalfDimensions.z);
FmVector3 absCol0 = abs(boxRotation.col0);
FmVector3 absCol1 = abs(boxRotation.col1);
FmVector3 absCol2 = abs(boxRotation.col2);
queryState.aabbMinPos = boxCenterPos - absCol0 * boxHalfDimensions.x - absCol1 * boxHalfDimensions.y - absCol2 * boxHalfDimensions.z;
queryState.aabbMaxPos = boxCenterPos + absCol0 * boxHalfDimensions.x + absCol1 * boxHalfDimensions.y + absCol2 * boxHalfDimensions.z;
queryState.tets = tetsIntersectingBox;
queryState.numTets = 0;
FmFindTetsIntersectingBoxRecursive(queryState, 0);
return queryState.numTets;
}
// Find all the rest mesh tetrahedra that intersect the box.
// Saves output to tetsIntersectingBox array, expected to be large enough for all tets of the mesh.
// Returns the number of intersected tets.
uint FmFindTetsIntersectingBox(
uint* tetsIntersectingBox,
const FmVector3* vertRestPositions, const FmTetVertIds* tetVertIds, const FmBvh* bvh,
const FmVector3& boxHalfDimensions,
const FmVector3& boxCenterPos,
const FmMatrix3& boxRotation)
{
FmTetsIntersectingBoxQueryState queryState;
queryState.tetMesh = NULL;
queryState.vertRestPositions = vertRestPositions;
queryState.tetVertIds = tetVertIds;
queryState.bvh = bvh;
queryState.boxHalfDimensions = boxHalfDimensions;
queryState.boxCenterPos = boxCenterPos;
queryState.boxRotation = boxRotation;
queryState.boxRotationInv = transpose(boxRotation);
queryState.boxPoints[0] = FmInitVector3(-boxHalfDimensions.x, -boxHalfDimensions.y, -boxHalfDimensions.z);
queryState.boxPoints[1] = FmInitVector3(boxHalfDimensions.x, -boxHalfDimensions.y, -boxHalfDimensions.z);
queryState.boxPoints[2] = FmInitVector3(-boxHalfDimensions.x, boxHalfDimensions.y, -boxHalfDimensions.z);
queryState.boxPoints[3] = FmInitVector3(boxHalfDimensions.x, boxHalfDimensions.y, -boxHalfDimensions.z);
queryState.boxPoints[4] = FmInitVector3(-boxHalfDimensions.x, -boxHalfDimensions.y, boxHalfDimensions.z);
queryState.boxPoints[5] = FmInitVector3(boxHalfDimensions.x, -boxHalfDimensions.y, boxHalfDimensions.z);
queryState.boxPoints[6] = FmInitVector3(-boxHalfDimensions.x, boxHalfDimensions.y, boxHalfDimensions.z);
queryState.boxPoints[7] = FmInitVector3(boxHalfDimensions.x, boxHalfDimensions.y, boxHalfDimensions.z);
FmVector3 absCol0 = abs(boxRotation.col0);
FmVector3 absCol1 = abs(boxRotation.col1);
FmVector3 absCol2 = abs(boxRotation.col2);
queryState.aabbMinPos = boxCenterPos - absCol0 * boxHalfDimensions.x - absCol1 * boxHalfDimensions.y - absCol2 * boxHalfDimensions.z;
queryState.aabbMaxPos = boxCenterPos + absCol0 * boxHalfDimensions.x + absCol1 * boxHalfDimensions.y + absCol2 * boxHalfDimensions.z;
queryState.tets = tetsIntersectingBox;
queryState.numTets = 0;
FmFindTetsIntersectingBoxRecursive(queryState, 0);
return queryState.numTets;
}
struct FmSceneCollisionPlanesContactsQueryState
{
FmCollidedObjectPair* objectPair;
FmSceneCollisionPlanes collisionPlanes;
};
void FmFindSceneCollisionPlanesContactsRecursive(FmSceneCollisionPlanesContactsQueryState& queryState, uint idx)
{
FmCollidedObjectPair* objectPair = queryState.objectPair;
const FmBvh* hierarchy = objectPair->objectAHierarchy;
FmSceneCollisionPlanes& collisionPlanes = queryState.collisionPlanes;
FmBvhNode* nodes = hierarchy->nodes;
float timestep = objectPair->timestep;
float distContactThreshold = objectPair->distContactThreshold;
// Return if AABB shows no potential contact
FmAabb& box = hierarchy->nodes[idx].box;
bool results[6];
float threshold = distContactThreshold * 0.5f; // distContactThreshold - AABB padding
if (!FmAabbSceneCollisionPlanesPotentialContact(results, box, collisionPlanes, timestep, threshold))
{
return;
}
int lc = nodes[idx].left;
int rc = nodes[idx].right;
if (lc == rc)
{
// Leaf, check for contact
uint exteriorFaceId = (uint)lc;
FmGenerateFaceCollisionPlaneContacts(objectPair, results, exteriorFaceId, collisionPlanes);
}
else
{
FmFindSceneCollisionPlanesContactsRecursive(queryState, (uint)lc);
FmFindSceneCollisionPlanesContactsRecursive(queryState, (uint)rc);
}
}
uint FmFindSceneCollisionPlanesContactsQuery(
FmCollidedObjectPair* objectPair,
const FmSceneCollisionPlanes& collisionPlanes)
{
uint numContactsStart = objectPair->numDistanceContacts;
FmSceneCollisionPlanesContactsQueryState queryState;
queryState.objectPair = objectPair;
queryState.collisionPlanes = collisionPlanes;
FmFindSceneCollisionPlanesContactsRecursive(queryState, 0);
return objectPair->numDistanceContacts - numContactsStart;
}
void FmCollideRecursive(FmCollidedObjectPair* objectPair, int indexA, int indexB)
{
FmBvh* hierarchyA = objectPair->objectAHierarchy;
FmBvh* hierarchyB = objectPair->objectBHierarchy;
float timestep = objectPair->timestep;
FmBvhNode* nodeA = &hierarchyA->nodes[indexA];
FmBvhNode* nodeB = &hierarchyB->nodes[indexB];
FmAabb* boxA = &hierarchyA->nodes[indexA].box;
FmAabb* boxB = &hierarchyB->nodes[indexB].box;
bool nodeAIsLeaf = nodeA->left == nodeA->right;
bool nodeBIsLeaf = nodeB->left == nodeB->right;
float impactTime;
if (FmAabbCcd(impactTime, *boxA, *boxB, timestep))
{
if (nodeAIsLeaf && nodeBIsLeaf)
{
#if FM_SOA_TRI_INTERSECTION
FmMeshCollisionTriPair& pair = objectPair->temps.meshCollisionTriPairs[objectPair->temps.numMeshCollisionTriPairs];
pair.exteriorFaceIdA = (uint)nodeA->left;
pair.exteriorFaceIdB = (uint)nodeB->left;
objectPair->temps.numMeshCollisionTriPairs++;
if (objectPair->temps.numMeshCollisionTriPairs >= FM_MAX_MESH_COLLISION_TRI_PAIR)
{
FmGenerateContactsFromMeshCollisionTriPairs(objectPair);
objectPair->temps.numMeshCollisionTriPairs = 0;
}
#else
FmGenerateContacts(objectPair, nodeA->left, nodeB->left);
#endif
}
else if (nodeAIsLeaf)
{
FmCollideRecursive(objectPair, indexA, nodeB->left);
FmCollideRecursive(objectPair, indexA, nodeB->right);
}
else if (nodeBIsLeaf)
{
FmCollideRecursive(objectPair, nodeA->left, indexB);
FmCollideRecursive(objectPair, nodeA->right, indexB);
}
else
{
float sizeA = lengthSqr(boxA->pmax - boxA->pmin);
float sizeB = lengthSqr(boxB->pmax - boxB->pmin);
// Split the larger node
if (sizeA > sizeB)
{
FmCollideRecursive(objectPair, nodeA->left, indexB);
FmCollideRecursive(objectPair, nodeA->right, indexB);
}
else
{
FmCollideRecursive(objectPair, indexA, nodeB->left);
FmCollideRecursive(objectPair, indexA, nodeB->right);
}
}
}
}
static FM_FORCE_INLINE bool FmAabbOverlapXY(const FmAabb& aabb0, const FmAabb& aabb1)
{
return
aabb0.pmin.x <= aabb1.pmax.x &&
aabb0.pmin.y <= aabb1.pmax.y &&
aabb1.pmin.x <= aabb0.pmax.x &&
aabb1.pmin.y <= aabb0.pmax.y;
}
void FmFindInsideVertsRecursive(FmCollidedObjectPair* objectPair, int indexA, int indexB, bool includeA, bool includeB)
{
FmBvh* hierarchyA = objectPair->objectAHierarchy;
FmBvh* hierarchyB = objectPair->objectBHierarchy;
FmBvhNode* nodeA = &hierarchyA->nodes[indexA];
FmBvhNode* nodeB = &hierarchyB->nodes[indexB];
FmAabb* boxA = &hierarchyA->nodes[indexA].box;
FmAabb* boxB = &hierarchyB->nodes[indexB].box;
bool nodeAIsLeaf = nodeA->left == nodeA->right;
bool nodeBIsLeaf = nodeB->left == nodeB->right;
// If node found to be outside of other mesh bounding box, do not need to test any of its vertices as inside.
// Pass flag down to all children tests to prevent computing intersection values.
includeA = includeA && FmAabbOverlap(boxA->pmin, boxA->pmax, objectPair->objectBMinPosition, objectPair->objectBMaxPosition);
includeB = includeB && FmAabbOverlap(boxB->pmin, boxB->pmax, objectPair->objectAMinPosition, objectPair->objectAMaxPosition);
if ((includeA || includeB) && FmAabbOverlapXY(*boxA, *boxB))
{
if (nodeAIsLeaf && nodeBIsLeaf)
{
FmUpdateVertIntersectionVals(objectPair, (uint)nodeA->left, (uint)nodeB->left, includeA, includeB);
}
else if (nodeAIsLeaf)
{
FmFindInsideVertsRecursive(objectPair, indexA, nodeB->left, includeA, includeB);
FmFindInsideVertsRecursive(objectPair, indexA, nodeB->right, includeA, includeB);
}
else if (nodeBIsLeaf)
{
FmFindInsideVertsRecursive(objectPair, nodeA->left, indexB, includeA, includeB);
FmFindInsideVertsRecursive(objectPair, nodeA->right, indexB, includeA, includeB);
}
else
{
float sizeA = lengthSqr(boxA->pmax - boxA->pmin);
float sizeB = lengthSqr(boxB->pmax - boxB->pmin);
// Split the larger node
if (sizeA > sizeB)
{
FmFindInsideVertsRecursive(objectPair, nodeA->left, indexB, includeA, includeB);
FmFindInsideVertsRecursive(objectPair, nodeA->right, indexB, includeA, includeB);
}
else
{
FmFindInsideVertsRecursive(objectPair, indexA, nodeB->left, includeA, includeB);
FmFindInsideVertsRecursive(objectPair, indexA, nodeB->right, includeA, includeB);
}
}
}
}
void FmFindInsideVerts(FmCollidedObjectPair* meshPair)
{
FmFindInsideVertsRecursive(meshPair, 0, 0, true, true);
}
void FmCollideHierarchies(FmCollidedObjectPair* meshPair)
{
FmCollideRecursive(meshPair, 0, 0);
#if FM_SOA_TRI_INTERSECTION
FmGenerateContactsFromMeshCollisionTriPairs(meshPair);
meshPair->temps.numMeshCollisionTriPairs = 0;
#endif
}
} | 44.294406 | 197 | 0.624225 |
af3c85ba4560bd4fbd781a99e2b5af71ae654cf9 | 772 | hpp | C++ | include/clpp/command_queue_flags.hpp | Robbepop/clpp | 7723bb68c55d861ac2135ccf84d3c5b92b2b2b50 | [
"MIT"
] | 5 | 2015-09-08T01:59:26.000Z | 2018-11-26T10:19:29.000Z | include/clpp/command_queue_flags.hpp | Robbepop/clpp | 7723bb68c55d861ac2135ccf84d3c5b92b2b2b50 | [
"MIT"
] | 6 | 2015-11-29T03:00:11.000Z | 2015-11-29T03:11:52.000Z | include/clpp/command_queue_flags.hpp | Robbepop/clpp | 7723bb68c55d861ac2135ccf84d3c5b92b2b2b50 | [
"MIT"
] | null | null | null | #ifndef CLPP_COMMAND_QUEUE_FLAGS_HPP
#define CLPP_COMMAND_QUEUE_FLAGS_HPP
#include "clpp/detail/common.hpp"
#include "clpp/detail/mask_wrapper.hpp"
namespace cl {
class CommandQueueFlags final :
public detail::MaskWrapper<cl_command_queue_properties>
{
public:
using detail::MaskWrapper<CommandQueueFlags::cl_mask_type>::MaskWrapper;
auto inline isOutOfOrderExecModeEnabled() const -> bool;
auto inline isProfilingEnabled() const -> bool;
auto inline enableOutOfOrderExecMode() -> CommandQueueFlags &;
auto inline enableProfiling() -> CommandQueueFlags &;
auto inline disableOutOfOrderExecMode() -> CommandQueueFlags &;
auto inline disableProfiling() -> CommandQueueFlags &;
};
}
#endif // CLPP_COMMAND_QUEUE_FLAGS_HPP
| 29.692308 | 74 | 0.759067 |
af3dbec14f268006eab1347a8a1f22de395ea87e | 1,872 | cpp | C++ | software/firmware/libraries/CommandQueue/CommandQueue.cpp | ByLinedu/LogoBot | d92c071bc0b52368fd8ca2b934a06a5b487b34b8 | [
"MIT"
] | null | null | null | software/firmware/libraries/CommandQueue/CommandQueue.cpp | ByLinedu/LogoBot | d92c071bc0b52368fd8ca2b934a06a5b487b34b8 | [
"MIT"
] | null | null | null | software/firmware/libraries/CommandQueue/CommandQueue.cpp | ByLinedu/LogoBot | d92c071bc0b52368fd8ca2b934a06a5b487b34b8 | [
"MIT"
] | 1 | 2018-07-31T08:43:24.000Z | 2018-07-31T08:43:24.000Z | #include "CommandQueue.h"
CommandQueue::CommandQueue(int length)
{
cmdQ = new COMMAND[length];
queueLength = length;
qHead = 0;
qSize = 0;
}
boolean CommandQueue::insert(String s, uint8_t cmdType) {
// inserts s at head of queue
// return true if inserted ok, false if buffer full
if (!isFull()) {
qHead--;
if (qHead < 0) qHead += queueLength;
cmdQ[qHead].cmd = String(s);
cmdQ[qHead].cmdType = cmdType;
qSize++;
return true;
}
else
return false;
}
boolean CommandQueue::enqueue(String s, uint8_t cmdType) {
// push s onto tail of queue
// return true if pushed ok, false if buffer full
if (!isFull()) {
int next = qHead + qSize;
if (next >= queueLength) next -= queueLength;
cmdQ[next].cmd = String(s);
cmdQ[next].cmdType = cmdType;
qSize++;
return true;
}
else
return false;
}
uint8_t CommandQueue::peekAtType() {
if (qSize > 0) {
return cmdQ[qHead].cmdType;
} else
return 0xff;
}
COMMAND * CommandQueue::dequeue() {
// pops head of queue
if (qSize > 0) {
COMMAND * res = &cmdQ[qHead];
//String s = cmdQ[qHead].cmd;
qSize--;
qHead++;
if (qHead >= queueLength) qHead -= queueLength;
return res;
}
else
return NULL;
}
boolean CommandQueue::isFull() {
// returns true if full
return qSize == queueLength;
}
boolean CommandQueue::isEmpty() {
return qSize == 0;
}
void CommandQueue::clear() {
qSize = 0;
}
int CommandQueue::pending() {
return qSize;
}
void CommandQueue::printCommandQ()
{
Serial.print("cmdQ:");
Serial.print(qHead);
Serial.print(':');
Serial.println(qSize);
// No longer very helpful, as the cmdType is not human readable
// and would take too much code storage to translate back...
/*
for (int i = 0; i<qSize; i++) {
Serial.print(i);
Serial.print(':');
int j = qHead + i;
if (j > queueLength) j -= queueLength;
Serial.println(cmdQ[j].cmd);
}
*/
}
| 17.660377 | 64 | 0.649038 |
af3df56bb45d05fea22f60c71a7c5f7d498925b9 | 1,114 | cpp | C++ | ast/src/FieldDeclarationNode.cpp | JBamberger/oberon0-compiler | 399d7ea367403809f1bf31aada10e13eb38aac12 | [
"Apache-2.0"
] | 1 | 2020-09-06T15:38:16.000Z | 2020-09-06T15:38:16.000Z | ast/src/FieldDeclarationNode.cpp | JBamberger/oberon0-compiler | 399d7ea367403809f1bf31aada10e13eb38aac12 | [
"Apache-2.0"
] | null | null | null | ast/src/FieldDeclarationNode.cpp | JBamberger/oberon0-compiler | 399d7ea367403809f1bf31aada10e13eb38aac12 | [
"Apache-2.0"
] | null | null | null | /**
* Copyright 2020 Jannik Bamberger
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include "FieldDeclarationNode.h"
#include "NodeVisitor.h"
#include <utility>
FieldDeclarationNode::FieldDeclarationNode(const FilePos& pos, std::string name, TypeNode* type)
: TypedIdentifierNode(pos, std::move(name), type)
{
}
FieldDeclarationNode::~FieldDeclarationNode() = default;
void FieldDeclarationNode::visit(NodeVisitor* visitor) const
{
visitor->visit(this);
}
void FieldDeclarationNode::print(std::ostream& stream) const
{
stream << "FieldNode(" << name_ << ", " << type_ << ")";
}
| 29.315789 | 96 | 0.728905 |
af479203d2cc77aaeb1e75e159093d0557b3792b | 8,788 | cpp | C++ | localgraphclustering/src/lib/include/maxflow.cpp | vishalbelsare/LocalGraphClustering | a6325350997932d548a876deb259c2387fc2c809 | [
"MIT"
] | 106 | 2017-09-06T04:47:02.000Z | 2022-03-30T07:43:27.000Z | localgraphclustering/src/lib/include/maxflow.cpp | pmacg/local-bipartite-clusters | d29e8d37c79e27b48e785b7b2c4bad9ea5d66b6d | [
"MIT"
] | 51 | 2017-09-06T02:22:09.000Z | 2021-12-15T11:39:28.000Z | localgraphclustering/src/lib/include/maxflow.cpp | vishalbelsare/LocalGraphClustering | a6325350997932d548a876deb259c2387fc2c809 | [
"MIT"
] | 38 | 2017-09-04T21:45:13.000Z | 2022-01-19T09:48:25.000Z | #ifndef MAXFLOW_cpp
#define MAXFLOW_cpp
#include "routines.hpp"
#include <list>
#include <climits>
#include <utility>
#include <iostream>
#include <stack>
#include <algorithm>
/*
Based on http://www.geeksforgeeks.org/dinics-algorithm-maximum-flow/
*/
using namespace std;
// Finds if more flow can be sent from s to t.
// Also assigns levels to nodes.
template<typename vtype, typename itype>
bool graph<vtype,itype>::BFS(vtype s, vtype t, vtype V)
{
//cout << "start BFS" << endl;
for (vtype i = 0 ; i < V ; i++) {
level[i] = -1;
}
level[s] = 0; // Level of source vertex
//cout << "start level" << level[t] << endl;
// Create a queue, enqueue source vertex
// and mark source vertex as visited here
// level[] array works as visited array also.
list< vtype > q;
q.push_back(s);
typename vector<Edge<vtype,itype>>::iterator i;
while (!q.empty()) {
vtype u = q.front();
q.pop_front();
for (i = adj[u].begin(); i != adj[u].end(); i++) {
Edge<vtype,itype> &e = *i;
if (level[e.v] < 0 && e.flow < e.C) {
// Level of current vertex is,
// level of parent + 1
level[e.v] = level[u] + 1;
q.push_back(e.v);
}
}
}
// IF we can not reach to the sink we
// return false else true
//cout << "level" << level[t] << endl;
return level[t] < 0 ? false : true ;
}
// A DFS based function to send flow after BFS has
// figured out that there is a possible flow and
// constructed levels. This function called multiple
// times for a single call of BFS.
// flow : Current flow send by parent function call
// start[] : To keep track of next edge to be explored.
// start[i] stores count of edges explored
// from i.
// u : Current vertex
// t : Sink
// UPDATE: convert original recursion approach to a iteration approach
// https://www.codeproject.com/Articles/418776/How-to-replace-recursive-functions-using-stack-and
template<typename vtype, typename itype>
double graph<vtype,itype>::sendFlow(vtype init_u, double init_flow, vtype t, vector<vtype>& start, vector<pair<int,double>>& SnapShots)
{
//pair<int,double> SnapShots[n];
double retVal = 0;
stack<vtype> SnapShotStack;
//SnapShot currentSnapShot = SnapShot(init_u,init_flow);
//SnapShot* currentPtr;
SnapShots[init_u].first = 0;
SnapShots[init_u].second = init_flow;
SnapShotStack.push(init_u);
while (!SnapShotStack.empty()) {
//cout << SnapShotStack.size() << endl;
vtype u=SnapShotStack.top();
if (u == t) {
retVal = SnapShots[u].second;
SnapShotStack.pop();
continue;
}
Edge<vtype,itype> &e = adj[u][start[u]];
double flow = SnapShots[u].second;
switch (SnapShots[u].first)
{
case 0:
//cout << "a" << endl;
//cout << u << " " << start[u] << " " << adj[u].size() << " " << e.v << endl;
SnapShots[u].first = 1;
//SnapShotStack.push(u);
if (level[e.v] == level[u]+1 && e.flow < e.C) {
// find minimum flow from u to t
double curr_flow = min(flow, e.C - e.flow);
SnapShots[e.v].first = 0;
SnapShots[e.v].second = curr_flow;
//SnapShot newSnapShot = SnapShot(e.v,curr_flow);
SnapShotStack.push(e.v);
}
break;
case 1:
//cout << "b" << endl;
if (retVal > 0) {
// add flow to current edge
e.flow += retVal;
// subtract flow from reverse edge
// of current edge
adj[e.v][e.rev].flow -= retVal;
}
if (retVal <= 0 && (start[u]+1) < adj[u].size()) {
start[u] ++;
//cout << u << " " << start[u] << " " << adj[u].size() << endl;
Edge<vtype,itype> &new_e = adj[u][start[u]];
//SnapShotStack.push(u);
//SnapShotStack.push(currentPtr);
if (level[new_e.v] == level[u]+1 && new_e.flow < new_e.C) {
double curr_flow = min(flow, new_e.C - new_e.flow);
SnapShots[new_e.v].first = 0;
SnapShots[new_e.v].second = curr_flow;
SnapShotStack.push(new_e.v);
//SnapShot newSnapShot = SnapShot(new_e.v,curr_flow);
//SnapShotStack.push(&newSnapShot);
}
}
else {
SnapShotStack.pop();
}
break;
}
}
return retVal;
}
// template<typename vtype, typename itype>
// double graph<vtype,itype>::sendFlow(vtype u, double flow, vtype t, vector<vtype>& start)
// {
// //cout << u << " " << start[u] << endl;
// // Sink reached
// if (u == t)
// return flow;
// // Traverse all adjacent edges one -by - one.
// for ( ; start[u] < adj[u].size(); start[u]++) {
// // Pick next edge from adjacency list of u
// Edge<vtype,itype> &e = adj[u][start[u]];
// if (level[e.v] == level[u]+1 && e.flow < e.C) {
// // find minimum flow from u to t
// double curr_flow = min(flow, e.C - e.flow);
// double temp_flow = sendFlow(e.v, curr_flow, t, start);
// // flow is greater than zero
// if (temp_flow > 0) {
// // add flow to current edge
// e.flow += temp_flow;
// // subtract flow from reverse edge
// // of current edge
// adj[e.v][e.rev].flow -= temp_flow;
// //cout << u << " " << temp_flow << endl;
// return temp_flow;
// }
// }
// }
// return 0;
// }
template<typename vtype, typename itype>
void graph<vtype,itype>::find_cut(vtype u_init, vector<bool>& mincut, vtype& length)
{
stack <vtype> stk;
stk.push(u_init);
while (!stk.empty()) {
vtype u = stk.top();
//cout << u << " " << stk.size() << endl;
stk.pop();
if (mincut[u] == true) {
continue;
}
mincut[u] = true;
length ++;
for (int i = 0 ; i < adj[u].size(); i ++) {
int k = adj[u].size() - 1 - i;
//cout << k << " " << adj[u].size() << endl;
Edge<vtype,itype> e = adj[u][k];
if (e.flow < e.C && mincut[e.v] == false) {
stk.push(e.v);
}
}
}
}
/*
template<typename vtype, typename itype>
void graph<vtype,itype>::find_cut(vtype u, vector<bool>& mincut, vtype& length)
{
mincut[u] = true;
length ++;
//cout << "current len: " << length << endl;
for (vtype i = 0 ; i < adj[u].size(); i ++) {
Edge<vtype,itype> e = adj[u][i];
if (e.flow < e.C && mincut[e.v] == false) {
find_cut(e.v,mincut,length);
}
}
}
*/
// Returns maximum flow in graph
// s: source node
// t: taget node
// V: total number of nodes
// mincut: store the result
template<typename vtype, typename itype>
pair<double,vtype> graph<vtype,itype>::DinicMaxflow(vtype s, vtype t, vtype V, vector<bool>& mincut)
{
for(int i = 0; i < V; i ++){
for(int j = 0; j < adj[i].size(); j ++){
Edge<vtype,itype> &e = adj[i][j];
//cout << i << " " << e.v << " " << e.C << " " << e.rev << " " << adj[e.v][e.rev].v << " " << adj[e.v][e.rev].C << " " << adj[e.v][e.rev].rev << endl;
}
}
// Corner case
if (s == t)
return make_pair(-1,0);
double total = 0; // Initialize result
// Augment the flow while there is path
// from source to sink
vector<vtype> start(V+1);
vector<pair<int,double>> SnapShots(V+1);
while (BFS(s, t, V) == true){
// store how many edges are visited
// from V { 0 to V }
fill(start.begin(),start.end(),0);
// while flow is not zero in graph from S to D
double flow = sendFlow(s, numeric_limits<double>::max(), t, start, SnapShots);
while (flow > 0) {
// Add path flow to overall flow
total += flow;
flow = sendFlow(s, numeric_limits<double>::max(), t, start, SnapShots);
}
//cout << "curr flow: " << total << endl;
//cout << "BFS" << endl;
}
//cout << "out" << endl;
vtype length = 0;
fill(mincut.begin(),mincut.end(),false);
find_cut(s,mincut,length);
//cout << "length " << length << endl;
// return maximum flow
return make_pair(total,length);
}
#endif
| 31.498208 | 162 | 0.505462 |
af4b5024feecf15d017f713595e8a8251eeb9623 | 3,158 | cpp | C++ | RTOS_JOB_SCHEDULING_SIMULATOR/Files/sjfnp.cpp | binodkumar23/IITJ_IDDEDA | 2c2f9ec14bcbb882c23866f1329a5fd0a1a7a993 | [
"MIT"
] | 1 | 2021-12-11T10:23:05.000Z | 2021-12-11T10:23:05.000Z | RTOS_JOB_SCHEDULING_SIMULATOR/Files/sjfnp.cpp | binodkumar23/IITJ_IDDEDA | 2c2f9ec14bcbb882c23866f1329a5fd0a1a7a993 | [
"MIT"
] | null | null | null | RTOS_JOB_SCHEDULING_SIMULATOR/Files/sjfnp.cpp | binodkumar23/IITJ_IDDEDA | 2c2f9ec14bcbb882c23866f1329a5fd0a1a7a993 | [
"MIT"
] | 3 | 2021-12-23T17:19:42.000Z | 2022-01-27T13:53:47.000Z | #include <bits/stdc++.h>
using namespace std;
vector<double> sjfnp(vector<int> &cpu_burst, vector<int> &arrival_times, int mode)
{
int n = cpu_burst.size();
vector<int> wait_time(n, 0), turnaround_time(n, 0), response_time(n), completion_time(n, 0);
vector<vector<int> > table(n, vector<int>(6));
table[0][0] = arrival_times[0];
table[0][1] = cpu_burst[0];
table[0][5] = 0;
for (int i = 1; i < n; i++)
{
table[i][0] = arrival_times[i];
table[i][1] = cpu_burst[i];
table[i][2] = completion_time[i];
table[i][3] = wait_time[i];
table[i][4] = turnaround_time[i];
table[i][5] = i;
}
sort(table.begin(), table.end());
table[0][2] = table[0][1] + table[0][0];
table[0][4] = table[0][2] - table[0][0];
table[0][3] = table[0][4] - table[0][1];
for (int i = 1; i < n; i++)
{
int ct = table[i - 1][2];
int burst = table[i][1];
int row = i;
bool inside = false;
for (int j = i; j < n; j++)
{
if (ct >= table[j][0] && burst >= table[j][1])
{
burst = table[j][1];
row = j;
}
}
if (ct < table[i][0])
ct = table[i][0];
table[row][2] = ct + table[row][1];
table[row][4] = table[row][2] - table[row][0];
table[row][3] = table[row][4] - table[row][1];
for (int k = 0; k < 5; k++)
{
swap(table[row][k], table[i][k]);
}
// completion_time[i]=wait_time[i]+cpu_burst[i]-;
}
if (mode == 0)
{
cout << "----------------------------------------------------------------------" << endl;
cout << "Shortest job first Non premptive" << endl;
vector<pair<int, pair<int, int> > > rq;
for (int j = 0; j < n; j++)
{
rq.push_back(make_pair(table[j][0], make_pair(0, table[j][5])));
rq.push_back(make_pair(table[j][3], make_pair(1, table[j][5])));
}
sort(rq.begin(), rq.end());
for (int j = 0; j < rq.size(); j++)
{
if (rq[j].second.first == 0)
{
cout << "Process " << rq[j].second.second+1 << " entering the ready queue" << endl;
}
else
{
cout << "Process " << rq[j].second.second+1 << " leaving the ready queue" << endl;
}
}
cout << "----------------------------------------------------------------------" << endl;
}
double average_waiting_time = 0, average_turnaround_time = 0, average_response_time = 0;
for (int i = 0; i < n; i++)
{
average_waiting_time += table[i][3];
average_turnaround_time += table[i][4];
// average_response_time+=response_time[i];
}
// cout<<average_turnaround_time<<" "<<average_waiting_time<<endl;
// average_response_time/=n;
average_turnaround_time /= n;
average_waiting_time /= n;
vector<double> final(3);
final[0] = average_waiting_time;
final[1] = average_turnaround_time;
final[2] = average_waiting_time;
return final;
} | 31.58 | 99 | 0.468334 |
af507d136ec0c8e4bb719e673a2005234f73e475 | 756 | hpp | C++ | src/UI/RepeaterBookResultsWidget.hpp | neotericpiguy/QDmrconfig | 5fd0b5fbacd414f5963bcfef153db95e9447bade | [
"MIT"
] | 1 | 2021-01-03T17:49:59.000Z | 2021-01-03T17:49:59.000Z | src/UI/RepeaterBookResultsWidget.hpp | neotericpiguy/QDmrconfig | 5fd0b5fbacd414f5963bcfef153db95e9447bade | [
"MIT"
] | 39 | 2020-12-19T18:19:06.000Z | 2021-12-29T01:25:39.000Z | src/UI/RepeaterBookResultsWidget.hpp | neotericpiguy/QDmrconfig | 5fd0b5fbacd414f5963bcfef153db95e9447bade | [
"MIT"
] | null | null | null | #ifndef REPEATERBOOKRESULTSWIDGET_HPP
#define REPEATERBOOKRESULTSWIDGET_HPP
#pragma GCC diagnostic ignored "-Weffc++"
#include <QtWidgets/QPlainTextEdit>
#include <QtWidgets/QTableWidget>
#include <QtWidgets/QtWidgets>
#include <memory>
#pragma GCC diagnostic pop
#include "BSONDocWidget.hpp"
class RepeaterBookResultsWidget : public BSONDocWidget
{
Q_OBJECT
public:
RepeaterBookResultsWidget(const std::vector<Mongo::BSONDoc>& bsonDocs, QWidget* parent = 0);
RepeaterBookResultsWidget(const RepeaterBookResultsWidget&) = delete;
RepeaterBookResultsWidget& operator=(const RepeaterBookResultsWidget&) = delete;
virtual ~RepeaterBookResultsWidget();
void filterPreset(const std::string& columnName, const std::string& regexStr);
};
#endif
| 28 | 94 | 0.80291 |
af530f8bc0cb8af0aa3e3ec65530a5292b8151a1 | 10,697 | inl | C++ | Phoenix3D/PX2Graphics/PX2Renderer.inl | PheonixFoundation/Phoenix3D | bfb2e3757bf61ac461aeeda9216bf8c8fdf76d99 | [
"BSL-1.0"
] | 36 | 2016-04-24T01:40:38.000Z | 2022-01-18T07:32:26.000Z | Phoenix3D/PX2Graphics/PX2Renderer.inl | PheonixFoundation/Phoenix3D | bfb2e3757bf61ac461aeeda9216bf8c8fdf76d99 | [
"BSL-1.0"
] | null | null | null | Phoenix3D/PX2Graphics/PX2Renderer.inl | PheonixFoundation/Phoenix3D | bfb2e3757bf61ac461aeeda9216bf8c8fdf76d99 | [
"BSL-1.0"
] | 16 | 2016-06-13T08:43:51.000Z | 2020-09-15T13:25:58.000Z | // PX2Renderer.inl
//----------------------------------------------------------------------------
inline int Renderer::GetWidth () const
{
return mWidth;
}
//----------------------------------------------------------------------------
inline int Renderer::GetHeight () const
{
return mHeight;
}
//----------------------------------------------------------------------------
inline Texture::Format Renderer::GetColorFormat () const
{
return mColorFormat;
}
//----------------------------------------------------------------------------
inline Texture::Format Renderer::GetDepthStencilFormat () const
{
return mDepthStencilFormat;
}
//----------------------------------------------------------------------------
inline int Renderer::GetNumMultisamples () const
{
return mNumMultisamples;
}
//----------------------------------------------------------------------------
inline const AlphaProperty* Renderer::GetAlphaProperty () const
{
return mAlphaProperty;
}
//----------------------------------------------------------------------------
inline const CullProperty* Renderer::GetCullProperty () const
{
return mCullProperty;
}
//----------------------------------------------------------------------------
inline const DepthProperty* Renderer::GetDepthProperty () const
{
return mDepthProperty;
}
//----------------------------------------------------------------------------
inline const OffsetProperty* Renderer::GetOffsetProperty () const
{
return mOffsetProperty;
}
//----------------------------------------------------------------------------
inline const StencilProperty* Renderer::GetStencilProperty () const
{
return mStencilProperty;
}
//----------------------------------------------------------------------------
inline const WireProperty* Renderer::GetWireProperty () const
{
return mWireProperty;
}
//----------------------------------------------------------------------------
inline void Renderer::SetOverrideAlphaProperty (const AlphaProperty* alphaState)
{
mOverrideAlphaProperty = alphaState;
if (alphaState)
{
SetAlphaProperty(alphaState);
}
else
{
SetAlphaProperty(mDefaultAlphaProperty);
}
}
//----------------------------------------------------------------------------
inline void Renderer::SetOverrideCullProperty (const CullProperty* cullState)
{
mOverrideCullProperty = cullState;
if (cullState)
{
SetCullProperty(cullState);
}
else
{
SetCullProperty(mDefaultCullProperty);
}
}
//----------------------------------------------------------------------------
inline void Renderer::SetOverrideDepthProperty (const DepthProperty* depthState)
{
mOverrideDepthProperty = depthState;
if (depthState)
{
SetDepthProperty(depthState);
}
else
{
SetDepthProperty(mDefaultDepthProperty);
}
}
//----------------------------------------------------------------------------
inline void Renderer::SetOverrideOffsetProperty (const OffsetProperty* offsetState)
{
mOverrideOffsetProperty = offsetState;
if (offsetState)
{
SetOffsetProperty(offsetState);
}
else
{
SetOffsetProperty(mDefaultOffsetProperty);
}
}
//----------------------------------------------------------------------------
inline void Renderer::SetOverrideStencilProperty (const StencilProperty* stencilState)
{
mOverrideStencilProperty = stencilState;
if (stencilState)
{
SetStencilProperty(stencilState);
}
else
{
SetStencilProperty(mDefaultStencilProperty);
}
}
//----------------------------------------------------------------------------
inline void Renderer::SetOverrideWireProperty (const WireProperty* wireState)
{
mOverrideWireProperty = wireState;
if (wireState)
{
SetWireProperty(wireState);
}
else
{
SetWireProperty(mDefaultWireProperty);
}
}
//----------------------------------------------------------------------------
inline const AlphaProperty* Renderer::GetOverrideAlphaProperty () const
{
return mOverrideAlphaProperty;
}
//----------------------------------------------------------------------------
inline const CullProperty* Renderer::GetOverrideCullProperty () const
{
return mOverrideCullProperty;
}
//----------------------------------------------------------------------------
inline const DepthProperty* Renderer::GetOverrideDepthProperty () const
{
return mOverrideDepthProperty;
}
//----------------------------------------------------------------------------
inline const OffsetProperty* Renderer::GetOverrideOffsetProperty () const
{
return mOverrideOffsetProperty;
}
//----------------------------------------------------------------------------
inline const StencilProperty* Renderer::GetOverrideStencilProperty () const
{
return mOverrideStencilProperty;
}
//----------------------------------------------------------------------------
inline const WireProperty* Renderer::GetOverrideWireProperty () const
{
return mOverrideWireProperty;
}
//----------------------------------------------------------------------------
inline void Renderer::SetReverseCullOrder (bool reverseCullOrder)
{
mReverseCullOrder = reverseCullOrder;
}
//----------------------------------------------------------------------------
inline bool Renderer::GetReverseCullOrder () const
{
return mReverseCullOrder;
}
//----------------------------------------------------------------------------
inline void Renderer::SetCamera (Camera* camera)
{
mCamera = camera;
}
//----------------------------------------------------------------------------
inline Camera* Renderer::GetCamera ()
{
return mCamera;
}
//----------------------------------------------------------------------------
inline const Camera* Renderer::GetCamera () const
{
return mCamera;
}
//----------------------------------------------------------------------------
inline const HMatrix& Renderer::GetViewMatrix () const
{
return mCamera->GetViewMatrix();
}
//----------------------------------------------------------------------------
inline const HMatrix& Renderer::GetProjectionMatrix () const
{
return mCamera->GetProjectionMatrix();
}
//----------------------------------------------------------------------------
inline const HMatrix& Renderer::GetPostProjectionMatrix () const
{
return mCamera->GetPostProjectionMatrix();
}
//----------------------------------------------------------------------------
inline const Rectf &Renderer::GetViewPort() const
{
return mViewPort;
}
//----------------------------------------------------------------------------
inline void Renderer::SetClearColor (const Float4& clearColor)
{
mClearColor = clearColor;
}
//----------------------------------------------------------------------------
inline const Float4& Renderer::GetClearColor () const
{
return mClearColor;
}
//----------------------------------------------------------------------------
inline void Renderer::SetClearDepth (float clearDepth)
{
mClearDepth = clearDepth;
}
//----------------------------------------------------------------------------
inline float Renderer::GetClearDepth () const
{
return mClearDepth;
}
//----------------------------------------------------------------------------
inline void Renderer::SetClearStencil (unsigned int clearStencil)
{
mClearStencil = clearStencil;
}
//----------------------------------------------------------------------------
inline unsigned int Renderer::GetClearStencil () const
{
return mClearStencil;
}
//----------------------------------------------------------------------------
inline void Renderer::GetColorMask (bool& allowRed, bool& allowGreen,
bool& allowBlue, bool& allowAlpha) const
{
allowRed = mAllowRed;
allowGreen = mAllowGreen;
allowBlue = mAllowBlue;
allowAlpha = mAllowAlpha;
}
//----------------------------------------------------------------------------
inline bool Renderer::InTexture2DMap (const Texture2D* texture)
{
return mTexture2Ds.find(texture) != mTexture2Ds.end();
}
//----------------------------------------------------------------------------
inline void Renderer::InsertInTexture2DMap (const Texture2D* texture,
PdrTexture2D* platformTexture)
{
mTexture2Ds[texture] = platformTexture;
}
//----------------------------------------------------------------------------
inline int Renderer::GetNumPdrVertexFormat () const
{
return (int)mVertexFormats.size();
}
//----------------------------------------------------------------------------
inline int Renderer::GetNumPdrVertexBuffer () const
{
return (int)mVertexBuffers.size();
}
//----------------------------------------------------------------------------
inline int Renderer::GetNumPdrIndexBuffer () const
{
return (int)mIndexBuffers.size();
}
//----------------------------------------------------------------------------
inline int Renderer::GetNumPdrTexture1D () const
{
return (int)mTexture1Ds.size();
}
//----------------------------------------------------------------------------
inline int Renderer::GetNumPdrTexture2D () const
{
return (int)mTexture2Ds.size();
}
//----------------------------------------------------------------------------
inline int Renderer::GetNumPdrTexture3D () const
{
return (int)mTexture3Ds.size();
}
//----------------------------------------------------------------------------
inline int Renderer::GetNumPdrTextureCube () const
{
return (int)mTextureCubes.size();
}
//----------------------------------------------------------------------------
inline int Renderer::GetNumPdrRenderTarget () const
{
return (int)mRenderTargets.size();
}
//----------------------------------------------------------------------------
inline int Renderer::GetNumPdrVertexShader () const
{
return (int)mVertexShaders.size();
}
//----------------------------------------------------------------------------
inline int Renderer::GetNumPdrPixelShader () const
{
return (int)mPixelShaders.size();
}
//----------------------------------------------------------------------------
inline int Renderer::GetNumPdrMaterialPass () const
{
return (int)mMaterialPasses.size();
}
//----------------------------------------------------------------------------
inline int Renderer::GetNumGPUVertexShader () const
{
return (int)mSharePdrVertexShaders.size();
}
//----------------------------------------------------------------------------
inline int Renderer::GetNumGPUPixelShader () const
{
return (int)mSharePdrPixelShaders.size();
}
//----------------------------------------------------------------------------
inline int Renderer::GetNumGPUMaterialPass () const
{
return (int)mSharePdrMaterialPasses.size();
}
//----------------------------------------------------------------------------
inline int Renderer::GetNumDrawPrimitivePerFrame () const
{
return mNumDrawPrimitivePerFrame;
}
//---------------------------------------------------------------------------- | 31.83631 | 86 | 0.450126 |
af543eb8e077bf30ca4be63a6821d95449f6d90f | 8,262 | cpp | C++ | src/mainDesc.cpp | KenOverholt/CarND-Path-Planning-Project | 081e2373a2a96e9e666dd9306cb9f693a516dbcb | [
"MIT"
] | null | null | null | src/mainDesc.cpp | KenOverholt/CarND-Path-Planning-Project | 081e2373a2a96e9e666dd9306cb9f693a516dbcb | [
"MIT"
] | null | null | null | src/mainDesc.cpp | KenOverholt/CarND-Path-Planning-Project | 081e2373a2a96e9e666dd9306cb9f693a516dbcb | [
"MIT"
] | null | null | null | // For converting back and forth between radians and degrees.
constexpr double pi() { return M_PI; }
double deg2rad(double x) { return x * pi() / 180; }
double rad2deg(double x) { return x * 180 / pi(); }
// distance between two points
double distance(double x1, double y1, double x2, double y2)
// closest waypoint (may be behind us)
int ClosestWaypoint(double x, double y, const vector<double> &maps_x, const vector<double> &maps_y)
// next waypoint (in front of us)
int NextWaypoint(double x, double y, double theta, const vector<double> &maps_x, const vector<double> &maps_y)
// Transform from Cartesian x,y coordinates to Frenet s,d coordinates
vector<double> getFrenet(double x, double y, double theta, const vector<double> &maps_x, const vector<double> &maps_y)
// Transform from Frenet s,d coordinates to Cartesian x,y
vector<double> getXY(double s, double d, const vector<double> &maps_s, const vector<double> &maps_x, const vector<double> &maps_y)
int main() {
// Load up map values for waypoint's x,y,s and d normalized normal vectors
vector<double> map_waypoints_x;
vector<double> map_waypoints_y;
vector<double> map_waypoints_s;
vector<double> map_waypoints_dx;
vector<double> map_waypoints_dy;
// The max s value before wrapping around the track back to 0
double max_s = 6945.554;
//start in lane 1;
int lane = 1;
// Target reference velocity
double ref_vel = 0; //mph
h.onMessage([&ref_vel, &map_waypoints_x, &map_waypoints_y, &map_waypoints_s, &map_waypoints_dx, &map_waypoints_dy, &lane]
(uWS::WebSocket<uWS::SERVER> ws, char *data, size_t length, uWS::OpCode opCode) {
// we have a valid message
if (length && length > 2 && data[0] == '4' && data[1] == '2') {
auto s = hasData(data);
if (s != "") {
auto j = json::parse(s);
string event = j[0].get<string>();
if (event == "telemetry") {
// j[1] is the data JSON object
// Main car's localization Data
double car_x = j[1]["x"];
double car_y = j[1]["y"];
double car_s = j[1]["s"];
double car_d = j[1]["d"];
double car_yaw = j[1]["yaw"];
double car_speed = j[1]["speed"];
// Previous path data given to the Planner
auto previous_path_x = j[1]["previous_path_x"];
auto previous_path_y = j[1]["previous_path_y"];
// Previous path's end s and d values
double end_path_s = j[1]["end_path_s"];
double end_path_d = j[1]["end_path_d"];
// Sensor Fusion Data, a list of all other cars on the same side of the road.
//auto sensor_fusion = j[1]["sensor_fusion"];
vector<vector<double>> sensor_fusion = j[1]["sensor_fusion"];
int prev_size = previous_path_x.size();
if(prev_size > 0)
{
car_s = end_path_s;
}
bool too_close = false;
//find ref_v to use
for(int i = 0; i < sensor_fusion.size(); i++) //for each other car on the road
{
//car is in my lane
float d = sensor_fusion[i][6];
if (d < (2+4*lane+2) && d > (2+4*lane-2) ) //if car is in the lane (even if offcenter (i.e., +/-2 from center))
{
double vx = sensor_fusion[i][3];
double vy = sensor_fusion[i][4];
double check_speed = sqrt(vx*vx+vy*vy);
double check_car_s = sensor_fusion[i][5];
check_car_s += ((double)prev_size*.02*check_speed); //if using previoius points, can project s value out
//check s values greater than mine and s gap
if((check_car_s > car_s) && ((check_car_s-car_s) < 30)) //30 meters
{
// TODO: either change lanes or lower reference velocity so we don't crash into the car in fromt of us
too_close = true;
//TODO: look into the future, what is the best lane to change into
//use finite state machine
// build a cost function taking into account which lane to get into
// use Frenet to help see where other cars are
if (lane > 0)
{
lane = 0;
}
} // end "check s values greater than mine and s gap"
} // end "if car is in the lane (even if offcenter..."
} // end "for each other car on the road"
if (too_close)
{
ref_vel -= .224; //5 m/s^2
}
else if (ref_vel < 49.5)
{
ref_vel += .224;
}
// Create a list of widely spaced (x,y) waypoints, evenly spaced at 30m
// later we will interpolate these waypoints with a spline and fill it in with more points that control speed.
vector<double> ptsx;
vector<double> ptsy;
// reference x,y, yaw states
// either we will reference the starting point as where the car is or at the previoius paths and point
double ref_x = car_x;
double ref_y = car_y;
double ref_yaw = deg2rad(car_yaw);
// if previoius size is almost empty, use the car as starting reference
if (prev_size < 2)
{
//Use two points that make the path tangent to the car
double prev_car_x = car_x - cos(car_yaw);
double prev_car_y = car_y - sin(car_yaw);
ptsx.push_back(prev_car_x);
ptsx.push_back(car_x);
ptsy.push_back(prev_car_y);
ptsy.push_back(car_y);
}
//use the previous path's endpoint as starting reference
else
{
//redefine reference state as previous path endpoint
ref_x = previous_path_x[prev_size-1];
ref_y = previous_path_y[prev_size-1];
double ref_x_prev = previous_path_x[prev_size-2];
double ref_y_prev = previous_path_y[prev_size-2];
ref_yaw = atan2(ref_y-ref_y_prev, ref_x - ref_x_prev);
//use two points that make the path tangent to the previous path's endpoint
ptsx.push_back(ref_x_prev);
ptsx.push_back(ref_x);
ptsy.push_back(ref_y_prev);
ptsy.push_back(ref_y);
}
// In Frenet add evenly 30m spaced points ahead of the starting reference
vector<double> next_wp0 = getXY(car_s+30, (2+4*lane), map_waypoints_s, map_waypoints_x, map_waypoints_y);
vector<double> next_wp1 = getXY(car_s+60, (2+4*lane), map_waypoints_s, map_waypoints_x, map_waypoints_y);
vector<double> next_wp2 = getXY(car_s+90, (2+4*lane), map_waypoints_s, map_waypoints_x, map_waypoints_y);
ptsx.push_back(next_wp0[0]);
ptsx.push_back(next_wp1[0]);
ptsx.push_back(next_wp2[0]);
ptsy.push_back(next_wp0[1]);
ptsy.push_back(next_wp1[1]);
ptsy.push_back(next_wp2[1]);
for (int i=0; i < ptsx.size(); i++ )
{
//shift car reference angle to 0 degrees
double shift_x = ptsx[i] - ref_x;
double shift_y = ptsy[i] - ref_y;
ptsx[i] = ( shift_x*cos(0-ref_yaw) - shift_y*sin(0-ref_yaw) );
ptsy[i] = ( shift_x*sin(0-ref_yaw) + shift_y*cos(0-ref_yaw) );
}
//create a spline
tk::spline s;
//set (x,y) points to the spline
s.set_points(ptsx, ptsy);
//define the portal (x,y) points we will use for the planner
vector<double> next_x_vals;
vector<double> next_y_vals;
// start with all of the previous path points from last time
for (int i=0; i<previous_path_x.size(); i++)
{
next_x_vals.push_back(previous_path_x[i]);
next_y_vals.push_back(previous_path_y[i]);
}
// calculate how to braak up spline points so that we travel of our desired reference velocity
double target_x = 30.0;
double target_y = s(target_x);
double target_dist = sqrt((target_x)*(target_x)+(target_y)*(target_y));
double x_add_on = 0;
// fill up the rest of our path planner after filling it with previous points, here we will always output 50 points
for (int i=1; i <= 50-previous_path_x.size(); i++)
{
double N = (target_dist/(0.02*ref_vel/2.24));
double x_point = x_add_on+(target_x)/N;
double y_point = s(x_point);
x_add_on = x_point;
double x_ref = x_point;
double y_ref = y_point;
// rotate back to normal after rotating it earlier
x_point = (x_ref*cos(ref_yaw) - y_ref*sin(ref_yaw) );
y_point = (x_ref*sin(ref_yaw) + y_ref*cos(ref_yaw) );
x_point += ref_x;
y_point += ref_y;
next_x_vals.push_back(x_point);
next_y_vals.push_back(y_point);
}
json msgJson;
msgJson["next_x"] = next_x_vals;
msgJson["next_y"] = next_y_vals;
}
}
}
});
| 33.585366 | 131 | 0.643065 |
af567748523f630b8d3278d7f56cc7d0ef2934f2 | 3,653 | cc | C++ | leveldb/util/io_posix.cc | naivewong/timeunion | 8070492d2c6a2d68175e7d026c27b858c2aec8e6 | [
"Apache-2.0"
] | null | null | null | leveldb/util/io_posix.cc | naivewong/timeunion | 8070492d2c6a2d68175e7d026c27b858c2aec8e6 | [
"Apache-2.0"
] | null | null | null | leveldb/util/io_posix.cc | naivewong/timeunion | 8070492d2c6a2d68175e7d026c27b858c2aec8e6 | [
"Apache-2.0"
] | null | null | null | #include "util/io_posix.h"
#include <algorithm>
#include <errno.h>
#include <fcntl.h>
#include <future>
#include <linux/falloc.h>
#include <linux/fs.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/ioctl.h>
#include <sys/mman.h>
#include <sys/stat.h>
#include <sys/statfs.h>
#include <sys/syscall.h>
#include <sys/sysmacros.h>
#include <sys/types.h>
#include <thread>
#include <unistd.h>
#include "leveldb/status.h"
namespace leveldb {
bool PosixWrite(int fd, const char* buf, size_t nbyte) {
const size_t kLimit1Gb = 1UL << 30;
const char* src = buf;
size_t left = nbyte;
while (left != 0) {
size_t bytes_to_write = std::min(left, kLimit1Gb);
ssize_t done = write(fd, src, bytes_to_write);
if (done < 0) {
if (errno == EINTR) {
continue;
}
return false;
}
left -= done;
src += done;
}
return true;
}
bool PosixPositionedWrite(int fd, const char* buf, size_t nbyte, off_t offset) {
const size_t kLimit1Gb = 1UL << 30;
const char* src = buf;
size_t left = nbyte;
while (left != 0) {
size_t bytes_to_write = std::min(left, kLimit1Gb);
ssize_t done = pwrite(fd, src, bytes_to_write, offset);
if (done < 0) {
if (errno == EINTR) {
continue;
}
return false;
}
left -= done;
offset += done;
src += done;
}
return true;
}
/*
* PosixDirectory
*/
PosixDirectory::~PosixDirectory() { close(fd_); }
Status PosixDirectory::Fsync() {
#ifndef OS_AIX
if (fsync(fd_) == -1) {
return IOError("While fsync", "a directory", errno);
}
#endif
return Status::OK();
}
/*
* PosixRandomRWFile
*/
PosixRandomRWFile::PosixRandomRWFile(const std::string& fname, int fd)
: filename_(fname), fd_(fd) {}
PosixRandomRWFile::~PosixRandomRWFile() {
if (fd_ >= 0) {
Close();
}
}
Status PosixRandomRWFile::Write(uint64_t offset, const Slice& data) {
const char* src = data.data();
size_t nbytes = data.size();
if (!PosixPositionedWrite(fd_, src, nbytes, static_cast<off_t>(offset))) {
return IOError("While write random read/write file at offset " +
std::to_string(offset),
filename_, errno);
}
return Status::OK();
}
Status PosixRandomRWFile::Read(uint64_t offset, size_t n, Slice* result,
char* scratch) const {
size_t left = n;
char* ptr = scratch;
while (left > 0) {
ssize_t done = pread(fd_, ptr, left, offset);
if (done < 0) {
// error while reading from file
if (errno == EINTR) {
// read was interrupted, try again.
continue;
}
return IOError("While reading random read/write file offset " +
std::to_string(offset) + " len " + std::to_string(n),
filename_, errno);
} else if (done == 0) {
// Nothing more to read
break;
}
// Read `done` bytes
ptr += done;
offset += done;
left -= done;
}
*result = Slice(scratch, n - left);
return Status::OK();
}
Status PosixRandomRWFile::Flush() { return Status::OK(); }
Status PosixRandomRWFile::Sync() {
if (fdatasync(fd_) < 0) {
return IOError("While fdatasync random read/write file", filename_, errno);
}
return Status::OK();
}
Status PosixRandomRWFile::Fsync() {
if (fsync(fd_) < 0) {
return IOError("While fsync random read/write file", filename_, errno);
}
return Status::OK();
}
Status PosixRandomRWFile::Close() {
if (close(fd_) < 0) {
return IOError("While close random read/write file", filename_, errno);
}
fd_ = -1;
return Status::OK();
}
} // namespace leveldb | 22.006024 | 80 | 0.607993 |
af5783770d5c282eca5c5eb8feffe07c4126afe6 | 8,308 | cpp | C++ | src/mongo/s/catalog/catalog_manager.cpp | rzh/mongo | f1c7cef21ac01792eb4934893b970f0303a23bca | [
"Apache-2.0"
] | null | null | null | src/mongo/s/catalog/catalog_manager.cpp | rzh/mongo | f1c7cef21ac01792eb4934893b970f0303a23bca | [
"Apache-2.0"
] | null | null | null | src/mongo/s/catalog/catalog_manager.cpp | rzh/mongo | f1c7cef21ac01792eb4934893b970f0303a23bca | [
"Apache-2.0"
] | null | null | null | /**
* Copyright (C) 2015 MongoDB Inc.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License, version 3,
* 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 Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
* 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 GNU Affero General 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.
*/
#include "mongo/platform/basic.h"
#include "mongo/s/catalog/catalog_manager.h"
#include <memory>
#include "mongo/base/status.h"
#include "mongo/base/status_with.h"
#include "mongo/db/write_concern_options.h"
#include "mongo/s/catalog/type_collection.h"
#include "mongo/s/catalog/type_database.h"
#include "mongo/s/client/shard_registry.h"
#include "mongo/s/write_ops/batched_command_request.h"
#include "mongo/s/write_ops/batched_command_response.h"
#include "mongo/s/write_ops/batched_delete_document.h"
#include "mongo/s/write_ops/batched_delete_request.h"
#include "mongo/s/write_ops/batched_insert_request.h"
#include "mongo/s/write_ops/batched_update_document.h"
#include "mongo/util/mongoutils/str.h"
namespace mongo {
using std::string;
using std::unique_ptr;
using std::vector;
namespace {
Status getStatus(const BatchedCommandResponse& response) {
if (response.getOk() == 0) {
return Status(static_cast<ErrorCodes::Error>(response.getErrCode()),
response.getErrMessage());
}
if (response.isErrDetailsSet()) {
const WriteErrorDetail* errDetail = response.getErrDetails().front();
return Status(static_cast<ErrorCodes::Error>(errDetail->getErrCode()),
errDetail->getErrMessage());
}
if (response.isWriteConcernErrorSet()) {
const WCErrorDetail* errDetail = response.getWriteConcernError();
return Status(static_cast<ErrorCodes::Error>(errDetail->getErrCode()),
errDetail->getErrMessage());
}
return Status::OK();
}
} // namespace
Status CatalogManager::insert(const string& ns,
const BSONObj& doc,
BatchedCommandResponse* response) {
unique_ptr<BatchedInsertRequest> insert(new BatchedInsertRequest());
insert->addToDocuments(doc);
BatchedCommandRequest request(insert.release());
request.setNS(ns);
request.setWriteConcern(WriteConcernOptions::Majority);
BatchedCommandResponse dummyResponse;
if (response == NULL) {
response = &dummyResponse;
}
// Make sure to add ids to the request, since this is an insert operation
unique_ptr<BatchedCommandRequest> requestWithIds(BatchedCommandRequest::cloneWithIds(request));
const BatchedCommandRequest& requestToSend = requestWithIds.get() ? *requestWithIds : request;
writeConfigServerDirect(requestToSend, response);
return getStatus(*response);
}
Status CatalogManager::update(const string& ns,
const BSONObj& query,
const BSONObj& update,
bool upsert,
bool multi,
BatchedCommandResponse* response) {
unique_ptr<BatchedUpdateDocument> updateDoc(new BatchedUpdateDocument());
updateDoc->setQuery(query);
updateDoc->setUpdateExpr(update);
updateDoc->setUpsert(upsert);
updateDoc->setMulti(multi);
unique_ptr<BatchedUpdateRequest> updateRequest(new BatchedUpdateRequest());
updateRequest->addToUpdates(updateDoc.release());
updateRequest->setWriteConcern(WriteConcernOptions::Majority);
BatchedCommandRequest request(updateRequest.release());
request.setNS(ns);
BatchedCommandResponse dummyResponse;
if (response == NULL) {
response = &dummyResponse;
}
writeConfigServerDirect(request, response);
return getStatus(*response);
}
Status CatalogManager::remove(const string& ns,
const BSONObj& query,
int limit,
BatchedCommandResponse* response) {
unique_ptr<BatchedDeleteDocument> deleteDoc(new BatchedDeleteDocument);
deleteDoc->setQuery(query);
deleteDoc->setLimit(limit);
unique_ptr<BatchedDeleteRequest> deleteRequest(new BatchedDeleteRequest());
deleteRequest->addToDeletes(deleteDoc.release());
deleteRequest->setWriteConcern(WriteConcernOptions::Majority);
BatchedCommandRequest request(deleteRequest.release());
request.setNS(ns);
BatchedCommandResponse dummyResponse;
if (response == NULL) {
response = &dummyResponse;
}
writeConfigServerDirect(request, response);
return getStatus(*response);
}
Status CatalogManager::updateCollection(const std::string& collNs, const CollectionType& coll) {
fassert(28634, coll.validate());
BatchedCommandResponse response;
Status status = update(CollectionType::ConfigNS,
BSON(CollectionType::fullNs(collNs)),
coll.toBSON(),
true, // upsert
false, // multi
&response);
if (!status.isOK()) {
return Status(status.code(),
str::stream() << "collection metadata write failed: " << response.toBSON()
<< "; status: " << status.toString());
}
return Status::OK();
}
Status CatalogManager::updateDatabase(const std::string& dbName, const DatabaseType& db) {
fassert(28616, db.validate());
BatchedCommandResponse response;
Status status = update(DatabaseType::ConfigNS,
BSON(DatabaseType::name(dbName)),
db.toBSON(),
true, // upsert
false, // multi
&response);
if (!status.isOK()) {
return Status(status.code(),
str::stream() << "database metadata write failed: " << response.toBSON()
<< "; status: " << status.toString());
}
return Status::OK();
}
// static
StatusWith<ShardId> CatalogManager::selectShardForNewDatabase(ShardRegistry* shardRegistry) {
vector<ShardId> allShardIds;
shardRegistry->getAllShardIds(&allShardIds);
if (allShardIds.empty()) {
shardRegistry->reload();
shardRegistry->getAllShardIds(&allShardIds);
if (allShardIds.empty()) {
return Status(ErrorCodes::ShardNotFound, "No shards found");
}
}
auto bestShard = shardRegistry->getShard(allShardIds[0]);
if (!bestShard) {
return {ErrorCodes::ShardNotFound, "Candidate shard disappeared"};
}
ShardStatus bestStatus = bestShard->getStatus();
for (size_t i = 1; i < allShardIds.size(); i++) {
const auto shard = shardRegistry->getShard(allShardIds[i]);
if (!shard) {
continue;
}
const ShardStatus status = shard->getStatus();
if (status < bestStatus) {
bestShard = shard;
bestStatus = status;
}
}
return bestShard->getId();
}
} // namespace mongo
| 35.504274 | 99 | 0.649735 |
af5891bdaf4af38f689b58909b68817b2462baa7 | 857 | cpp | C++ | dev/IconSource/PathIconSource.cpp | ZachT1711/microsoft-ui-xaml | b781f9d71051cc41968d2cf22501de227832e74b | [
"MIT"
] | 3,788 | 2019-05-07T02:41:36.000Z | 2022-03-30T12:34:15.000Z | dev/IconSource/PathIconSource.cpp | ZachT1711/microsoft-ui-xaml | b781f9d71051cc41968d2cf22501de227832e74b | [
"MIT"
] | 6,170 | 2019-05-06T21:32:43.000Z | 2022-03-31T23:46:55.000Z | dev/IconSource/PathIconSource.cpp | ZachT1711/microsoft-ui-xaml | b781f9d71051cc41968d2cf22501de227832e74b | [
"MIT"
] | 532 | 2019-05-07T12:15:58.000Z | 2022-03-31T11:36:26.000Z | // Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See LICENSE in the project root for license information.
#include "pch.h"
#include "common.h"
#include "IconSource.h"
#include "PathIconSource.h"
winrt::IconElement PathIconSource::CreateIconElementCore()
{
winrt::PathIcon pathIcon;
if (auto const data = Data())
{
pathIcon.Data(data);
}
if (const auto newForeground = Foreground())
{
pathIcon.Foreground(newForeground);
}
return pathIcon;
}
winrt::DependencyProperty PathIconSource::GetIconElementPropertyCore(winrt::DependencyProperty sourceProperty)
{
if (sourceProperty == s_DataProperty)
{
return winrt::PathIcon::DataProperty();
}
return __super::GetIconElementPropertyCore(sourceProperty);
}
| 25.205882 | 111 | 0.682614 |
af58dd217a39669eeccb09954b94c546564e8b0a | 955 | cpp | C++ | src/Privileges.cpp | vexyl/MCHawk2 | 9c69795181c5a59ff6c57c36e77d71623df4db8b | [
"MIT"
] | 5 | 2020-09-02T06:58:15.000Z | 2021-12-26T02:29:35.000Z | src/Privileges.cpp | vexyl/MCHawk2 | 9c69795181c5a59ff6c57c36e77d71623df4db8b | [
"MIT"
] | 10 | 2021-11-23T16:10:38.000Z | 2021-12-30T16:05:52.000Z | src/Privileges.cpp | vexyl/MCHawk2 | 9c69795181c5a59ff6c57c36e77d71623df4db8b | [
"MIT"
] | 1 | 2021-07-13T16:55:53.000Z | 2021-07-13T16:55:53.000Z | #include "../include/Privileges.hpp"
#include <algorithm>
void PrivilegeHandler::GivePrivilege(std::string name, std::string priv)
{
auto iter = m_privs.find(name);
if (iter == m_privs.end()) {
// TODO: error check
m_privs.insert(std::make_pair(name, std::vector { priv }));
}
else {
// TODO: Check if already has priv
iter->second.push_back(priv);
}
}
void PrivilegeHandler::TakePrivilege(std::string name, std::string priv)
{
auto iter = m_privs.find(name);
if (iter != m_privs.end()) {
std::remove_if(iter->second.begin(), iter->second.end(), [&](std::string checkPriv) { return priv == checkPriv; });
}
}
priv_result PrivilegeHandler::HasPrivilege(std::string name, std::string priv) const
{
priv_result result{ "Missing priv: " + priv, -1 };
auto iter = m_privs.find(name);
if (iter != m_privs.end()) {
for (auto& obj : iter->second) {
if (obj == priv) {
result.error = 0;
break;
}
}
}
return result;
}
| 22.738095 | 117 | 0.653403 |
af5c39f793d2afa67502e2cd8d8dfca3c8bb0987 | 4,149 | cpp | C++ | Libraries/RobsJuceModules/rapt/Unfinished/MiscAudio/BandwidthConverter.cpp | RobinSchmidt/RS-MET-Preliminary | 6c01cbaad7cce3daa3293c444dd9e4b74e5ebfbe | [
"FTL"
] | null | null | null | Libraries/RobsJuceModules/rapt/Unfinished/MiscAudio/BandwidthConverter.cpp | RobinSchmidt/RS-MET-Preliminary | 6c01cbaad7cce3daa3293c444dd9e4b74e5ebfbe | [
"FTL"
] | null | null | null | Libraries/RobsJuceModules/rapt/Unfinished/MiscAudio/BandwidthConverter.cpp | RobinSchmidt/RS-MET-Preliminary | 6c01cbaad7cce3daa3293c444dd9e4b74e5ebfbe | [
"FTL"
] | null | null | null | template<class T>
T rsBandwidthConverter::bandedgesToCenterFrequency(T fl, T fu)
{
return sqrt(fl*fu);
}
template<class T>
T rsBandwidthConverter::bandedgesToAbsoluteBandwidth(T fl, T fu)
{
return fu - fl;
}
template<class T>
T rsBandwidthConverter::relativeBandwidthToBandedgeFactor(T br)
{
return 0.5*br + sqrt(0.25*br*br + 1);
}
template<class T>
void rsBandwidthConverter::absoluteBandwidthToBandedges(T bw, T fc, T *fl,
T *fu)
{
T br = bandwidthAbsoluteToRelative(bw, fc);
T k = relativeBandwidthToBandedgeFactor(br);
*fl = fc/k;
*fu = fc*k;
}
template<class T>
T rsBandwidthConverter::bandwidthAbsoluteToRelative(T bw, T fc)
{
return bw / fc;
}
template<class T>
T rsBandwidthConverter::absoluteBandwidthToQ(T bw, T fc)
{
return 1.0 / bandwidthAbsoluteToRelative(bw, fc);
}
template<class T>
T rsBandwidthConverter::bandedgesToBandwidthInOctaves(T fl, T fu)
{
return rsLog2(fu/fl);
}
template<class T>
T rsBandwidthConverter::absoluteBandwidthToOctaves(T bw, T fc)
{
T fl, fu;
absoluteBandwidthToBandedges(bw, fc, &fl, &fu);
return bandedgesToBandwidthInOctaves(fl, fu);
}
template<class T>
T rsBandwidthConverter::multipassScalerButterworth(int M, int N, T g)
{
return pow(pow(g, -2.0/M)-1, -0.5/N);
// The formula was derived by considering the analog magnitude-squared response of a N-th order
// Butterworth lowpass applied M times, given by: g^2(w) = (1 / (1 + (w^2/w0^2)^N))^M. To find
// the frequency w, where the magnitude-squared response has some particular value p, we solve
// for w. Chosing some particluar value for g (such as g = sqrt(0.5) for the -3.01 dB
// "half-power" point), we can compute the scaler s, at which we see this value of p. Scaling our
// cutoff frequency w0 by 1/s, we shift the half-power point to w0 in the multipass case.
// \todo to apply this to bilinear-transform based digital filters, we should replace w by
// wd = tan(...) and solve....
}
// for energy normalization, use the total energy formula (that i have obtained via sage)
// E = pi*gamma(M - 1/2/N)/(N*gamma(M)*gamma(-1/2/N + 1)*sin(1/2*pi/N)) // 1/2 -> 0.5
// E = pi*gamma(M - 0.5/N)/(N*gamma(M)*gamma(-0.5/N + 1)*sin(0.5*pi/N)) // k = 0.5/N
// k = 0.5/N
// E = pi*gamma(M-k) / (N*gamma(M)*gamma(1-k)*sin(k*pi))
// maybe compare the energy normalization to the formula above
// this formula has been implemented in
// rsPrototypeDesigner<T>::butterworthEnergy
template<class T>
T rsBandwidthConverter::lowpassResoGainToQ(T a)
{
a *= a;
T b = sqrt(a*a - a);
T P = T(0.5) * (a + b); // P := Q^2
return sqrt(P);
// The formula was derived by considering the magnitude response of a 2nd order analog lowpass
// with transfer function H(s) = 1 / (1 + s/Q + s^2). The magnitude-squared response of such a
// filter is given by: M(w) = Q^2 / (Q^2 (w^2 - 1)^2 + w^2). This function has maxima of height
// (4 Q^4)/(4 Q^2 - 1) at w = -1/2 sqrt(4 - 2/Q^2). The expression for the height was solved
// for Q. We get a quadratic equation for P := Q^2. The correct solution of the two was picked
// empirically. It was also observed empirically that the formula also works for highpass
// filters.
}
// ToDo: implement a formula, that computes the exact frequency of the resonance peak, i.e. the
// w at which the derivative of the mag-response is zero. This could be useful, if the filter
// designer wants to set the peak-gain frequency rather than the resonance frequency. These two
// frequencies are different because each pole sits on the skirt of the other. For high Q,
// they are approximately the same but for low Q, the peak-freq will be appreciably below the
// nominal reso-freq in the lowpass case - in fact, for Q <= 1/sqrt(2), the peak will be at DC.
// A filter design algo could first fix the resonance gain, then compute the Q via the function
// above, then compute the peak-freq, then scale the cutoff accordingly, namely by the reciprocal
// of the computed (normalized) peak-freq.
/*
More formulas that need some numeric checks:
fu = fl * 2^bo
fc = fl * sqrt(2^bo) = fl * 2^(bo/2)
k = 2^(bo/2)
Q = 2^(bo/2) / (2^bo - 1)
*/ | 35.767241 | 100 | 0.692697 |
af5defc1c825bc5680eab5e811e314bbc2dc0de5 | 404 | cpp | C++ | naive_simulation_works/systemc_for_dummies/full_adder/MyTestBenchMonitor.cpp | VSPhaneendraPaluri/pvsdrudgeworks | 5827f45567eecbcf0bb606de6adb1fb94fe2d8c6 | [
"MIT"
] | null | null | null | naive_simulation_works/systemc_for_dummies/full_adder/MyTestBenchMonitor.cpp | VSPhaneendraPaluri/pvsdrudgeworks | 5827f45567eecbcf0bb606de6adb1fb94fe2d8c6 | [
"MIT"
] | null | null | null | naive_simulation_works/systemc_for_dummies/full_adder/MyTestBenchMonitor.cpp | VSPhaneendraPaluri/pvsdrudgeworks | 5827f45567eecbcf0bb606de6adb1fb94fe2d8c6 | [
"MIT"
] | null | null | null | #include "MyTestBenchMonitor.h"
void MyTestBenchMonitor::Display_Patterns()
{
cout << "At time : " << sc_time_stamp();
//next_trigger(TBMonitor_a. | TBMonitor_b | TBMonitor_c);
cout << "\ta = " << TBMonitor_a << "\tb = " << TBMonitor_b << "\tc_in = " << TBMonitor_c;
//next_trigger(TBMonitor_sum | TBMonitor_sum);
cout << "\tCarry = " << TBMonitor_carry << "\tSum = " << TBMonitor_sum << endl;
}
| 33.666667 | 90 | 0.648515 |
af5dfb203e9dceb2ef6970ffe47f34b30138073b | 17,261 | cpp | C++ | examples/lowlevel/benchmark_map.cpp | hrissan/crablib | db86e5f52acddcc233aec755d5fce0e6f19c0e21 | [
"MIT"
] | 3 | 2020-02-13T02:08:06.000Z | 2020-10-06T16:26:30.000Z | examples/lowlevel/benchmark_map.cpp | hrissan/crablib | db86e5f52acddcc233aec755d5fce0e6f19c0e21 | [
"MIT"
] | null | null | null | examples/lowlevel/benchmark_map.cpp | hrissan/crablib | db86e5f52acddcc233aec755d5fce0e6f19c0e21 | [
"MIT"
] | null | null | null | // Copyright (c) 2007-2020, Grigory Buteyko aka Hrissan
// Licensed under the MIT License. See LICENSE for details.
#include <array>
#include <chrono>
#include <functional>
#include <iomanip>
#include <iostream>
#include <map>
#include <random>
#include <set>
#include <unordered_map>
#include <unordered_set>
#include <crab/crab.hpp>
static size_t count_zeroes(uint64_t val) {
for (size_t i = 0; i != sizeof(val) * 8; ++i)
if ((val & (uint64_t(1) << i)) != 0)
return i;
return sizeof(val) * 8;
}
struct Random {
explicit Random(uint64_t random_seed = 0) : random_seed(random_seed) {}
uint64_t rnd() { // MMIX by Donald Knuth
random_seed = 6364136223846793005 * random_seed + 1442695040888963407;
return random_seed;
}
private:
uint64_t random_seed;
};
static constexpr size_t LEVELS = 10;
template<class T>
class SkipList {
public:
struct Item { // We allocate only part of it
T value;
Item *prev;
size_t height;
Item *s_nexts[LEVELS];
Item *&nexts(size_t i) {
if (i >= height)
throw std::logic_error("out of nexts");
return s_nexts[i];
}
};
struct InsertPtr {
std::array<Item *, LEVELS> previous_levels{};
Item *next() const { return previous_levels.at(0)->nexts(0); }
};
SkipList() {
tail_head.value = T{};
tail_head.prev = &tail_head;
tail_head.height = LEVELS;
for (size_t i = 0; i != LEVELS; ++i)
tail_head.nexts(i) = &tail_head;
}
~SkipList() {
while (tail_head.prev != &tail_head) {
erase_begin();
// print();
}
}
int lower_bound(const T &value, InsertPtr *insert_ptr) {
Item *curr = &tail_head;
size_t current_height = LEVELS - 1;
int hops = 0;
Item **p_levels = insert_ptr->previous_levels.data();
while (true) {
hops += 1;
Item *next_curr = curr->s_nexts[current_height];
if (next_curr == &tail_head || next_curr->value >= value) {
p_levels[current_height] = curr;
if (current_height == 0)
break;
current_height -= 1;
continue;
}
curr = next_curr;
}
return hops;
}
int count(const T &value) {
InsertPtr insert_ptr;
lower_bound(value, &insert_ptr);
Item *del_item = insert_ptr.next();
if (del_item == &tail_head || del_item->value != value)
return 0;
return 1;
}
std::pair<Item *, bool> insert(const T &value) {
InsertPtr insert_ptr;
lower_bound(value, &insert_ptr);
Item *next_curr = insert_ptr.next();
if (next_curr != &tail_head && next_curr->value == value)
return std::make_pair(next_curr, false);
// static uint64_t keybuf[4] = {};
// auto ctx = blake2b_ctx{};
// blake2b_init(&ctx, 32, nullptr, 0);
// blake2b_update(&ctx, &keybuf, sizeof(keybuf));
// blake2b_final(&ctx, &keybuf);
const size_t height = std::min<size_t>(LEVELS, 1 + count_zeroes(random.rnd()) / 3); // keybuf[0]
Item *new_item =
reinterpret_cast<Item *>(malloc(sizeof(Item) - (LEVELS - height) * sizeof(Item *))); // new Item{};
new_item->prev = insert_ptr.previous_levels.at(0);
next_curr->prev = new_item;
new_item->height = height;
size_t i = 0;
for (; i != height; ++i) {
new_item->nexts(i) = insert_ptr.previous_levels.at(i)->nexts(i);
insert_ptr.previous_levels.at(i)->nexts(i) = new_item;
}
// for(; i != LEVELS; ++i)
// new_item->nexts(i) = nullptr;
new_item->value = value;
return std::make_pair(new_item, true);
}
bool erase(const T &value) {
InsertPtr insert_ptr;
lower_bound(value, &insert_ptr);
Item *del_item = insert_ptr.next();
if (del_item == &tail_head || del_item->value != value)
return false;
del_item->nexts(0)->prev = del_item->prev;
del_item->prev = nullptr;
for (size_t i = 0; i != del_item->height; ++i)
if (del_item->nexts(i)) {
insert_ptr.previous_levels.at(i)->nexts(i) = del_item->nexts(i);
del_item->nexts(i) = nullptr;
}
free(del_item); // delete del_item;
return true;
}
void erase_begin() {
Item *del_item = tail_head.nexts(0);
if (del_item == &tail_head)
throw std::logic_error("deleting head_tail");
Item *prev_item = del_item->prev;
del_item->nexts(0)->prev = prev_item;
del_item->prev = nullptr;
for (size_t i = 0; i != del_item->height; ++i) {
prev_item->nexts(i) = del_item->nexts(i);
del_item->nexts(i) = nullptr;
}
free(del_item); // delete del_item;
}
bool empty() const { return tail_head.prev == &tail_head; }
Item *end(const T &v);
void print() {
Item *curr = &tail_head;
std::array<size_t, LEVELS> level_counts{};
std::cerr << "---- list ----" << std::endl;
while (true) {
if (curr == &tail_head)
std::cerr << std::setw(4) << "end"
<< " | ";
else
std::cerr << std::setw(4) << curr->value << " | ";
for (size_t i = 0; i != curr->height; ++i) {
level_counts[i] += 1;
if (curr == &tail_head || curr->nexts(i) == &tail_head)
std::cerr << std::setw(4) << "end"
<< " ";
else
std::cerr << std::setw(4) << curr->nexts(i)->value << " ";
}
for (size_t i = curr->height; i != LEVELS; ++i)
std::cerr << std::setw(4) << "_"
<< " ";
if (curr->prev == &tail_head)
std::cerr << "| " << std::setw(4) << "end" << std::endl;
else
std::cerr << "| " << std::setw(4) << curr->prev->value << std::endl;
if (curr == tail_head.prev)
break;
curr = curr->nexts(0);
}
std::cerr << " #"
<< " | ";
for (size_t i = 0; i != LEVELS; ++i) {
std::cerr << std::setw(4) << level_counts[i] << " ";
}
std::cerr << "| " << std::endl;
}
private:
Item tail_head;
Random random;
};
struct HeapElement {
crab::IntrusiveHeapIndex heap_index;
uint64_t value = 0;
bool operator<(const HeapElement &other) const { return value < other.value; }
};
// typical benchmark
// skiplist insert of 1000000 hashes, inserted 632459, seconds=1.486
// skiplist get of 1000000 hashes, hops 37.8428, seconds=1.428
// skiplist delete of 1000000 hashes, found 400314, seconds=1.565
// std::set insert of 1000000 hashes, inserted 632459, seconds=0.782
// std::set get of 1000000 hashes, found_counter 1000000, seconds=0.703
// std::set delete of 1000000 hashes, found 400314, seconds=0.906
std::vector<uint64_t> fill_random(uint64_t seed, size_t count) {
Random random(seed);
std::vector<uint64_t> result;
for (size_t i = 0; i != count; ++i)
result.push_back(random.rnd() % count);
return result;
}
void benchmark_timers() {
constexpr size_t COUNT = 1000000;
constexpr size_t COUNT_MOVE = 100;
crab::RunLoop runloop;
Random random(12345);
std::vector<std::chrono::steady_clock::duration> durs;
std::list<crab::Timer> timers;
for (size_t i = 0; i != COUNT; ++i) {
timers.emplace_back(crab::empty_handler);
std::chrono::duration<double> delay(random.rnd() % COUNT);
durs.push_back(std::chrono::duration_cast<std::chrono::steady_clock::duration>(delay));
}
auto idea_start = std::chrono::high_resolution_clock::now();
std::list<crab::Timer>::iterator it = timers.begin();
for (size_t i = 0; it != timers.end(); ++i, ++it) {
it->once(durs[i]);
}
auto idea_ms =
std::chrono::duration_cast<std::chrono::milliseconds>(std::chrono::high_resolution_clock::now() - idea_start);
std::cout << "Set Timers (random delay)"
<< " count=" << COUNT << ", seconds=" << double(idea_ms.count()) / 1000 << std::endl;
idea_start = std::chrono::high_resolution_clock::now();
for (size_t j = 0; j != COUNT_MOVE; ++j) {
it = timers.begin();
for (size_t i = 0; it != timers.end(); ++i, ++it) {
it->once(durs[i] + std::chrono::steady_clock::duration{1 + j});
}
}
idea_ms =
std::chrono::duration_cast<std::chrono::milliseconds>(std::chrono::high_resolution_clock::now() - idea_start);
std::cout << "Moving Timers to the future"
<< " count=" << COUNT_MOVE << "*" << COUNT << ", seconds=" << double(idea_ms.count()) / 1000
<< std::endl;
idea_start = std::chrono::high_resolution_clock::now();
it = timers.begin();
for (size_t i = 0; it != timers.end(); ++i, ++it) {
it->cancel();
}
idea_ms =
std::chrono::duration_cast<std::chrono::milliseconds>(std::chrono::high_resolution_clock::now() - idea_start);
std::cout << "Cancel Timers"
<< " count=" << COUNT << ", seconds=" << double(idea_ms.count()) / 1000 << std::endl;
}
template<class T, class Op>
void benchmark_op(const char *str, const std::vector<T> &samples, Op op) {
size_t found_counter = 0;
auto idea_start = std::chrono::high_resolution_clock::now();
for (const auto &sample : samples)
found_counter += op(sample);
auto idea_ms =
std::chrono::duration_cast<std::chrono::milliseconds>(std::chrono::high_resolution_clock::now() - idea_start);
std::cout << str << " count=" << samples.size() << " hits=" << found_counter
<< ", seconds=" << double(idea_ms.count()) / 1000 << std::endl;
}
void benchmark_sets() {
size_t count = 1000000;
std::vector<uint64_t> to_insert = fill_random(1, count);
std::vector<uint64_t> to_count = fill_random(2, count);
std::vector<uint64_t> to_erase = fill_random(3, count);
std::vector<HeapElement *> el_to_insert;
std::vector<HeapElement *> el_to_count;
std::vector<HeapElement *> el_to_erase;
std::map<uint64_t, HeapElement> heap_storage;
for (auto s : to_insert)
el_to_insert.push_back(&heap_storage[s]);
for (auto s : to_count)
el_to_count.push_back(&heap_storage[s]);
for (auto s : to_erase)
el_to_erase.push_back(&heap_storage[s]);
crab::IntrusiveHeap<HeapElement, &HeapElement::heap_index, std::less<HeapElement>> int_heap;
int_heap.reserve(1000000);
benchmark_op(
"OurHeap insert ", el_to_insert, [&](HeapElement *sample) -> size_t { return int_heap.insert(*sample); });
benchmark_op(
"OurHeap erase ", el_to_erase, [&](HeapElement *sample) -> size_t { return int_heap.erase(*sample); });
benchmark_op("OurHeap pop_front ", el_to_insert, [&](HeapElement *sample) -> size_t {
if (int_heap.empty())
return 0;
int_heap.pop_front();
return 1;
});
std::set<uint64_t> test_set;
benchmark_op(
"std::set insert ", to_insert, [&](uint64_t sample) -> size_t { return test_set.insert(sample).second; });
benchmark_op("std::set count ", to_count, [&](uint64_t sample) -> size_t { return test_set.count(sample); });
benchmark_op("std::set erase ", to_erase, [&](uint64_t sample) -> size_t { return test_set.erase(sample); });
benchmark_op("std::set pop_front ", to_insert, [&](uint64_t sample) -> size_t {
if (!test_set.empty()) {
test_set.erase(test_set.begin());
return 1;
}
return 0;
});
std::unordered_set<uint64_t> test_uset;
benchmark_op(
"std::uset insert ", to_insert, [&](uint64_t sample) -> size_t { return test_uset.insert(sample).second; });
benchmark_op("std::uset count ", to_count, [&](uint64_t sample) -> size_t { return test_uset.count(sample); });
benchmark_op("std::uset erase ", to_erase, [&](uint64_t sample) -> size_t { return test_uset.erase(sample); });
benchmark_op("std::uset pop_front ", to_insert, [&](uint64_t sample) -> size_t {
if (!test_uset.empty()) {
test_uset.erase(test_uset.begin());
return 1;
}
return 0;
});
SkipList<uint64_t> skip_list;
benchmark_op(
"skip_list insert ", to_insert, [&](uint64_t sample) -> size_t { return skip_list.insert(sample).second; });
benchmark_op("skip_list count ", to_count, [&](uint64_t sample) -> size_t { return skip_list.count(sample); });
benchmark_op("skip_list erase ", to_erase, [&](uint64_t sample) -> size_t { return skip_list.erase(sample); });
// immer::set<uint64_t> immer_set;
// benchmark_op("immer insert ", to_insert, [&](uint64_t sample)->size_t{
// size_t was_size = immer_set.size();
// immer_set = immer_set.insert(sample);
// return immer_set.size() - was_size;
// });
// benchmark_op("immer count ", to_count, [&](uint64_t sample)->size_t{ return immer_set.count(sample); });
// benchmark_op("immer erase ", to_count, [&](uint64_t sample)->size_t{
// size_t was_size = immer_set.size();
// immer_set = immer_set.erase(sample);
// return was_size - immer_set.size();
// });
// const auto v0 = immer::vector<int>{};
// const auto v1 = v0.push_back(13);
// assert(v0.size() == 0 && v1.size() == 1 && v1[0] == 13);
//
// const auto v2 = v1.set(0, 42);
// assert(v1[0] == 13 && v2[0] == 42);
}
template<typename T>
struct BucketsGetter {
static size_t bucket_count(const T &) { return 0; }
};
template<>
struct BucketsGetter<std::unordered_map<std::string, size_t>> {
static size_t bucket_count(const std::unordered_map<std::string, size_t> &v) { return v.bucket_count(); }
};
constexpr size_t COUNT = 1000000;
template<typename K, typename T, size_t max_key>
class ArrayAdapter { // Array large enough to index by K
public:
void emplace(K k, T t) {
std::pair<T, bool> &pa = storage.at(k);
if (pa.second)
return;
storage_size += 1;
pa = std::make_pair(t, true);
}
size_t size() const { return 1000; }
size_t count(K k) const { return storage.at(k).second ? 1 : 0; }
private:
size_t storage_size = 0;
std::array<std::pair<T, bool>, max_key + 1> storage;
};
template<typename T, typename S>
void benchmark(std::function<T(size_t)> items_gen) {
S storage;
std::mt19937 rnd;
std::vector<T> to_insert;
std::vector<T> to_search;
for (size_t i = 0; i != COUNT; ++i) {
to_insert.push_back(items_gen(rnd() % COUNT));
to_search.push_back(items_gen(rnd() % COUNT));
}
auto tp = std::chrono::high_resolution_clock::now();
auto start = tp;
size_t counter = 0;
struct Sample {
int mksec;
size_t counter;
size_t buckets;
};
std::vector<Sample> long_samples;
long_samples.reserve(to_insert.size());
for (const auto &key : to_insert) {
storage.emplace(key, ++counter);
auto now = std::chrono::high_resolution_clock::now();
auto mksec = std::chrono::duration_cast<std::chrono::microseconds>(now - tp).count();
if (mksec > 100) {
auto bc = BucketsGetter<S>::bucket_count(storage);
long_samples.emplace_back(Sample{int(mksec), counter, bc});
}
tp = now;
}
auto now = std::chrono::high_resolution_clock::now();
auto mksec = std::chrono::duration_cast<std::chrono::microseconds>(now - start).count();
std::cout << "inserted " << storage.size() << ", mksec=" << mksec << std::endl;
for (const auto &p : long_samples)
std::cout << "mksec=" << p.mksec << " counter=" << p.counter << " buckets=" << p.buckets << std::endl;
start = now;
counter = 0;
for (const auto &key : to_search)
counter += storage.count(key);
now = std::chrono::high_resolution_clock::now();
mksec = std::chrono::duration_cast<std::chrono::microseconds>(now - start).count();
std::cout << "searched " << to_search.size() << ", found=" << counter << ", mksec=" << mksec << std::endl;
}
std::string string_gen(size_t c) {
return std::to_string(c % COUNT) + std::string("SampleSampleSampleSampleSampleSample");
}
int int_gen(size_t c) { return int(c); }
int small_int_gen(size_t c) { return int(c % 256); }
struct OrderId {
uint64_t arr[4] = {};
bool operator==(const OrderId &b) const {
return arr[0] == b.arr[0] && arr[1] == b.arr[1] && arr[2] == b.arr[2] && arr[3] == b.arr[3];
}
bool operator!=(const OrderId &b) const { return !operator==(b); }
};
OrderId order_id_gen(size_t c) {
OrderId id;
id.arr[0] = 12345678;
id.arr[1] = 87654321;
id.arr[2] = c % COUNT;
id.arr[3] = 88888888;
return id;
}
template<typename T>
inline void hash_combine(std::size_t &seed, T const &v) {
seed ^= std::hash<T>()(v) + 0x9e3779b9 + (seed << 6) + (seed >> 2);
// seed ^= std::hash<T>()(v) + 0x9e3779b9 * seed;
}
namespace std {
template<>
struct hash<OrderId> {
std::size_t operator()(const OrderId &w) const {
size_t hash = 0;
hash_combine(hash, w.arr[0]);
hash_combine(hash, w.arr[1]);
hash_combine(hash, w.arr[2]);
hash_combine(hash, w.arr[3]);
return hash;
}
};
} // namespace std
int main() {
benchmark_timers();
benchmark_sets();
std::cout << "Testing small std::map<int> count=" << COUNT << std::endl;
benchmark<int, std::map<int, size_t>>(small_int_gen);
std::cout << "Testing small std::unordered<int> count=" << COUNT << std::endl;
benchmark<int, std::unordered_map<int, size_t>>(small_int_gen);
std::cout << "Testing small ArrayAdapter count=" << COUNT << std::endl;
benchmark<int, ArrayAdapter<int, size_t, 2000>>(small_int_gen);
std::cout << "----" << std::endl;
std::cout << "Testing std::map<std::string> count=" << COUNT << std::endl;
benchmark<std::string, std::map<std::string, size_t>>(string_gen);
std::cout << "Testing std::unordered<std::string> count=" << COUNT << std::endl;
benchmark<std::string, std::unordered_map<std::string, size_t>>(string_gen);
std::cout << "Testing std::unordered<OrderId> count=" << COUNT << std::endl;
benchmark<OrderId, std::unordered_map<OrderId, size_t>>(order_id_gen);
std::cout << "----" << std::endl;
std::cout << "Testing std::map<int> count=" << COUNT << std::endl;
benchmark<int, std::map<int, size_t>>(int_gen);
std::cout << "Testing std::unordered<int> count=" << COUNT << std::endl;
benchmark<int, std::unordered_map<int, size_t>>(int_gen);
std::cout << "----" << std::endl;
return 0;
}
| 33.911591 | 115 | 0.639071 |
af5e21470c196899820ebe9cf8bd7082c1cde99a | 834 | cpp | C++ | Language_Coder/문자열2/형성평가/FormativeString201.cpp | NadanKim/CodingTest_JUNGOL | f1f448eb5a107b59bfa196c2682ba89e89431358 | [
"MIT"
] | null | null | null | Language_Coder/문자열2/형성평가/FormativeString201.cpp | NadanKim/CodingTest_JUNGOL | f1f448eb5a107b59bfa196c2682ba89e89431358 | [
"MIT"
] | null | null | null | Language_Coder/문자열2/형성평가/FormativeString201.cpp | NadanKim/CodingTest_JUNGOL | f1f448eb5a107b59bfa196c2682ba89e89431358 | [
"MIT"
] | null | null | null | #include "FormativeString201.h"
/// <summary>
/// 문제
/// 공백을 포함한 문자열을 입력받아 각 단어로 분리하여 문자열 배열에 저장한 후 입력순서의 반대 순서로 출력하는 프로그램을 작성하시오.
/// 문자열의 길이는 100자 이하이다.
///
/// 입력 예
/// C++ Programing jjang!!
///
/// 출력 예
/// jjang!!
/// Programing
/// C++
///
/// Hint!
/// [문장을 단어로 나누기](http://comkiwer.tistory.com/entry/C-CPP-%EA%B3%B5%EB%B0%B1%EC%9D%84-%ED%8F%AC%ED%95%A8%ED%95%9C-%EB%AC%B8%EC%9E%90%EC%97%B4-split%ED%95%98%EA%B8%B0?category=734118)
///
/// http://www.jungol.co.kr/bbs/board.php?bo_table=pbank&wr_id=89&sca=10f0
/// </summary>
void FormativeString201::Code()
{
string str;
std::getline(std::cin, str);
string word;
vector<string> words;
for (stringstream ss{ str }; ss >> word;)
{
words.push_back(word);
}
for (int i = static_cast<int>(words.size()) - 1; i >= 0; i--)
{
std::cout << words[i] << '\n';
}
} | 21.947368 | 182 | 0.609113 |
af60f971a6f1c6055b70c3a18f62b8330d3fd656 | 439 | cpp | C++ | libs/libc/source/string/memccpy.cpp | zhiayang/nx | 0d9da881f67ec351244abd72e1f3884816b48f5b | [
"Apache-2.0"
] | 16 | 2019-03-14T19:45:02.000Z | 2022-02-06T19:18:08.000Z | libs/libc/source/string/memccpy.cpp | zhiayang/nx | 0d9da881f67ec351244abd72e1f3884816b48f5b | [
"Apache-2.0"
] | 1 | 2020-05-08T08:40:02.000Z | 2020-05-08T13:27:59.000Z | libs/libc/source/string/memccpy.cpp | zhiayang/nx | 0d9da881f67ec351244abd72e1f3884816b48f5b | [
"Apache-2.0"
] | 2 | 2021-01-16T20:42:05.000Z | 2021-12-01T23:37:18.000Z | // memccpy.cpp
// Copyright (c) 2014 - 2016, zhiayang
// Licensed under the Apache License Version 2.0.
#include <stddef.h>
extern "C" void* memccpy(void* dest_ptr, const void* src_ptr, int c, size_t n)
{
unsigned char* dest = (unsigned char*) dest_ptr;
const unsigned char* src = (const unsigned char*) src_ptr;
for(size_t i = 0; i < n; i++)
{
if((dest[i] = src[i]) == (unsigned char) c)
return dest + i + 1;
}
return NULL;
}
| 25.823529 | 78 | 0.649203 |
af661942888ffecea18cb24d30e3d05615c1592e | 3,693 | cpp | C++ | gm/daa.cpp | NearTox/Skia | 8b7e0616161fff86ecbd8938b90600d72b8d5c1d | [
"BSD-3-Clause"
] | null | null | null | gm/daa.cpp | NearTox/Skia | 8b7e0616161fff86ecbd8938b90600d72b8d5c1d | [
"BSD-3-Clause"
] | null | null | null | gm/daa.cpp | NearTox/Skia | 8b7e0616161fff86ecbd8938b90600d72b8d5c1d | [
"BSD-3-Clause"
] | null | null | null | /*
* Copyright 2018 Google Inc.
*
* Use of this source code is governed by a BSD-style license that can be
* found in the LICENSE file.
*/
#include "gm/gm.h"
#include "include/core/SkCanvas.h"
#include "include/core/SkColor.h"
#include "include/core/SkFont.h"
#include "include/core/SkPaint.h"
#include "include/core/SkPathBuilder.h"
#include "include/core/SkPoint.h"
#include "include/core/SkTypes.h"
// This GM shows off a flaw in delta-based rasterizers (DAA, CCPR, etc.).
// See also the bottom of dashing4 and skia:6886.
static const int K = 49;
DEF_SIMPLE_GM(daa, canvas, K + 350, 5 * K) {
SkPaint paint;
paint.setAntiAlias(true);
{
paint.setColor(SK_ColorBLACK);
canvas->drawString(
"Should be a green square with no red showing through.", K * 1.5f, K * 0.5f, SkFont(),
paint);
paint.setColor(SK_ColorRED);
canvas->drawRect({0, 0, K, K}, paint);
SkPoint tri1[] = {{0, 0}, {K, K}, {0, K}, {0, 0}};
SkPoint tri2[] = {{0, 0}, {K, K}, {K, 0}, {0, 0}};
SkPath path = SkPathBuilder()
.addPolygon(tri1, SK_ARRAY_COUNT(tri1), false)
.addPolygon(tri2, SK_ARRAY_COUNT(tri2), false)
.detach();
paint.setColor(SK_ColorGREEN);
canvas->drawPath(path, paint);
}
canvas->translate(0, K);
{
paint.setColor(SK_ColorBLACK);
canvas->drawString(
"Adjacent rects, two draws. Blue then green, no red?", K * 1.5f, K * 0.5f, SkFont(),
paint);
paint.setColor(SK_ColorRED);
canvas->drawRect({0, 0, K, K}, paint);
{
SkPath path = SkPath::Polygon({{0, 0}, {0, K}, {K * 0.5f, K}, {K * 0.5f, 0}}, false);
paint.setColor(SK_ColorBLUE);
canvas->drawPath(path, paint);
}
{
SkPath path = SkPath::Polygon({{K * 0.5f, 0}, {K * 0.5f, K}, {K, K}, {K, 0}}, false);
paint.setColor(SK_ColorGREEN);
canvas->drawPath(path, paint);
}
}
canvas->translate(0, K);
{
paint.setColor(SK_ColorBLACK);
canvas->drawString(
"Adjacent rects, wound together. All green?", K * 1.5f, K * 0.5f, SkFont(), paint);
paint.setColor(SK_ColorRED);
canvas->drawRect({0, 0, K, K}, paint);
{
SkPath path = SkPathBuilder()
.addPolygon({{0, 0}, {0, K}, {K * 0.5f, K}, {K * 0.5f, 0}}, false)
.addPolygon({{K * 0.5f, 0}, {K * 0.5f, K}, {K, K}, {K, 0}}, false)
.detach();
paint.setColor(SK_ColorGREEN);
canvas->drawPath(path, paint);
}
}
canvas->translate(0, K);
{
paint.setColor(SK_ColorBLACK);
canvas->drawString(
"Adjacent rects, wound opposite. All green?", K * 1.5f, K * 0.5f, SkFont(), paint);
paint.setColor(SK_ColorRED);
canvas->drawRect({0, 0, K, K}, paint);
{
SkPath path = SkPathBuilder()
.addPolygon({{0, 0}, {0, K}, {K * 0.5f, K}, {K * 0.5f, 0}}, false)
.addPolygon({{K * 0.5f, 0}, {K, 0}, {K, K}, {K * 0.5f, K}}, false)
.detach();
paint.setColor(SK_ColorGREEN);
canvas->drawPath(path, paint);
}
}
canvas->translate(0, K);
{
paint.setColor(SK_ColorBLACK);
canvas->drawString(
"One poly, wound opposite. All green?", K * 1.5f, K * 0.5f, SkFont(), paint);
paint.setColor(SK_ColorRED);
canvas->drawRect({0, 0, K, K}, paint);
SkPath path = SkPath::Polygon(
{{K * 0.5f, 0},
{0, 0},
{0, K},
{K * 0.5f, K},
{K * 0.5f, 0},
{K, 0},
{K, K},
{K * 0.5f, K}},
false);
paint.setColor(SK_ColorGREEN);
canvas->drawPath(path, paint);
}
}
| 27.766917 | 94 | 0.541565 |
af6865b70dca6d51f0e12fc6ac104705796886d2 | 1,670 | hpp | C++ | apps/stochastic_lasso/src/prox_grad.hpp | daiwei89/wdai_petuum_public | 4068859897061201d0a63630a3da6011b0d0f75f | [
"BSD-3-Clause"
] | null | null | null | apps/stochastic_lasso/src/prox_grad.hpp | daiwei89/wdai_petuum_public | 4068859897061201d0a63630a3da6011b0d0f75f | [
"BSD-3-Clause"
] | null | null | null | apps/stochastic_lasso/src/prox_grad.hpp | daiwei89/wdai_petuum_public | 4068859897061201d0a63630a3da6011b0d0f75f | [
"BSD-3-Clause"
] | null | null | null | #pragma once
#include <vector>
#include <ml/include/ml.hpp>
#include <petuum_ps_common/include/petuum_ps.hpp>
#include <random>
namespace lasso {
struct ProxGradConfig {
int worker_rank = -1;
int feature_start = 0;
int feature_end = 0;
int num_samples = 0;
int num_reps = 1;
};
class ProxGrad {
public:
ProxGrad(const ProxGradConfig& config);
void ProxStep(
const std::vector<petuum::ml::SparseFeature<float>*>& X_cols,
const petuum::ml::DenseFeature<float>& y,
float lr, int my_clock);
float EvalSqLoss(
const petuum::ml::DenseFeature<float>& y);
float EvalL1Penalty() const;
// Cound # of non-zeros in beta (sharded to workers).
int EvalBetaNNZ() const;
int GetSampleSize() const {
return num_feature_samples_;
}
private:
void SoftThreshold(float threshold,
petuum::ml::DenseFeature<float>* x);
private:
int worker_rank_;
int num_workers_;
int num_samples_;
int feature_start_;
int feature_end_;
int num_features_; // # features in this worker.
// stochastic version uses only this many coordinates in each step
int num_feature_samples_;
int num_reps_;
petuum::ml::DenseFeature<float> beta_; // [num_features_ x 1]
petuum::ml::DenseFeature<float> r_; // [num_samples_ x 1]
//petuum::ml::DenseFeature<float> delta_; // [num_features_ x 1]
petuum::Table<float> w_table_;
petuum::Table<float> unused_table_;
petuum::Table<int64_t> staleness_table_;
std::random_device r;
std::seed_seq seed2{r(), r(), r(), r(), r(), r(), r(), r()};
std::mt19937 rand_eng{seed2};
std::uniform_real_distribution<float> uniform_dist{0, 1};
};
} // namespace lasso
| 25.30303 | 68 | 0.691617 |
af69030ff4cfb16d97d5be413074405e5b354d61 | 883 | cxx | C++ | panda/src/gobj/timerQueryContext.cxx | cmarshall108/panda3d-python3 | 8bea2c0c120b03ec1c9fd179701fdeb7510bb97b | [
"PHP-3.0",
"PHP-3.01"
] | null | null | null | panda/src/gobj/timerQueryContext.cxx | cmarshall108/panda3d-python3 | 8bea2c0c120b03ec1c9fd179701fdeb7510bb97b | [
"PHP-3.0",
"PHP-3.01"
] | null | null | null | panda/src/gobj/timerQueryContext.cxx | cmarshall108/panda3d-python3 | 8bea2c0c120b03ec1c9fd179701fdeb7510bb97b | [
"PHP-3.0",
"PHP-3.01"
] | null | null | null | /**
* PANDA 3D SOFTWARE
* Copyright (c) Carnegie Mellon University. All rights reserved.
*
* All use of this software is subject to the terms of the revised BSD
* license. You should have received a copy of this license along
* with this source code in a file named "LICENSE."
*
* @file timerQueryContext.cxx
* @author rdb
* @date 2014-08-22
*/
#include "timerQueryContext.h"
TypeHandle TimerQueryContext::_type_handle;
/**
* Returns the timestamp that is the result of this timer query. There's no
* guarantee about which clock this uses, the only guarantee is that
* subtracting a start time from an end time should yield a time in seconds.
* If is_answer_ready() did not return true, this function may block before it
* returns.
*
* It is only valid to call this from the draw thread.
*/
double TimerQueryContext::
get_timestamp() const {
return 0.0;
}
| 28.483871 | 78 | 0.730464 |
af6c046a383a54748e3ec6ccb3a3a7a5f9d7014b | 18,315 | cpp | C++ | termsrv/newclient/clshell/propperf.cpp | npocmaka/Windows-Server-2003 | 5c6fe3db626b63a384230a1aa6b92ac416b0765f | [
"Unlicense"
] | 17 | 2020-11-13T13:42:52.000Z | 2021-09-16T09:13:13.000Z | termsrv/newclient/clshell/propperf.cpp | sancho1952007/Windows-Server-2003 | 5c6fe3db626b63a384230a1aa6b92ac416b0765f | [
"Unlicense"
] | 2 | 2020-10-19T08:02:06.000Z | 2020-10-19T08:23:18.000Z | termsrv/newclient/clshell/propperf.cpp | sancho1952007/Windows-Server-2003 | 5c6fe3db626b63a384230a1aa6b92ac416b0765f | [
"Unlicense"
] | 14 | 2020-11-14T09:43:20.000Z | 2021-08-28T08:59:57.000Z | //
// propperf.cpp: local resources property sheet dialog proc
//
// Tab E
//
// Copyright Microsoft Corporation 2000
// nadima
#include "stdafx.h"
#define TRC_GROUP TRC_GROUP_UI
#define TRC_FILE "propperf"
#include <atrcapi.h>
#include "sh.h"
#include "commctrl.h"
#include "propperf.h"
CPropPerf* CPropPerf::_pPropPerfInstance = NULL;
//
// Lookup tables
//
//
// Controls that need to be disabled/enabled
// during connection (for progress animation)
//
CTL_ENABLE connectingDisableCtlsPPerf[] = {
{UI_IDC_STATIC_CHOOSE_SPEED, FALSE},
{IDC_COMBO_PERF_OPTIMIZE, FALSE},
{UI_IDC_STATIC_OPTIMIZE_PERF, FALSE},
{IDC_CHECK_DESKTOP_BKND, FALSE},
{IDC_CHECK_SHOW_FWD, FALSE},
{IDC_CHECK_MENU_ANIMATIONS, FALSE},
{IDC_CHECK_THEMES, FALSE},
{IDC_CHECK_BITMAP_CACHING, FALSE},
{IDC_CHECK_ENABLE_ARC, FALSE}
};
const UINT numConnectingDisableCtlsPPerf =
sizeof(connectingDisableCtlsPPerf)/
sizeof(connectingDisableCtlsPPerf[0]);
//
// MAP from optimization level to disabled feature list
// Disabled features list
//
// Index is the optimization level, entry is the disabled feature list
//
DWORD g_dwMapOptLevelToDisabledList[NUM_PERF_OPTIMIZATIONS] =
{
// 28K
TS_PERF_DISABLE_WALLPAPER |
TS_PERF_DISABLE_FULLWINDOWDRAG |
TS_PERF_DISABLE_MENUANIMATIONS |
TS_PERF_DISABLE_THEMING,
// 56K
TS_PERF_DISABLE_WALLPAPER |
TS_PERF_DISABLE_FULLWINDOWDRAG |
TS_PERF_DISABLE_MENUANIMATIONS,
// Broadband
TS_PERF_DISABLE_WALLPAPER,
// LAN
TS_PERF_DISABLE_NOTHING,
//
// CUSTOM (defaults to same as 56K
// 56K
//
// NOTE: This value gets changed at runtime
// to reflect the current custom settings
//
TS_PERF_DISABLE_WALLPAPER |
TS_PERF_DISABLE_FULLWINDOWDRAG |
TS_PERF_DISABLE_MENUANIMATIONS
};
//
// Mask of flags that can be set by checkboxes
//
#define CHECK_BOX_PERF_MASK (TS_PERF_DISABLE_WALLPAPER | \
TS_PERF_DISABLE_FULLWINDOWDRAG | \
TS_PERF_DISABLE_MENUANIMATIONS | \
TS_PERF_DISABLE_THEMING | \
TS_PERF_DISABLE_BITMAPCACHING | \
TS_PERF_DISABLE_CURSORSETTINGS) \
CPropPerf::CPropPerf(HINSTANCE hInstance, CTscSettings* pTscSet, CSH* pSh)
{
DC_BEGIN_FN("CPropPerf");
_hInstance = hInstance;
CPropPerf::_pPropPerfInstance = this;
_pTscSet = pTscSet;
_hwndDlg = NULL;
_fSyncingCheckboxes = FALSE;
_pSh = pSh;
TRC_ASSERT(_pTscSet,(TB,_T("_pTscSet is null")));
TRC_ASSERT(_pSh,(TB,_T("_pSh is null")));
DC_END_FN();
}
CPropPerf::~CPropPerf()
{
CPropPerf::_pPropPerfInstance = NULL;
}
INT_PTR CALLBACK CPropPerf::StaticPropPgPerfDialogProc(HWND hwndDlg,
UINT uMsg,
WPARAM wParam,
LPARAM lParam)
{
//
// Delegate to appropriate instance (only works for single instance dialogs)
//
DC_BEGIN_FN("StaticDialogBoxProc");
DCINT retVal = 0;
TRC_ASSERT(_pPropPerfInstance, (TB,
_T("perf dialog has NULL static instance ptr\n")));
retVal = _pPropPerfInstance->PropPgPerfDialogProc( hwndDlg,
uMsg,
wParam,
lParam);
DC_END_FN();
return retVal;
}
INT_PTR CALLBACK CPropPerf::PropPgPerfDialogProc (HWND hwndDlg,
UINT uMsg,
WPARAM wParam,
LPARAM lParam)
{
DC_BEGIN_FN("PropPgPerfDialogProc");
switch(uMsg)
{
case WM_INITDIALOG:
{
#ifndef OS_WINCE
int i;
#endif
_hwndDlg = hwndDlg;
//
// Position the dialog within the tab
//
SetWindowPos( hwndDlg, HWND_TOP,
_rcTabDispayArea.left, _rcTabDispayArea.top,
_rcTabDispayArea.right - _rcTabDispayArea.left,
_rcTabDispayArea.bottom - _rcTabDispayArea.top,
0);
InitPerfCombo();
SyncCheckBoxesToPerfFlags(
_pTscSet->GetPerfFlags());
//
// AutoReconnection checkbox
//
CheckDlgButton(hwndDlg, IDC_CHECK_ENABLE_ARC,
_pTscSet->GetEnableArc() ?
BST_CHECKED : BST_UNCHECKED);
_pSh->SH_ThemeDialogWindow(hwndDlg, ETDT_ENABLETAB);
return TRUE;
}
break; //WM_INITDIALOG
case WM_TSC_ENABLECONTROLS:
{
//
// wParam is TRUE to enable controls,
// FALSE to disable them
//
CSH::EnableControls( hwndDlg,
connectingDisableCtlsPPerf,
numConnectingDisableCtlsPPerf,
wParam ? TRUE : FALSE);
}
break;
case WM_SAVEPROPSHEET: //Intentional fallthru
case WM_DESTROY:
{
BOOL fEnableArc;
//
// Save page settings
//
DWORD dwCheckBoxPerfFlags = GetPerfFlagsFromCheckboxes();
DWORD dwPerfFlags = MergePerfFlags( dwCheckBoxPerfFlags,
_pTscSet->GetPerfFlags(),
CHECK_BOX_PERF_MASK );
fEnableArc = IsDlgButtonChecked(hwndDlg, IDC_CHECK_ENABLE_ARC);
_pTscSet->SetEnableArc(fEnableArc);
_pTscSet->SetPerfFlags(dwPerfFlags);
}
break; //WM_DESTROY
case WM_COMMAND:
{
switch(DC_GET_WM_COMMAND_ID(wParam))
{
case IDC_COMBO_PERF_OPTIMIZE:
{
if(HIWORD(wParam) == CBN_SELCHANGE)
{
OnPerfComboSelChange();
}
}
break;
default:
{
if (HIWORD(wParam) == BN_CLICKED)
{
//
// One of the checkboxes has been checked
// (prevent recursive looping due to feedback)
//
if (!_fSyncingCheckboxes)
{
OnCheckBoxStateChange((int)LOWORD(wParam));
}
}
}
break;
}
}
break;
}
DC_END_FN();
return 0;
}
BOOL CPropPerf::InitPerfCombo()
{
INT ret = 1;
DC_BEGIN_FN("InitPerfCombo");
TRC_ASSERT(g_fPropPageStringMapInitialized,
(TB,_T("Perf strings not loaded")));
TRC_ASSERT(_hwndDlg,
(TB,_T("_hwndDlg not set")));
if (!g_fPropPageStringMapInitialized)
{
return FALSE;
}
#ifndef OS_WINCE
while (ret && ret != CB_ERR)
{
ret = SendDlgItemMessage(_hwndDlg,
IDC_COMBO_PERF_OPTIMIZE,
CBEM_DELETEITEM,
0,0);
}
#else
SendDlgItemMessage(_hwndDlg, IDC_COMBO_PERF_OPTIMIZE, CB_RESETCONTENT, 0, 0);
#endif
//
// Only set up to the last but one string in the table
// as the last string is only used in the perf page
//
for (int i=0; i<NUM_PERF_OPTIMIZATIONS+1; i++)
{
if (NUM_PERF_OPTIMIZATIONS-1 == i)
{
//
// Skip the last but one string it's the
// custom entry for the main dialog
//
continue;
}
SendDlgItemMessage(_hwndDlg,
IDC_COMBO_PERF_OPTIMIZE,
CB_ADDSTRING,
0,
(LPARAM)(PDCTCHAR)g_PerfOptimizeStringTable[i].szString);
}
//
// Set the optimization level according to the disabled feature list
//
DWORD dwPerfFlags = _pTscSet->GetPerfFlags();
int optLevel = MapPerfFlagsToOptLevel(dwPerfFlags);
TRC_ASSERT(optLevel >= 0 && optLevel < NUM_PERF_OPTIMIZATIONS,
(TB,_T("optlevel %d out of range"), optLevel));
SendDlgItemMessage(_hwndDlg, IDC_COMBO_PERF_OPTIMIZE,CB_SETCURSEL,
(WPARAM)optLevel,0);
DC_END_FN();
return TRUE;
}
//
// Notification that the perf combo's selection has changed
//
VOID CPropPerf::OnPerfComboSelChange()
{
int curSel = 0;
DWORD dwDisableFeatureList = 0;
DC_BEGIN_FN("OnPerfComboSelChange");
//
// Figure out what the new selected item is
//
curSel = SendDlgItemMessage(_hwndDlg,
IDC_COMBO_PERF_OPTIMIZE,
CB_GETCURSEL,
0,0);
if (curSel < 0)
{
curSel = 0;
}
TRC_ASSERT(curSel < NUM_PERF_OPTIMIZATIONS,
(TB,_T("curSel (%d) > NUM_PERF_OPTIMIZATIONS (%d)"),
curSel,NUM_PERF_OPTIMIZATIONS));
if (curSel >= NUM_PERF_OPTIMIZATIONS)
{
curSel = NUM_PERF_OPTIMIZATIONS - 1;
}
//
// Map that to a list of disabled features
//
dwDisableFeatureList = MapOptimizationLevelToPerfFlags(curSel);
//
// Check and uncheck the checkboxes
//
SyncCheckBoxesToPerfFlags(dwDisableFeatureList);
DC_END_FN();
}
//
// Static method. Maps an optimization to the disabled feature list
// (packed in a DWORD)
// Params:
// [in] optLevel - optimization level from 0 to NUM_PERF_OPTIMIZATIONS-1
// [return] DWORD feature list
//
DWORD CPropPerf::MapOptimizationLevelToPerfFlags(int optLevel)
{
DWORD dwPerfFlags = 0;
DC_BEGIN_FN("MapOptimizationLevelToPerfFlags");
if (optLevel < 0)
{
TRC_ERR((TB,_T("Opt level out of range %d"),optLevel));
optLevel = 0;
}
if (optLevel >= NUM_PERF_OPTIMIZATIONS)
{
TRC_ERR((TB,_T("Opt level out of range %d"),optLevel));
optLevel = NUM_PERF_OPTIMIZATIONS - 1;
}
dwPerfFlags = g_dwMapOptLevelToDisabledList[optLevel];
TRC_NRM((TB,_T("Return disable list 0x%x"),dwPerfFlags));
DC_END_FN();
return dwPerfFlags;
}
//
// Toggles checkboxes to match the disabled feature list
// NOTE: the checkboxes represent 'enabled' features i.e the negation
// of the list
//
VOID CPropPerf::SyncCheckBoxesToPerfFlags(DWORD dwPerfFlagss)
{
DC_BEGIN_FN("SyncCheckBoxesToPerfFlags");
//
// Prevent recursive sets based on change notifications
// for the checkboxes (As they could change the combo leading
// to a subsequent change in the checkboxes, etc...)
//
_fSyncingCheckboxes = TRUE;
//
// Wallpaper (Desktop background)
//
CheckDlgButton(_hwndDlg, IDC_CHECK_DESKTOP_BKND,
(dwPerfFlagss & TS_PERF_DISABLE_WALLPAPER ?
BST_UNCHECKED : BST_CHECKED));
//
// Fullwindow drag
//
CheckDlgButton(_hwndDlg, IDC_CHECK_SHOW_FWD,
(dwPerfFlagss & TS_PERF_DISABLE_FULLWINDOWDRAG ?
BST_UNCHECKED : BST_CHECKED));
//
// Menu animations
//
CheckDlgButton(_hwndDlg, IDC_CHECK_MENU_ANIMATIONS,
(dwPerfFlagss & TS_PERF_DISABLE_MENUANIMATIONS ?
BST_UNCHECKED : BST_CHECKED));
//
// Theming
//
CheckDlgButton(_hwndDlg, IDC_CHECK_THEMES,
(dwPerfFlagss & TS_PERF_DISABLE_THEMING ?
BST_UNCHECKED : BST_CHECKED));
//
// Bitmap caching
//
CheckDlgButton(_hwndDlg, IDC_CHECK_BITMAP_CACHING,
(dwPerfFlagss & TS_PERF_DISABLE_BITMAPCACHING ?
BST_UNCHECKED : BST_CHECKED));
_fSyncingCheckboxes = FALSE;
DC_END_FN();
}
//
// Maps the disabled feature list to the appropriate optimization level
//
INT CPropPerf::MapPerfFlagsToOptLevel(DWORD dwPerfFlags)
{
DC_BEGIN_FN("MapPerfFlagsToOptLevel");
for (int i=0;i<NUM_PERF_OPTIMIZATIONS;i++)
{
if (g_dwMapOptLevelToDisabledList[i] == dwPerfFlags)
{
return i;
}
}
DC_END_FN();
//
// Didn't find an entry so return the last optimization level (custom)
//
return (NUM_PERF_OPTIMIZATIONS-1);
}
//
// Called whenever a checkbox's state changes (Checked or unchecked)
//
//
VOID CPropPerf::OnCheckBoxStateChange(int checkBoxID)
{
DWORD dwCheckBoxPerfFlags = 0;
DWORD dwPerfFlags = 0;
int optLevel = 0;
int curSel = 0;
DC_BEGIN_FN("OnCheckBoxStateChange");
//
// Pickup the current disabled feature list from the
// checkboxes
//
dwCheckBoxPerfFlags = GetPerfFlagsFromCheckboxes();
dwPerfFlags = MergePerfFlags( dwCheckBoxPerfFlags,
_pTscSet->GetPerfFlags(),
CHECK_BOX_PERF_MASK );
//
// Figure out the optimization level
//
optLevel = MapPerfFlagsToOptLevel(dwPerfFlags);
TRC_ASSERT(optLevel >= 0 && optLevel < NUM_PERF_OPTIMIZATIONS,
(TB,_T("optlevel %d out of range"), optLevel));
//
// If the combo is at a different opt level then switch it to
// the new level
//
curSel = SendDlgItemMessage(_hwndDlg,
IDC_COMBO_PERF_OPTIMIZE,
CB_GETCURSEL,
0,0);
//
// Update the custom disabled list based on the current
// settings
//
UpdateCustomDisabledList(dwPerfFlags);
if (curSel != optLevel)
{
SendDlgItemMessage(_hwndDlg, IDC_COMBO_PERF_OPTIMIZE,CB_SETCURSEL,
(WPARAM)optLevel,0);
}
DC_END_FN();
}
//
// Queries the checkboxes and returns the disabled feature list
// as a DWORD of flags
//
DWORD CPropPerf::GetPerfFlagsFromCheckboxes()
{
DWORD dwPerfFlags = 0;
DC_BEGIN_FN("GetPerfFlagsFromCheckboxes");
//
// Wallpaper (Desktop background)
//
if (!IsDlgButtonChecked(_hwndDlg,IDC_CHECK_DESKTOP_BKND))
{
dwPerfFlags |= TS_PERF_DISABLE_WALLPAPER;
}
//
// Fullwindow drag
//
if (!IsDlgButtonChecked(_hwndDlg,IDC_CHECK_SHOW_FWD))
{
dwPerfFlags |= TS_PERF_DISABLE_FULLWINDOWDRAG;
}
//
// Menu animations
//
if (!IsDlgButtonChecked(_hwndDlg,IDC_CHECK_MENU_ANIMATIONS))
{
dwPerfFlags |= TS_PERF_DISABLE_MENUANIMATIONS;
}
//
// Themeing
//
if (!IsDlgButtonChecked(_hwndDlg,IDC_CHECK_THEMES))
{
dwPerfFlags |= TS_PERF_DISABLE_THEMING;
}
//
// Bitmap caching
//
if (!IsDlgButtonChecked(_hwndDlg,IDC_CHECK_BITMAP_CACHING))
{
dwPerfFlags |= TS_PERF_DISABLE_BITMAPCACHING;
}
TRC_NRM((TB,_T("Return disable list 0x%x"),dwPerfFlags));
DC_END_FN();
return dwPerfFlags;
}
//
// Called to initialize the 'custom' disabled property
// list (e.g called at initialization time or after loading
// new settings
//
VOID CPropPerf::UpdateCustomDisabledList(DWORD dwPerfFlags)
{
DC_BEGIN_FN("InitCustomDisabledList");
//
//
//
INT optLevel = MapPerfFlagsToOptLevel(dwPerfFlags);
if (CUSTOM_OPTIMIZATION_LEVEL == optLevel)
{
//
// Store this as the new set of custom settings
//
TRC_NRM((TB,_T("Recording new custom setting: 0x%x"),
dwPerfFlags));
g_dwMapOptLevelToDisabledList[CUSTOM_OPTIMIZATION_LEVEL] =
dwPerfFlags;
}
DC_END_FN();
}
BOOL CPropPerf::EnableCheckBoxes(BOOL fEnable)
{
DC_BEGIN_FN("EnableCheckBoxes");
//
// Wallpaper (Desktop background)
//
EnableWindow( GetDlgItem(_hwndDlg, IDC_CHECK_DESKTOP_BKND),
fEnable );
//
// Fullwindow drag
//
EnableWindow( GetDlgItem(_hwndDlg, IDC_CHECK_SHOW_FWD),
fEnable );
//
// Menu animations
//
EnableWindow( GetDlgItem(_hwndDlg, IDC_CHECK_MENU_ANIMATIONS),
fEnable );
//
// Theming
//
EnableWindow( GetDlgItem(_hwndDlg, IDC_CHECK_THEMES),
fEnable );
//
// Bitmap caching
//
EnableWindow( GetDlgItem(_hwndDlg, IDC_CHECK_BITMAP_CACHING),
fEnable );
//
// Title static control
//
EnableWindow( GetDlgItem(_hwndDlg, UI_IDC_STATIC_OPTIMIZE_PERF),
fEnable );
DC_END_FN();
return TRUE;
}
//
// Merge perf flags from two sources
// 1) dwCheckBoxFlags - flags that come from the checkboxes
// 2) dwOrig set of passed in flags
//
// Use dwMask to preserve original flags that should not be affected
// by the checkboxes
//
// return - merged flags
//
DWORD CPropPerf::MergePerfFlags(DWORD dwCheckBoxFlags,
DWORD dwOrig,
DWORD dwMask)
{
DWORD dwNewFlags;
DC_BEGIN_FN("MergePerfFlags");
dwNewFlags = (dwOrig & ~dwMask) | (dwCheckBoxFlags & dwMask);
DC_END_FN();
return dwNewFlags;
}
| 27.173591 | 82 | 0.546219 |
af6c3a5fa03dab6a87d9a3abe48f4804956e52cf | 1,287 | hpp | C++ | library/sha256/sha256.hpp | shuyangsun/ssy_blockchain | 846c3758ddeb6717b8e7425a9ad89eda5eceb7ab | [
"MIT"
] | null | null | null | library/sha256/sha256.hpp | shuyangsun/ssy_blockchain | 846c3758ddeb6717b8e7425a9ad89eda5eceb7ab | [
"MIT"
] | null | null | null | library/sha256/sha256.hpp | shuyangsun/ssy_blockchain | 846c3758ddeb6717b8e7425a9ad89eda5eceb7ab | [
"MIT"
] | null | null | null | /*********************************************************************
* Filename: sha256.h
* Author: Brad Conte (brad AT bradconte.com)
* Copyright:
* Disclaimer: This code is presented "as is" without any guarantees.
* Details: Defines the API for the corresponding SHA1 implementation.
*********************************************************************/
#ifndef SSYBC_LIBRARY_SHA256_SHA256_HPP_
#define SSYBC_LIBRARY_SHA256_SHA256_HPP_
/*************************** HEADER FILES ***************************/
#include <stddef.h>
/****************************** MACROS ******************************/
#define SHA256_BLOCK_SIZE 32 // SHA256 outputs a 32 byte digest
/**************************** DATA TYPES ****************************/
typedef unsigned char BYTE; // 8-bit byte
typedef unsigned int WORD; // 32-bit word, change to "long" for 16-bit machines
typedef struct {
BYTE data[64];
WORD datalen;
unsigned long long bitlen;
WORD state[8];
} SHA256_CTX;
/*********************** FUNCTION DECLARATIONS **********************/
void sha256_init(SHA256_CTX *ctx);
void sha256_update(SHA256_CTX *ctx, const BYTE data[], size_t len);
void sha256_final(SHA256_CTX *ctx, BYTE hash[]);
#endif // SSYBC_LIBRARY_SHA256_SHA256_HPP_
| 36.771429 | 92 | 0.523699 |
af6de3fd4345760aea98549bb776b82adb22984a | 603 | cpp | C++ | VehicleIR.cpp | tcklpl/remotevehicle-vehicle | 49c9a7fd455e9c9246077b20bf192f3805d6c873 | [
"MIT"
] | null | null | null | VehicleIR.cpp | tcklpl/remotevehicle-vehicle | 49c9a7fd455e9c9246077b20bf192f3805d6c873 | [
"MIT"
] | null | null | null | VehicleIR.cpp | tcklpl/remotevehicle-vehicle | 49c9a7fd455e9c9246077b20bf192f3805d6c873 | [
"MIT"
] | null | null | null | /*
RemoteVehicle - library for controlling a remote vehicle using a ESP32CAM board.
Created by Luan Negroni Sibinel, August 24, 2021.
Released under the MIT license.
*/
#include "VehicleIR.h"
VehicleIR::VehicleIR(int8_t panalog, int8_t pdigital) {
_panalog = panalog;
_pdigital = pdigital;
if (_pdigital != -1)
pinMode(_pdigital, INPUT);
if (_panalog != -1)
pinMode(_panalog, INPUT);
}
int VehicleIR::digital() {
return _pdigital == -1 ? -1 : digitalRead(_pdigital);
}
int VehicleIR::analog() {
return _panalog == -1 ? -1 : analogRead(_panalog);
}
| 25.125 | 84 | 0.660033 |
af6e73cb9cc01c2facf801835c69d271e7115792 | 7,182 | cpp | C++ | src/wmecore/UiObjectOld.cpp | retrowork/wme | 54cf8905091736aef0a35fe6d3e05b818441f3c8 | [
"MIT"
] | null | null | null | src/wmecore/UiObjectOld.cpp | retrowork/wme | 54cf8905091736aef0a35fe6d3e05b818441f3c8 | [
"MIT"
] | null | null | null | src/wmecore/UiObjectOld.cpp | retrowork/wme | 54cf8905091736aef0a35fe6d3e05b818441f3c8 | [
"MIT"
] | null | null | null | // This file is part of Wintermute Engine
// For conditions of distribution and use, see copyright notice in license.txt
#include "Wme.h"
#include "UiObjectOld.h"
#include "UiObjectFactory.h"
#include "ContentManager.h"
#include "ElementCollection.h"
#include "Sprite.h"
#include "XmlUtil.h"
namespace Wme
{
//////////////////////////////////////////////////////////////////////////
UiObjectOld::UiObjectOld(GuiStage* parentStage)
{
m_ParentStage = parentStage;
m_Parent = NULL;
m_ZOrder = 0;
m_PixelPerfect = false;
m_Disabled = false;
m_Visible = true;
m_PosX = m_PosY = 0;
m_Width = m_Height = 0;
}
//////////////////////////////////////////////////////////////////////////
UiObjectOld::~UiObjectOld()
{
foreach (UiObjectOld* child, m_Children)
{
SAFE_DELETE(child);
}
m_Children.clear();
}
//////////////////////////////////////////////////////////////////////////
void UiObjectOld::Create()
{
}
//////////////////////////////////////////////////////////////////////////
void UiObjectOld::Display(ElementCollection* elementCol, const SpriteDrawingParams& params)
{
foreach (UiObjectOld* child, m_Children)
{
child->Display(elementCol, params);
}
}
//////////////////////////////////////////////////////////////////////////
void UiObjectOld::Update()
{
foreach (UiObjectOld* child, m_Children)
{
child->Update();
}
}
//////////////////////////////////////////////////////////////////////////
void UiObjectOld::AddChild(UiObjectOld* child)
{
UiObjectList::iterator it = std::find(m_Children.begin(), m_Children.end(), child);
if (it != m_Children.end()) return;
m_Children.push_back(child);
child->SetParent(this);
UpdateChildrenZOrder();
}
//////////////////////////////////////////////////////////////////////////
void UiObjectOld::RemoveChild(UiObjectOld* child)
{
UiObjectList::iterator it = std::find(m_Children.begin(), m_Children.end(), child);
if (it != m_Children.end())
{
(*it)->SetParent(NULL);
m_Children.erase(it);
}
UpdateChildrenZOrder();
}
//////////////////////////////////////////////////////////////////////////
void UiObjectOld::MoveChildAfter(UiObjectOld* child, UiObjectOld* pos)
{
UiObjectList::iterator it;
it = std::find(m_Children.begin(), m_Children.end(), child);
if (it != m_Children.end()) m_Children.erase(it);
it = std::find(m_Children.begin(), m_Children.end(), pos);
if (it != m_Children.end())
{
it++;
m_Children.insert(it, child);
}
else m_Children.push_back(child);
UpdateChildrenZOrder();
}
//////////////////////////////////////////////////////////////////////////
void UiObjectOld::MoveChildBefore(UiObjectOld* child, UiObjectOld* pos)
{
UiObjectList::iterator it;
it = std::find(m_Children.begin(), m_Children.end(), child);
if (it != m_Children.end()) m_Children.erase(it);
it = std::find(m_Children.begin(), m_Children.end(), pos);
if (it != m_Children.end()) m_Children.insert(it, child);
else m_Children.push_front(child);
UpdateChildrenZOrder();
}
//////////////////////////////////////////////////////////////////////////
UiObjectOld* UiObjectOld::GetChild(size_t index)
{
foreach (UiObjectOld* child, m_Children)
{
if (child->GetZOrder() == index) return child;
}
return NULL;
}
//////////////////////////////////////////////////////////////////////////
UiObjectOld* UiObjectOld::GetChild(const WideString& name)
{
foreach (UiObjectOld* child, m_Children)
{
if (child->GetName() == name) return child;
}
return NULL;
}
//////////////////////////////////////////////////////////////////////////
void UiObjectOld::UpdateChildrenZOrder()
{
size_t order = 0;
foreach (UiObjectOld* child, m_Children)
{
child->SetZOrder(order);
order++;
}
}
//////////////////////////////////////////////////////////////////////////
void UiObjectOld::GetOffset(int& offsetX, int& offsetY) const
{
if (m_Parent) m_Parent->GetOffset(offsetX, offsetY);
offsetX += m_PosX;
offsetY += m_PosY;
}
//////////////////////////////////////////////////////////////////////////
int UiObjectOld::GetAbsoluteX() const
{
int posX = 0;
int posY = 0;
GetOffset(posX, posY);
return posX;
}
//////////////////////////////////////////////////////////////////////////
int UiObjectOld::GetAbsoluteY() const
{
int posX = 0;
int posY = 0;
GetOffset(posX, posY);
return posY;
}
//////////////////////////////////////////////////////////////////////////
// DocumentAwareObject
//////////////////////////////////////////////////////////////////////////
bool UiObjectOld::LoadFromXml(TiXmlElement* rootNode)
{
ScriptableObject::LoadFromXml(rootNode);
for (TiXmlElement* elem = rootNode->FirstChildElement(); elem != NULL; elem = elem->NextSiblingElement())
{
if (elem->ValueStr() == "Position")
{
m_PosX = XmlUtil::AttrToInt(elem, "X", 0);
m_PosY = XmlUtil::AttrToInt(elem, "Y", 0);
}
else if (elem->ValueStr() == "Size")
{
m_Width = XmlUtil::AttrToInt(elem, "Width", 0);
m_Height = XmlUtil::AttrToInt(elem, "Height", 0);
}
else if (elem->ValueStr() == "PixelPerfect")
{
m_PixelPerfect = XmlUtil::TextToBool(elem, false);
}
else if (elem->ValueStr() == "Disabled")
{
m_Disabled = XmlUtil::TextToBool(elem, false);
}
else if (elem->ValueStr() == "Visible")
{
m_Visible = XmlUtil::TextToBool(elem, false);
}
else if (elem->ValueStr() == "Text")
{
m_Text = XmlUtil::TextToString(elem);
}
// load children
else if (elem->ValueStr() == "Children")
{
for (TiXmlElement* childNode = elem->FirstChildElement(); childNode != NULL; childNode = childNode->NextSiblingElement())
{
UiObjectOld* child = UiObjectFactory::GetInstance()->CreateInstance(m_ParentStage, childNode->ValueStr());
if (!child) continue;
child->Create();
child->LoadFromXml(childNode);
AddChild(child);
}
}
}
UpdateChildrenZOrder();
return true;
}
//////////////////////////////////////////////////////////////////////////
bool UiObjectOld::SaveToXml(TiXmlElement* rootNode)
{
ScriptableObject::SaveToXml(rootNode);
TiXmlElement* elem;
elem = XmlUtil::AddElem("Position", rootNode);
XmlUtil::SetAttr(elem, "X", m_PosX);
XmlUtil::SetAttr(elem, "Y", m_PosY);
elem = XmlUtil::AddElem("Size", rootNode);
XmlUtil::SetAttr(elem, "Width", m_Width);
XmlUtil::SetAttr(elem, "Height", m_Height);
elem = XmlUtil::AddElem("PixelPerfect", rootNode);
XmlUtil::SetText(elem, m_PixelPerfect);
elem = XmlUtil::AddElem("Disabled", rootNode);
XmlUtil::SetText(elem, m_Disabled);
elem = XmlUtil::AddElem("Visible", rootNode);
XmlUtil::SetText(elem, m_Visible);
elem = XmlUtil::AddElem("Text", rootNode);
XmlUtil::SetText(elem, m_Text, true);
// save children
elem = XmlUtil::AddElem("Children", rootNode);
foreach (UiObjectOld* child, m_Children)
{
TiXmlElement* childNode = XmlUtil::AddElem(child->GetDocRootName(), elem);
child->SaveToXml(childNode);
}
return true;
}
} // namespace Wme
| 25.468085 | 125 | 0.536062 |
af6e84b677151341d0b68349539afe102963feb1 | 413 | cpp | C++ | cpp/ql/src/jsf/4.17 Types/AV Rule 147.cpp | vadi2/codeql | a806a4f08696d241ab295a286999251b56a6860c | [
"MIT"
] | 4,036 | 2020-04-29T00:09:57.000Z | 2022-03-31T14:16:38.000Z | cpp/ql/src/jsf/4.17 Types/AV Rule 147.cpp | vadi2/codeql | a806a4f08696d241ab295a286999251b56a6860c | [
"MIT"
] | 2,970 | 2020-04-28T17:24:18.000Z | 2022-03-31T22:40:46.000Z | cpp/ql/src/jsf/4.17 Types/AV Rule 147.cpp | ScriptBox99/github-codeql | 2ecf0d3264db8fb4904b2056964da469372a235c | [
"MIT"
] | 794 | 2020-04-29T00:28:25.000Z | 2022-03-30T08:21:46.000Z | // Wrong: floating point bit implementation exposed by union with bit field.
// Endianness and different floating-point implementations across architectures
// as well as different packing methods across compilers could make this behave
// incorrectly.
typedef union {
float float_num;
struct {
unsigned sign : 1;
unsigned exp : 8;
unsigned fraction : 23;
} bits;
} floatbits;
| 31.769231 | 79 | 0.711864 |
af73ccd755f8939eaefe068d90b89b9d27790bde | 5,783 | cpp | C++ | XFree86-3.3/xc/lib/pex5/PEX5-def.cpp | tharindusathis/sourcecodes-of-CodeReadingTheOpenSourcePerspective | 1b0172cdb78757fd17898503aaf6ce03d940ef28 | [
"Apache-1.1"
] | 46 | 2015-12-04T17:12:58.000Z | 2022-03-11T04:30:49.000Z | XFree86-3.3/xc/lib/pex5/PEX5-def.cpp | tharindusathis/sourcecodes-of-CodeReadingTheOpenSourcePerspective | 1b0172cdb78757fd17898503aaf6ce03d940ef28 | [
"Apache-1.1"
] | null | null | null | XFree86-3.3/xc/lib/pex5/PEX5-def.cpp | tharindusathis/sourcecodes-of-CodeReadingTheOpenSourcePerspective | 1b0172cdb78757fd17898503aaf6ce03d940ef28 | [
"Apache-1.1"
] | 23 | 2016-10-24T09:18:14.000Z | 2022-02-25T02:11:35.000Z | LIBRARY PEX5
VERSION LIBRARY_VERSION
EXPORTS
PEXAccumulateState
PEXAddToNameSet
PEXAnnotationText
PEXAnnotationText2D
PEXApplicationData
PEXBeginPickAll
PEXBeginPickOne
PEXBeginRendering
PEXBeginStructure
PEXBuildTransform
PEXBuildTransform2D
PEXCellArray
PEXCellArray2D
PEXChangeNameSet
PEXChangePickDevice
PEXChangePipelineContext
PEXChangeRenderer
PEXChangeSearchContext
PEXChangeStructureRefs
PEXCopyBytesToOC
PEXCopyElements
PEXCopyLookupTable
PEXCopyNameSet
PEXCopyPipelineContext
PEXCopySearchContext
PEXCopyStructure
PEXCountOCs
PEXCreateLookupTable
PEXCreateNameSet
PEXCreatePickMeasure
PEXCreatePipelineContext
PEXCreateRenderer
PEXCreateSearchContext
PEXCreateStructure
PEXCreateWorkstation
PEXDecodeOCs
PEXDeleteBetweenLabels
PEXDeleteElements
PEXDeleteTableEntries
PEXDeleteToLabel
PEXDestroyStructures
PEXElementSearch
PEXEncodeOCs
PEXEncodedAnnoText
PEXEncodedAnnoText2D
PEXEncodedText
PEXEncodedText2D
PEXEndPickAll
PEXEndPickOne
PEXEndRendering
PEXEndStructure
PEXEscape
PEXEscapeWithReply
PEXExecuteDeferredActions
PEXExecuteStructure
PEXExtendedCellArray
PEXFetchElements
PEXFetchElementsAndSend
PEXFillArea
PEXFillArea2D
PEXFillAreaSet
PEXFillAreaSet2D
PEXFillAreaSetWithData
PEXFillAreaWithData
PEXFinishOCs
PEXFreeEnumInfo
PEXFreeFontInfo
PEXFreeFontNames
PEXFreeLookupTable
PEXFreeNameSet
PEXFreeOCData
PEXFreePCAttributes
PEXFreePDAttributes
PEXFreePMAttributes
PEXFreePickMeasure
PEXFreePickPaths
PEXFreePipelineContext
PEXFreeRenderer
PEXFreeRendererAttributes
PEXFreeSCAttributes
PEXFreeSearchContext
PEXFreeStructurePaths
PEXFreeTableEntries
PEXFreeWorkstation
PEXFreeWorkstationAttributes
PEXGDP
PEXGDP2D
PEXGSE
PEXGeoNormFillArea
PEXGeoNormFillAreaSet
PEXGeoNormQuadrilateralMesh
PEXGeoNormSetOfFillAreaSets
PEXGeoNormTriangleStrip
PEXGetAncestors
PEXGetDefinedIndices
PEXGetDescendants
PEXGetElementInfo
PEXGetEnumTypeInfo
PEXGetExtensionInfo
PEXGetImpDepConstants
PEXGetNameSet
PEXGetOCAddr
PEXGetPickDevice
PEXGetPickMeasure
PEXGetPipelineContext
PEXGetPredefinedEntries
PEXGetProtocolFloatFormat
PEXGetRendererAttributes
PEXGetRendererDynamics
PEXGetSearchContext
PEXGetSizeOCs
PEXGetStructureInfo
PEXGetStructuresInNetwork
PEXGetTableEntries
PEXGetTableEntry
PEXGetTableInfo
PEXGetWorkstationAttributes
PEXGetWorkstationDynamics
PEXGetWorkstationPostings
PEXGetWorkstationViewRep
PEXIdentityMatrix
PEXIdentityMatrix2D
PEXInitialize
PEXInvertMatrix
PEXInvertMatrix2D
PEXLabel
PEXListFonts
PEXListFontsWithInfo
PEXLoadFont
PEXLookAtViewMatrix
PEXMapDCToWC
PEXMapWCToDC
PEXMapXCToNPC
PEXMapXCToNPC2D
PEXMarkers
PEXMarkers2D
PEXMatchRenderingTargets
PEXMatrixMult
PEXMatrixMult2D
PEXNPCToXCTransform
PEXNPCToXCTransform2D
PEXNURBCurve
PEXNURBSurface
PEXNoop
PEXNormalizeVectors
PEXNormalizeVectors2D
PEXOrthoProjMatrix
PEXPerspProjMatrix
PEXPickAll
PEXPickOne
PEXPolarViewMatrix
PEXPolyline
PEXPolyline2D
PEXPolylineSetWithData
PEXPostStructure
PEXQuadrilateralMesh
PEXQueryEncodedTextExtents
PEXQueryFont
PEXQueryTextExtents
PEXRedrawAllStructures
PEXRedrawClipRegion
PEXRemoveFromNameSet
PEXRenderElements
PEXRenderNetwork
PEXRestoreModelClipVolume
PEXRotate
PEXRotate2D
PEXRotateGeneral
PEXScale
PEXScale2D
PEXSearchNetwork
PEXSendOCs
PEXSetATextAlignment
PEXSetATextHeight
PEXSetATextPath
PEXSetATextStyle
PEXSetATextUpVector
PEXSetBFInteriorStyle
PEXSetBFInteriorStyleIndex
PEXSetBFReflectionAttributes
PEXSetBFReflectionModel
PEXSetBFSurfaceColor
PEXSetBFSurfaceColorIndex
PEXSetBFSurfaceInterpMethod
PEXSetCharExpansion
PEXSetCharHeight
PEXSetCharSpacing
PEXSetCharUpVector
PEXSetColorApproxIndex
PEXSetCurveApprox
PEXSetDepthCueIndex
PEXSetEchoColor
PEXSetEdgeBundleIndex
PEXSetEditingMode
PEXSetElementPtr
PEXSetElementPtrAtLabel
PEXSetFacetCullingMode
PEXSetFacetDistinguishFlag
PEXSetGlobalTransform
PEXSetGlobalTransform2D
PEXSetHLHSRID
PEXSetIndividualASF
PEXSetInteriorBundleIndex
PEXSetInteriorStyle
PEXSetInteriorStyleIndex
PEXSetLightSourceState
PEXSetLineBundleIndex
PEXSetLineColor
PEXSetLineColorIndex
PEXSetLineType
PEXSetLineWidth
PEXSetLocalTransform
PEXSetLocalTransform2D
PEXSetMarkerBundleIndex
PEXSetMarkerColor
PEXSetMarkerColorIndex
PEXSetMarkerScale
PEXSetMarkerType
PEXSetModelClipFlag
PEXSetModelClipVolume
PEXSetModelClipVolume2D
PEXSetOfFillAreaSets
PEXSetParaSurfCharacteristics
PEXSetPatternAttributes
PEXSetPatternAttributes2D
PEXSetPatternSize
PEXSetPickID
PEXSetPolylineInterpMethod
PEXSetReflectionAttributes
PEXSetReflectionModel
PEXSetRenderingColorModel
PEXSetSurfaceApprox
PEXSetSurfaceColor
PEXSetSurfaceColorIndex
PEXSetSurfaceEdgeColor
PEXSetSurfaceEdgeColorIndex
PEXSetSurfaceEdgeFlag
PEXSetSurfaceEdgeType
PEXSetSurfaceEdgeWidth
PEXSetSurfaceInterpMethod
PEXSetTableEntries
PEXSetTextAlignment
PEXSetTextBundleIndex
PEXSetTextColor
PEXSetTextColorIndex
PEXSetTextFontIndex
PEXSetTextPath
PEXSetTextPrecision
PEXSetViewIndex
PEXSetWorkstationBufferMode
PEXSetWorkstationDisplayUpdateMode
PEXSetWorkstationHLHSRMode
PEXSetWorkstationViewPriority
PEXSetWorkstationViewRep
PEXSetWorkstationViewport
PEXSetWorkstationWindow
PEXStartOCs
PEXText
PEXText2D
PEXTransformPoints
PEXTransformPoints2D
PEXTransformPoints2DH
PEXTransformPoints4D
PEXTransformVectors
PEXTransformVectors2D
PEXTranslate
PEXTranslate2D
PEXTriangleStrip
PEXUnloadFont
PEXUnpostAllStructures
PEXUnpostStructure
PEXUpdatePickMeasure
PEXUpdateWorkstation
PEXViewMappingMatrix
PEXViewMappingMatrix2D
PEXViewOrientationMatrix
PEXViewOrientationMatrix2D
PEXXCToNPCTransform
PEXXCToNPCTransform2D
/* $XConsortium: PEX5-def.cpp /main/2 1996/05/07 13:15:18 kaleb $ */
| 20.362676 | 68 | 0.898496 |
af774e896c3c26f1dd8eac933d891f0007b6d59f | 3,048 | cpp | C++ | source/buffer.cpp | gnader/glutils | d80ec61eecfc1ea2555efd5f52317a54a86289cd | [
"MIT"
] | null | null | null | source/buffer.cpp | gnader/glutils | d80ec61eecfc1ea2555efd5f52317a54a86289cd | [
"MIT"
] | null | null | null | source/buffer.cpp | gnader/glutils | d80ec61eecfc1ea2555efd5f52317a54a86289cd | [
"MIT"
] | null | null | null | /**
* This file is part of gltoolbox
*
* MIT License
*
* Copyright (c) 2021 Georges Nader
*
* 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 <gltoolbox/buffer.h>
using namespace gltoolbox;
Buffer::Buffer(GLenum target, GLsizei elementsize, GLenum usage)
: mId(0), mOwned(false), mUsage(usage), mTarget(target), mElementSize(elementsize)
{
create();
}
Buffer::Buffer(Buffer &&temp)
{
//delete whatever was there
destroy();
//move buffer ownership
mId = temp.mId;
mOwned = temp.mOwned;
mUsage = temp.mUsage;
mTarget = temp.mTarget;
mElementSize = temp.mElementSize;
temp.mId = 0;
temp.mOwned = false;
}
Buffer::~Buffer()
{
destroy();
}
Buffer &Buffer::operator=(Buffer &other)
{
//delete whatever was there
destroy();
//move buffer ownership
mId = other.mId;
mOwned = other.mOwned;
mUsage = other.mUsage;
mTarget = other.mTarget;
mElementSize = other.mElementSize;
other.mId = 0;
other.mOwned = false;
return *this;
}
void Buffer::upload(void *ptr, GLsizei count) const
{
bind();
glBufferData(target(), count * element_size(), ptr, usage());
}
void Buffer::upload(void *ptr, GLsizei offset, GLsizei count) const
{
bind();
glBufferSubData(target(), offset * element_size(), count * element_size(), ptr);
}
void Buffer::download(void *ptr, GLsizei size) const
{
bind();
glGetBufferSubData(target(), 0, size, ptr);
}
void Buffer::download(void *ptr, GLsizei offset, GLsizei size) const
{
bind();
glGetBufferSubData(target(), offset, size, ptr);
}
void Buffer::create()
{
if (!mOwned || !is_valid())
{
glCreateBuffers(1, &mId);
bind(); // this will actually trigger the buffer creation
mOwned = true;
}
}
void Buffer::destroy()
{
if (mOwned && is_valid())
{
glDeleteBuffers(1, &mId);
mId = 0;
mOwned = false;
}
}
GLint Buffer::get_parameter(const GLenum param) const
{
GLint result;
bind();
glGetBufferParameteriv(target(), param, &result);
return result;
} | 23.8125 | 86 | 0.69521 |
af7b6ea6d128439d18c9fff9b840644ddb98f9d1 | 2,779 | cpp | C++ | 10.1.1.cpp | luckylove/extra | 8d27ec0e62bdc2ab6a261d197b455fea07120a55 | [
"CC-BY-4.0",
"MIT"
] | null | null | null | 10.1.1.cpp | luckylove/extra | 8d27ec0e62bdc2ab6a261d197b455fea07120a55 | [
"CC-BY-4.0",
"MIT"
] | null | null | null | 10.1.1.cpp | luckylove/extra | 8d27ec0e62bdc2ab6a261d197b455fea07120a55 | [
"CC-BY-4.0",
"MIT"
] | null | null | null | // program to quick short the linked list
// first of all create the linked list
#include<stdio.h>
#include<stdlib.h>
struct node
{
int data;
struct node* next;
};
void push(struct node **head,int data1)
{
struct node* newnode=NULL;
newnode=(struct node*)malloc(sizeof(struct node));
newnode->data=data1;
newnode->next=*head;
*head=newnode;
}
void printlinkedlist(struct node* head)
{
while(head!=NULL)
{
printf("%d",head->data);
head=head->next;
}
}
struct node* gettail(struct node* head)
{
struct node* current =head;
while(current!=NULL&¤t->next!=NULL)
{
current=current->next;
}
return current;
}
struct node* partitionof(struct node*head1,struct node*end1,struct node**newhead,struct node**newend)
{
struct node*previous=NULL;
struct node*pivot=end1;
struct node*current = head1;
struct node*tail=pivot;
while(current!=pivot)
{
printf("ss");
if(current->data < pivot->data)
{
if((*newhead)==NULL)
{
(*newhead)=current;
}
previous=current;
current=current->next;
}
else
{
if(previous!=NULL)
{
previous->next=current->next;
}
struct node* temp=current->next;
current->next=NULL;
tail->next=current;
// tail=tail->next;
tail=current;
current=temp;
}
if((*newhead)==NULL)
{
(*newhead)=pivot;
}
(*newend)=tail;
printlinkedlist(pivot);
printf("\n");
return pivot;
}
}
struct node*quicksortrecursive(struct node*head,struct node*end1)
{
if(head==NULL||head==end1)
{
return head;
}
struct node*newend=NULL;
struct node*newhead=NULL;
struct node*pivot=partitionof(head,end1,&newhead,&newend);
if(newhead!=pivot)
{
struct node*temp=newhead;
while(temp->next!=pivot)
{
temp=temp->next;
}
temp->next=NULL;
newhead=quicksortrecursive(newhead,temp);
temp=gettail(newhead);
temp->next=pivot;
}
pivot->next=quicksortrecursive(pivot->next,newend);
return newhead;
}
void quicksort(struct node**head)
{
(*head)=quicksortrecursive((*head),gettail(*head));
return;
}
int main()
{
struct node*head=NULL;
push(&head,1);
push(&head,2);
push(&head,3);
push(&head,4);
printlinkedlist(head);
printf("\n");
// struct node* nodee=head->next->next->next;
// struct node* one=NULL;
// struct node* two=NULL;
quicksort(&head);
// printf("SS");
printlinkedlist(head);
printf("\n");
}
| 21.21374 | 101 | 0.558834 |
af7d7ff58aa66834699fd90068f50fdaa921635a | 4,318 | cpp | C++ | Engine/Source/Runtime/Engine/Private/SpotLight.cpp | windystrife/UnrealEngine_NVIDIAGameWork | b50e6338a7c5b26374d66306ebc7807541ff815e | [
"MIT"
] | 1 | 2022-01-29T18:36:12.000Z | 2022-01-29T18:36:12.000Z | Engine/Source/Runtime/Engine/Private/SpotLight.cpp | windystrife/UnrealEngine_NVIDIAGameWork | b50e6338a7c5b26374d66306ebc7807541ff815e | [
"MIT"
] | null | null | null | Engine/Source/Runtime/Engine/Private/SpotLight.cpp | windystrife/UnrealEngine_NVIDIAGameWork | b50e6338a7c5b26374d66306ebc7807541ff815e | [
"MIT"
] | null | null | null | // Copyright 1998-2017 Epic Games, Inc. All Rights Reserved.
#include "Engine/SpotLight.h"
#include "Components/ArrowComponent.h"
#include "Components/SpotLightComponent.h"
ASpotLight::ASpotLight(const FObjectInitializer& ObjectInitializer)
: Super(ObjectInitializer.SetDefaultSubobjectClass<USpotLightComponent>(TEXT("LightComponent0")))
{
// Structure to hold one-time initialization
struct FConstructorStatics
{
FName ID_Lighting;
FText NAME_Lighting;
FConstructorStatics()
: ID_Lighting(TEXT("Lighting"))
, NAME_Lighting(NSLOCTEXT( "SpriteCategory", "Lighting", "Lighting" ))
{
}
};
static FConstructorStatics ConstructorStatics;
SpotLightComponent = CastChecked<USpotLightComponent>(GetLightComponent());
SpotLightComponent->Mobility = EComponentMobility::Stationary;
SpotLightComponent->RelativeRotation = FRotator(-90, 0, 0);
RootComponent = SpotLightComponent;
#if WITH_EDITORONLY_DATA
ArrowComponent = CreateEditorOnlyDefaultSubobject<UArrowComponent>(TEXT("ArrowComponent0"));
if (ArrowComponent)
{
ArrowComponent->ArrowColor = GetLightColor().ToFColor(true);
ArrowComponent->bTreatAsASprite = true;
ArrowComponent->SpriteInfo.Category = ConstructorStatics.ID_Lighting;
ArrowComponent->SpriteInfo.DisplayName = ConstructorStatics.NAME_Lighting;
ArrowComponent->SetupAttachment(SpotLightComponent);
ArrowComponent->bLightAttachment = true;
ArrowComponent->bIsScreenSizeScaled = true;
}
#endif // WITH_EDITORONLY_DATA
}
void ASpotLight::PostLoad()
{
Super::PostLoad();
if (GetLightComponent()->Mobility == EComponentMobility::Static)
{
GetLightComponent()->LightFunctionMaterial = NULL;
}
#if WITH_EDITORONLY_DATA
if(ArrowComponent)
{
ArrowComponent->ArrowColor = GetLightColor().ToFColor(true);
}
#endif
}
#if WITH_EDITOR
void ASpotLight::LoadedFromAnotherClass(const FName& OldClassName)
{
Super::LoadedFromAnotherClass(OldClassName);
if(GetLinkerUE4Version() < VER_UE4_REMOVE_LIGHT_MOBILITY_CLASSES)
{
static FName SpotLightStatic_NAME(TEXT("SpotLightStatic"));
static FName SpotLightMovable_NAME(TEXT("SpotLightMovable"));
static FName SpotLightStationary_NAME(TEXT("SpotLightStationary"));
check(GetLightComponent() != NULL);
if(OldClassName == SpotLightStatic_NAME)
{
GetLightComponent()->Mobility = EComponentMobility::Static;
}
else if(OldClassName == SpotLightMovable_NAME)
{
GetLightComponent()->Mobility = EComponentMobility::Movable;
}
else if(OldClassName == SpotLightStationary_NAME)
{
GetLightComponent()->Mobility = EComponentMobility::Stationary;
}
}
}
#endif // WITH_EDITOR
void ASpotLight::SetInnerConeAngle(float NewInnerConeAngle)
{
SpotLightComponent->SetInnerConeAngle(NewInnerConeAngle);
}
void ASpotLight::SetOuterConeAngle(float NewOuterConeAngle)
{
SpotLightComponent->SetOuterConeAngle(NewOuterConeAngle);
}
// Disable for now
//void ASpotLight::SetLightShaftConeAngle(float NewLightShaftConeAngle)
//{
// SpotLightComponent->SetLightShaftConeAngle(NewLightShaftConeAngle);
//}
#if WITH_EDITOR
void ASpotLight::EditorApplyScale(const FVector& DeltaScale, const FVector* PivotLocation, bool bAltDown, bool bShiftDown, bool bCtrlDown)
{
const FVector ModifiedScale = DeltaScale * ( AActor::bUsePercentageBasedScaling ? 10000.0f : 100.0f );
if ( bCtrlDown )
{
FMath::ApplyScaleToFloat( SpotLightComponent->OuterConeAngle, ModifiedScale, 0.01f );
SpotLightComponent->OuterConeAngle = FMath::Min( 89.0f, SpotLightComponent->OuterConeAngle );
SpotLightComponent->InnerConeAngle = FMath::Min( SpotLightComponent->OuterConeAngle, SpotLightComponent->InnerConeAngle );
}
else if ( bAltDown )
{
FMath::ApplyScaleToFloat( SpotLightComponent->InnerConeAngle, ModifiedScale, 0.01f );
SpotLightComponent->InnerConeAngle = FMath::Min( 89.0f, SpotLightComponent->InnerConeAngle );
SpotLightComponent->OuterConeAngle = FMath::Max( SpotLightComponent->OuterConeAngle, SpotLightComponent->InnerConeAngle );
}
else
{
FMath::ApplyScaleToFloat( SpotLightComponent->AttenuationRadius, ModifiedScale );
}
PostEditChange();
}
void ASpotLight::PostEditChangeProperty(FPropertyChangedEvent& PropertyChangedEvent)
{
Super::PostEditChangeProperty(PropertyChangedEvent);
if(ArrowComponent)
{
ArrowComponent->ArrowColor = GetLightColor().ToFColor(true);
}
}
#endif
| 30.408451 | 138 | 0.787633 |
502d2f4ef3dfaf8e96f415818e968aa727d067f8 | 26,232 | cpp | C++ | vuecepc/client/VueceNativeClientImplWin.cpp | vuece/vuece-hub-win | 9d09ca44ec44b48e4ef422872f27572d06a1b140 | [
"MIT"
] | null | null | null | vuecepc/client/VueceNativeClientImplWin.cpp | vuece/vuece-hub-win | 9d09ca44ec44b48e4ef422872f27572d06a1b140 | [
"MIT"
] | null | null | null | vuecepc/client/VueceNativeClientImplWin.cpp | vuece/vuece-hub-win | 9d09ca44ec44b48e4ef422872f27572d06a1b140 | [
"MIT"
] | null | null | null | #include "VueceNativeClientImplWin.h"
#include <cstdio>
#include <iostream>
#include <time.h>
#include <iomanip>
#include <cstdio>
#include <cstring>
#include <vector>
#include <stdio.h>
#include <stdlib.h>
#include "talk/xmpp/constants.h"
#include "talk/base/logging.h"
#include "talk/base/flags.h"
#include "talk/base/pathutils.h"
#include "talk/base/stream.h"
#include "talk/base/thread.h"
#include "talk/base/helpers.h"
#include "talk/base/base64.h"
#include "talk/base/stringdigest.h"
#include "talk/session/fileshare/VueceMediaStream.h"
#include "VueceCoreClient.h"
#include "VueceConstants.h"
#include "VueceGlobalSetting.h"
#include "VueceMediaDBManager.h"
#include "VueceMediaItem.h"
#include "VueceLogger.h"
#include "libjson.h"
#include "json/json.h"
#include "tinyxml2.h"
#include "DebugLog.h"
using namespace tinyxml2;
using namespace vuece;
static const int DEFAULT_PORT = 5222;
VueceNativeClientImplWin::VueceNativeClientImplWin(vuece::InitData* init_data) {
LOG(INFO) << "VueceNativeClientImplWin()";
client = NULL;
exitReason = VueceEvent_Client_SignedOut;
}
VueceNativeClientImplWin::~VueceNativeClientImplWin() {
LOG(INFO) << "VueceNativeClientImplWin - De-constructor called, exit reason: " << exitReason;
//NOTE: DONT TRY TO DELETE ANY THING HERE!!!!
}
RosterMap* VueceNativeClientImplWin::GetRosterMap() {
if (client == NULL) {
return NULL;
}
return client->GetRosterMap();
}
void VueceNativeClientImplWin::AddBuddy(const std::string& jid) {
if (client == NULL) {
return;
}
client->InviteFriend(jid);
}
int VueceNativeClientImplWin::InitiateMediaStream(
const std::string& share_id,
const std::string& jid,
const std::string& targetUri,
const std::string& width,
const std::string& height,
const std::string& preview_file_path,
const std::string& start_pos,
const std::string& need_preview,
VueceStreamType stream_type,
VueceMediaItem* mediaItem
)
{
int errCode = VueceStreamSessionInitErrType_None;
LOG(INFO) << "---------------------------------------------------------------------------------------------------------------";
LOG(INFO)
<< "VueceNativeClientImplWin::InitiateMediaStream: VueceShareId=" << share_id << ", Jid=" << jid << ", TargetUri=" << targetUri;
LOG(INFO) << "---------------------------------------------------------------------------------------------------------------";
//here we use ascii code FS to separate param1 and param2 and param3 in one string
switch(stream_type)
{
case VueceStreamType_File:
{
errCode = client->SendFile(share_id, jid, targetUri, width, height, preview_file_path, start_pos, need_preview);
break;
}
case VueceStreamType_Music:
{
errCode = client->InitiateMusicStreamDB(share_id, jid, targetUri, width, height, preview_file_path, start_pos, need_preview, mediaItem);
break;
}
default:
{
break;
}
}
return errCode;
}
void VueceNativeClientImplWin::CancelFileShare(const std::string& share_id){
LOG(INFO) << "VueceNativeClientImplWin::CancelFileShare: " << share_id;
SigVueuceCommandMessage(VUECE_CMD_CANCEL_FILE, share_id.c_str());
}
void VueceNativeClientImplWin::AcceptFileShare(const std::string& share_id,const std::string& target_folder, const std::string& target_file_name){
//dummy value for PC impl
std::string sample_rate("0");
LOG(INFO) << "VueceNativeClientImplWin::AcceptFileShare: " << share_id << "; sample rate: " << sample_rate;
int i;
char buf[128];
//here we use ascii code FS to separate param1 and param2 and param3 in one string
memset(buf, '\0', sizeof(buf));
strcpy(buf, share_id.c_str());
i = strlen(buf);
buf[i] = 0x1C;
strcat(buf, sample_rate.c_str());
i = strlen(buf);
buf[i] = 0x1C;
strcat(buf, target_folder.c_str());
i = strlen(buf);
buf[i] = 0x1C;
strcat(buf, target_file_name.c_str());
SigVueuceCommandMessage(VUECE_CMD_ACCEPT_FILE, buf);
}
void VueceNativeClientImplWin::DeclineFileShare(const std::string& share_id){
LOG(INFO) << "VueceNativeClientImplWin::DeclineFileShare: " << share_id;
SigVueuceCommandMessage(VUECE_CMD_DECLINE_FILE, share_id.c_str());
}
void VueceNativeClientImplWin::SendSubscriptionMessage(const std::string& jid, int type) {
if (client == NULL) {
return;
}
client->SendSubscriptionMessage(jid, type);
}
void VueceNativeClientImplWin::SendPresence(const std::string& status)
{
if (client == NULL) {
return;
}
client->SendPresence(status);
}
void VueceNativeClientImplWin::SendPresence(const std::string& status, const std::string& signature) {
if (client == NULL) {
return;
}
client->SendPresence(status, signature);
}
void VueceNativeClientImplWin::SendSignature(const std::string& sig) {
if (client == NULL) {
return;
}
client->SendSignature(sig);
}
vuece::ClientState VueceNativeClientImplWin::GetClientState(void)
{
return client->GetClientState();
}
int VueceNativeClientImplWin::Start(const char* name, const char* pwd, const int auth_type) {
bool debug = true;
bool bIsLoginFailed = false;
std::string protocol = "hybrid";
std::string secure = "disable";
LOG(INFO) << "VueceNativeClientImplWin::SignIn - Start";
if(client != NULL)
{
VueceLogger::Fatal("VueceNativeClientImplWin::Start - VueceCoreClient instance should be null, abort now!");
return RESULT_FUNC_NOT_ALLOWED;
}
client = new VueceCoreClient(this, name);
SigVueuceCommandMessage.connect(client, &VueceCoreClient::OnVueceCommandReceived);
client->SignalVueceEvent.connect(this, &VueceNativeClientImplWin::OnVueceEvent);
//a blocking call
client->Start(name, pwd, auth_type);
delete client;
client = NULL;
LOG(INFO) << "====================================================";
LOG(INFO) << "VueceNativeClientImplWin::Start:Call client finalized!!!!!";
LOG(INFO) << "====================================================";
if(bIsLoginFailed)
{
return RESULT_UNAUTHORIZED;
}
return RESULT_OK;
}
//Note - Make sure this method call is the ONLY entry point of logging out precedure.
int VueceNativeClientImplWin::LogOut()
{
LOG(INFO) << "VueceNativeClientImplWin::LogOut";
return client->LogOut();
}
void VueceNativeClientImplWin::OnClientStateChanged(vuece::ClientEvent event, vuece::ClientState state)
{
LOG(INFO) << "VueceNativeClientImplWin::OnClientStateChanged - event = " << event << ", state = " << state ;
VueceNativeInterface::LogClientEvent(event);
VueceNativeInterface::LogClientState(state);
switch(event)
{
case CLIENT_EVENT_LOGGING_IN:
{
LOG(INFO) << "VueceNativeClientImplWin::OnClientStateChanged - LOGGING_IN";
break;
}
case CLIENT_EVENT_LOGIN_OK:
{
LOG(INFO) << "VueceNativeClientImplWin::OnClientStateChanged - LOGGING_OK";
SigUserEvent(VueceEvent_Client_SignedIn);
break;
}
case CLIENT_EVENT_AUTH_ERR:
{
LOG(INFO) << "VueceNativeClientImplWin::OnClientStateChanged - AUTH_ERR";
exitReason = VueceEvent_Client_AuthFailed;
SigUserEvent(VueceEvent_Client_AuthFailed);
break;
}
case CLIENT_EVENT_NETWORK_ERR:
{
LOG(INFO) << "VueceNativeClientImplWin::OnClientStateChanged - NETWORK_ERR";
exitReason = VueceEvent_Connection_Failed;
//Note - This call will eventually make the UI layer trigger a call to LogOut on VueceCoreClient instance
SigUserEvent(VueceEvent_Connection_Failed);
break;
}
case CLIENT_EVENT_LOGGING_OUT:
{
LOG(INFO) << "VueceNativeClientImplWin::OnClientStateChanged - LOGGING_OUT";
break;
}
case CLIENT_EVENT_LOGOUT_OK:
{
LOG(INFO) << "VueceNativeClientImplWin::OnClientStateChanged - LOGGING_OK";
SigUserEvent(VueceEvent_Client_SignedOut);
break;
}
}
}
void VueceNativeClientImplWin::OnVueceEvent(int code, const char* jid, const char* other)
{
std::string jid_s (jid);
LOG(INFO) << "VueceNativeClientImplWin::OnVueceEvent, code = " << code << ", jid = " << jid << ", other value = " << other;
switch(code)
{
//TODO - Use a separate signal to handle this event, don't mix it with FSM
case VueceEvent_FileAccess_Denied:
{
std::ostringstream os;
os << "{'action':'play', 'reply':'error','category':'music','control':'start','reason':'Access denied.', 'uri':'";
os << other;
os << "'}";
LOG(INFO) << "VueceNativeClientImplWin::OnVueceEvent - VueceEvent_FileAccess_Denied";
client->SendVHubMessage(jid_s, "result", os.str());
break;
}
default:
{
VueceLogger::Fatal("VueceNativeClientImplWin::OnVueceEvent - Unexpected event notification, code: %d, abort now.", code);
break;
}
}
}
int VueceNativeClientImplWin::SendVHubMessage(const std::string& to, const std::string& type,const std::string& message)
{
return RESULT_GENERAL_ERR;
}
void VueceNativeClientImplWin::OnRosterStatusUpdate(const buzz::Status& status) {
// LOG(INFO) << "VueceNativeClientImplWin: OnRosterStatusUpdate";
// LOG(INFO) << "VueceNativeClientImplWin:OnRosterStatusUpdate:Jid:[" << status.jid().Str().c_str() << "]";
// LOG(INFO) << "VueceNativeClientImplWin:OnRosterStatusUpdate:Status:[" << status.status().c_str() << "]";
//
//#ifdef VCARD_ENABLED
// SendVCardRequest(status.jid().Str());
//#endif
}
#ifdef CHAT_ENABLED
void VueceNativeClientImplWin::SendChat(const std::string& to, const std::string& msg) {
if (client == NULL) {
return;
}
client->SendChat(to, msg);
}
void VueceNativeClientImplWin::OnChatMessageReceived(const buzz::Jid& from, const std::string& msg) {
LOG(LS_VERBOSE) << "OnChatMessageReceived:Received a msg from: " << from.node();
LOG(LS_VERBOSE) << "OnChatMessageReceived:Message content:\n-------------------\n" <<
msg << "\n-------------------\n";
}
#endif
#ifdef VCARD_ENABLED
void VueceNativeClientImplWin::OnRosterVCardReceived(const std::string& jid, const std::string& fn, const std::string& img_data)
{
LOG(LS_VERBOSE) << "OnRosterVCardReceived:Received a vcard query result for: " << jid;
LOG(LS_VERBOSE) << "OnRosterVCardReceived:Full name:" << fn;
SigRosterVCardReceived(jid, fn, img_data);
}
void VueceNativeClientImplWin::SendVCardRequest(const std::string& to) {
if (client == NULL) {
return;
}
client->SendVCardRequest(to);
}
#endif
void VueceNativeClientImplWin::ShareMusicDBFile(const buzz::Jid& jid)
{
std::string db_path = VueceMediaDBManager::GetFullDBFilePath();
LOG(LS_VERBOSE) << "VueceNativeClientImplWin:ShareMusicDBFile - Full db file path: " << db_path;
InitiateMediaStream(
talk_base::ToString(talk_base::CreateRandomId()), //session id
jid.Str(), //jid
db_path.c_str() , //file path
"0", //image width
"0", //image height
"", //preview image path
"0", //start position in seconds
"0",
VueceStreamType_File,
NULL
);
}
void VueceNativeClientImplWin::OnVHubGetMessageReceived(const buzz::Jid& jid, const std::string& message)
{
LOG(LS_INFO)
<< "VueceNativeClientImplWin::VHub Msg Received - jid: " << jid.Str().c_str() << ", message: " << message;
Json::Value root; // will contains the root value after parsing.
Json::Reader reader;
std::string msg(message);
std::replace( msg.begin(), msg.end(), '\'', '"');
bool parsingSuccessful = reader.parse( msg.c_str(), root );
VueceGlobalSetting* iVueceGlobalSetting = VueceGlobalContext::Instance();
const char* accountUserName = VueceGlobalContext::GetAccountUserName();
char remote_bare_jid[128+1];
bool access_allowed = false;
bool config_allowFriendsAccess = (bool)VueceGlobalContext::GetAllowFriendAccess();
memset(remote_bare_jid, 0, sizeof(remote_bare_jid));
strcpy(remote_bare_jid, jid.BareJid().Str().c_str());
if ( !parsingSuccessful )
{
// report to the user the failure and their locations in the document.
LOG(LS_ERROR) << "VueceNativeClientImplWin::VHub Msg Received - Failed to parse configuration\n"
<< reader.getFormattedErrorMessages();
return;
}
std::string action = root.get("action","").asString();
LOG(LS_VERBOSE) << "VueceNativeClientImplWin::VHub Msg Received - action: " << action << ", checking access now...";
LOG(LS_VERBOSE) << "VueceNativeClientImplWin::Performing access control - Owner's hub jid: " << accountUserName << ", bare_remote_jid: " << remote_bare_jid;
if(strcmp(accountUserName, remote_bare_jid) != 0)
{
LOG(LS_VERBOSE) << "VueceNativeClientImplWin::Remote client is not owner's device: " << remote_bare_jid;
if(!config_allowFriendsAccess)
{
LOG(LS_VERBOSE) << "VueceNativeClientImplWin::Remote client is not owner's device and access is NOT allowed";
access_allowed = false;
}
else
{
LOG(LS_VERBOSE) << "VueceNativeClientImplWin::Remote client is not owner's device but access is allowed";
access_allowed = true;
}
}
else
{
LOG(LS_VERBOSE) << "VueceNativeClientImplWin::Remote client is running on owner's device";
access_allowed = true;
}
if(access_allowed)
{
LOG(LS_VERBOSE) << "VueceNativeClientImplWin::Access is allowed";
}
else
{
char err_resp [128+1];
memset(err_resp, 0, sizeof(err_resp));
LOG(LS_VERBOSE) << "VueceNativeClientImplWin::Access is NOT allowed, sending error response";
sprintf(err_resp, "{'action':'%s', 'reply':'noaccess','reason':'You are not allowed to access this hub.'}", action.c_str());
client->SendVHubMessage(jid.Str().c_str(), "result", err_resp);
return;
}
if (action.compare("probe")==0)
{
//get all categories, etc. music, video, camera
std::string db_md5 = VueceMediaDBManager::RetrieveDBFileChecksum(false);
std::string message="{'action':'probe', 'reply':'ok','categories':['music'],'db-cache-chksum':'";
message.append(db_md5);
message.append("'}");
client->SendVHubMessage(jid.Str().c_str(), "result", message);
}
else if (action.compare("browse")==0)
{
// browse resources
std::string category = root.get("category","").asString();
std::string uri = root.get("uri","").asString();
LOG(LS_INFO) << "VueceNativeClientImplWin::VHub Msg Received - category: " << category;
if (category.compare("music")==0)
{
std::ostringstream resp;
LOG(INFO) << "VueceNativeClientImplWin::VHub Msg Received - Start browsing target uri: " << uri;
client->BrowseMediaItem(uri, resp);
LOG(INFO) << "VueceNativeClientImplWin::VHub Msg Received - Shared media info string len: " << resp.str().length();
LOG(INFO) << "VueceNativeClientImplWin::VHub Msg Received - Shared media info string: " << resp.str();
client->SendVHubMessage(jid.Str().c_str(), "result", resp.str());
}
}
else if (action.compare("play")==0)
{
// control
std::string category = root.get("category","").asString();
std::string control = root.get("control","").asString();
std::string uri = root.get("uri","").asString();
LOG(LS_INFO) << "VueceNativeClientImplWin::VHub Msg Received - category: " << category << ", control: " << control << ", uri: " << uri;
if (uri.compare("")==0)
{
std::string message="{'action':'play', 'reply':'error','category':'music','control':'"+control+"', 'reason':'URI cannot be empty'}";
client->SendVHubMessage(jid.Str().c_str(), "result", message);
}
else
{
if (category.compare("music")==0)
{
LOG(LS_INFO) << "VueceNativeClientImplWin::VHub Msg Received - This message belongs to MUSIC category.";
if (control.compare("start")==0)
{
//TODO - Implement error handling here
//If we are currently streaming file and meanwhile we receive another play request from remote client
//this is unexpected because remote client is supposed to send a STOP before sending a new START, but
//we don't trust remote client so we need to protect ourselves from crashing, so in this case, we abort
//current streaming and return an ACCESS DENIED response to remove client, the we go back to idle state
std::string previewImagePath("");
LOG(LS_INFO) << "VueceNativeClientImplWin::VHub Msg Received - Received a START request from remote client, preview image path is: " << previewImagePath ;
std::string start_position = root.get("start","0").asString();
std::string need_preview = root.get("need_preview","0").asString();
LOG(LS_INFO) << "VueceNativeClientImplWin::VHub Msg Received - start_position: " << start_position << ";need preview?" << need_preview;
LOG(LS_INFO) << "VueceNativeClientImplWin::VHub Msg Received - Enter media streaming mode.";
//query the actual file path according to the file URL
//if target item cannot be found, a vuece event VueceEvent_FileAccess_Denied
//will be fired and error response will be sent back
// std::string absFilePath = client->LocateMediaItemInDB(jid.Str().c_str(), uri);
VueceMediaItem* targetItem = client->LocateMediaItemInDB(jid.Str().c_str(), uri);
if(targetItem != NULL)
{
int errCode = VueceStreamSessionInitErrType_None;
if(targetItem->IsFolder())
{
LOG(LS_INFO) << "VueceNativeClientImplWin::VHub Msg Received - This is folder, cannot be played, return an error. ";
errCode = VueceStreamSessionInitErrType_NotAFile;
}
else
{
std::string absFilePath = talk_base::Base64::Decode(targetItem->Path(), talk_base::Base64::DO_STRICT);
errCode = InitiateMediaStream(
talk_base::ToString(talk_base::CreateRandomId()), //session id
jid.Str().c_str(), //jid
absFilePath,//uri, //target uri
"128", //image width
"128", //image height
previewImagePath.c_str(), //preview image path
start_position, //start position in seconds
need_preview, //need preview or not,
VueceStreamType_Music,
targetItem
);
LOG(LS_INFO) << "VueceNativeClientImplWin::VHub Msg Received - InitiateMediaStream() returned: " << errCode;
}
if(errCode != VueceStreamSessionInitErrType_OK)
{
LOG(LS_INFO) << "VueceNativeClientImplWin::VHub Msg Received - Target cannot be found or played, return an error msg now.";
std::string message = "";
if(errCode == VueceStreamSessionInitErrType_NodeBusy)
{
message="{'action':'play', 'reply':'error','category':'music','control':'"+control+"', 'reason':'" + VHUB_MSG_BUSY_NOW +"'}";
}
else
{
message="{'action':'play', 'reply':'error','category':'music','control':'"+control+"', 'reason':'" + VHUB_MSG_STREAMING_TARGET_INVALID +"'}";
}
client->SendVHubMessage(jid.Str().c_str(), "result", message);
}
}
}
}
else
{
std::string message="{'action':'play', 'reply':'error','category':'unknown','control':'"+control+"', 'reason':'Invalid request'}";
client->SendVHubMessage(jid.Str().c_str(), "result", message);
}
}
}
else if (action.compare("sync-cache")==0)
{
client->SendVHubMessage(jid.Str().c_str(), "result", "{'action':'sync-cache', 'reply':'ok'}");
ShareMusicDBFile(jid);
}
}
void VueceNativeClientImplWin::OnVHubResultMessageReceived(const buzz::Jid& jid, const std::string& message)
{
LOG(LS_INFO)
<< "VueceNativeClientImplWin::OnVHubResultMessageReceived:jid: " << jid.Str().c_str() << ", message: " << message << " - Empty impl";
}
void VueceNativeClientImplWin::OnRosterSubRespReceived(VueceRosterSubscriptionMsg* m) {
LOG(LS_VERBOSE) << "OnRosterSubRespReceived";
SigRosterSubscriptionMsgReceived(m);
}
void VueceNativeClientImplWin::OnRosterReceived(const buzz::XmlElement* stanza) {
LOG(INFO) << "OnRosterReceived - Do nothing";
}
void VueceNativeClientImplWin::OnFileSharePreviewReceived(const std::string& share_id, const std::string& path, int w, int h)
{
LOG(LS_VERBOSE)
<< "VueceNativeClientImplWin:OnFileSharePreviewReceived:share_id: " << share_id << ", path: " << path << ", w: " << w << ", h: " << h<< ", do nothing";
}
void VueceNativeClientImplWin::OnFileShareProgressUpdated(const std::string& share_id, int percent)
{
LOG(LS_VERBOSE)
<< "VueceNativeClientImplWin:OnFileShareProgressUpdated:share_id: " << share_id << ", progress: " << percent << ", do nothing";
}
void VueceNativeClientImplWin::OnFileShareStateChanged(const std::string& remote_jid, const std::string& sid, int state)
{
LOG(LS_VERBOSE) << "VueceNativeClientImplWin:OnFileShareStateChanged:state: " << state << ", remote_jid: " << remote_jid << ", session id: " << sid;
if(state == (int)cricket::FS_RESOURCE_RELEASED)
{
std::ostringstream os;
LOG(LS_VERBOSE) << "VueceNativeClientImplWin:OnFileShareStateChanged:state - FS_RESOURCE_RELEASED";
os << "{'action':'notification', 'category':'music', 'type':'streaming-resource-released', 'sid':'";
os << sid;
os << "'}";
client->RemoveStreamingNode(remote_jid);
client->SendVHubMessage(remote_jid, "get", os.str());
}
else
{
//do nothing for now if the notification state is not FS_RESOURCE_RELEASED
LOG(LS_VERBOSE) << "VueceNativeClientImplWin:OnFileShareStateChanged:state - do nothing for now because the notification state is not FS_RESOURCE_RELEASED";
}
}
void VueceNativeClientImplWin::OnFileShareRequestReceived(const std::string& share_id, const buzz::Jid& target, int type, const std::string& fileName, int size, bool needPreview)
{
LOG(LS_VERBOSE) << "VueceNativeClientImplWin:OnFileShareRequestReceived:fileName: " << fileName;
}
void VueceNativeClientImplWin::OnFileSystemChanged()
{
LOG(LS_VERBOSE) << "VueceNativeClientImplWin::OnFileSystemChanged";
}
void VueceNativeClientImplWin::OnRemoteDeviceActivity(VueceStreamingDevice* d)
{
LOG(LS_VERBOSE) << "VueceNativeClientImplWin::OnRemoteDeviceActivity - User id: " << d->user_id
<< ", Activity type: " << d->activity << ", File url: " << d->file_url;
SigRemoteDeviceActivity(d);
}
//music playing
void VueceNativeClientImplWin::OnStreamPlayerStateChanged(const std::string& share_id, int state)
{
LOG(LS_INFO) << "VueceNativeClientImplWin::OnStreamPlayerStateChanged:share_id: " << share_id << ", state: " << state<< ", do nothing";
}
void VueceNativeClientImplWin::StopStreamPlayer(const std::string& pos)
{
VueceLogger::Fatal("VueceNativeClientImplWin - StopStreamPlayer is not supported, abort!");
}
void VueceNativeClientImplWin::ResumeStreamPlayer(const std::string& pos)
{
VueceLogger::Fatal("VueceNativeClientImplWin - ResumeStreamPlayer is not supported, abort!");
}
vuece::NetworkPlayerState VueceNativeClientImplWin::GetNetworkPlayerState(void)
{
VueceLogger::Fatal("VueceNativeClientImplWin - GetNetworkPlayerState is not supported, abort!");
return vuece::NetworkPlayerState_Idle;
}
void VueceNativeClientImplWin::OnNetworkPlayerStateChanged(vuece::NetworkPlayerEvent e, vuece::NetworkPlayerState s)
{
VueceLogger::Fatal("VueceNativeClientImplWin - OnNetworkPlayerStateChanged is not supported, abort!");
}
bool VueceNativeClientImplWin::IsMusicStreaming(void)
{
VueceLogger::Fatal("VueceNativeClientImplWin - IsMusicStreaming is not supported, abort!");
return false;
}
int VueceNativeClientImplWin::GetCurrentPlayingProgress(void)
{
VueceLogger::Fatal("VueceNativeClientImplWin - GetCurrentPlayingProgress is not supported, abort!");
return -1;
}
int VueceNativeClientImplWin::Play(const std::string &jid, const std::string &song_uuid)
{
VueceLogger::Fatal("VueceNativeClientImplWin - Play is not supported, abort!");
return -1;
}
int VueceNativeClientImplWin::Pause()
{
VueceLogger::Fatal("VueceNativeClientImplWin - Pause is not supported, abort!");
return -1;
}
int VueceNativeClientImplWin::Resume()
{
VueceLogger::Fatal("VueceNativeClientImplWin - Resume is not supported, abort!");
return -1;
}
int VueceNativeClientImplWin::Seek(const int position)
{
VueceLogger::Fatal("VueceNativeClientImplWin - Seek is not supported, abort!");
return -1;
}
void VueceNativeClientImplWin::OnMusicStreamingProgressUpdated(const std::string& share_id, int progress)
{
VueceLogger::Fatal("VueceNativeClientImplWin - OnMusicStreamingProgressUpdated is not supported, abort!");
}
int VueceNativeClientImplWin::GetCurrentMusicStreamingProgress(const std::string& share_id)
{
VueceLogger::Fatal("VueceNativeClientImplWin - GetCurrentMusicStreamingProgress is not supported, abort!");
return -1;
}
cricket::CallOptions* VueceNativeClientImplWin::GetCurrentCallOption(void)
{
return NULL;
}
buzz::Jid VueceNativeClientImplWin::GetCurrentJidInCall(void)
{
buzz::Jid jid;
return jid;
}
//Test method
void VueceNativeClientImplWin::TestMusicStreaming()
{
//input not used for sender
int sample_rate = -1;
int bit_rate = -1;
int nchannels = -1;
int duration = -1;
bool fOpend = 0;
char readBuf[2048];
size_t read_len = 0;
int read_err;
talk_base::StreamResult sr =talk_base:: SR_ERROR;
LOG(LS_VERBOSE) << "VueceNativeClientImplWin:TestMusicStreaming - Start";
talk_base::VueceMediaStream* file = new talk_base::VueceMediaStream("", sample_rate, bit_rate, nchannels, duration);
fOpend = (file->Open("D:\\STREAM_SAMPLES\\SHORT.mp3", "rb", 0));
if ( !fOpend )
{
LOG(LS_ERROR) << "VueceNativeClientImplWin:OnHttpRequest:Meida hub - File cannot be opened";
return;
}
while(true)
{
sr = file->Read(readBuf, 2048, &read_len, &read_err);
if(sr == talk_base::SR_ERROR || sr == talk_base::SR_EOS)
{
break;
}
}
LOG(LS_VERBOSE) << "VueceNativeClientImplWin:TestMusicStreaming - Done";
}
int VueceNativeClientImplWin::SendVHubPlayRequest(const std::string& to, const std::string& type,const std::string& message, const std::string& uri)
{
return 0;
}
| 32.06846 | 179 | 0.679437 |
5038382f91b12e996e0a51390909ea21e6dce422 | 4,239 | cpp | C++ | source/primitive/Box.cpp | xzrunner/raytracing | c130691a92fab2cc9605f04534f42ca9b99e6fde | [
"MIT"
] | null | null | null | source/primitive/Box.cpp | xzrunner/raytracing | c130691a92fab2cc9605f04534f42ca9b99e6fde | [
"MIT"
] | null | null | null | source/primitive/Box.cpp | xzrunner/raytracing | c130691a92fab2cc9605f04534f42ca9b99e6fde | [
"MIT"
] | null | null | null | #include "raytracing/primitive/Box.h"
#include "raytracing/maths/Ray.h"
#include "raytracing/maths/Normal.h"
#include "raytracing/utilities/ShadeRec.h"
#include "raytracing/utilities/Constants.h"
namespace rt
{
Box::Box(const Point3D& min, const Point3D& max)
{
x0 = min.x;
y0 = min.y;
z0 = min.z;
x1 = max.x;
y1 = max.y;
z1 = max.z;
}
bool Box::Hit(const Ray& ray, double& tmin, ShadeRec& sr) const
{
double ox = ray.ori.x; double oy = ray.ori.y; double oz = ray.ori.z;
double dx = ray.dir.x; double dy = ray.dir.y; double dz = ray.dir.z;
double tx_min, ty_min, tz_min;
double tx_max, ty_max, tz_max;
double a = 1.0 / dx;
if (a >= 0) {
tx_min = (x0 - ox) * a;
tx_max = (x1 - ox) * a;
} else {
tx_min = (x1 - ox) * a;
tx_max = (x0 - ox) * a;
}
double b = 1.0 / dy;
if (b >= 0) {
ty_min = (y0 - oy) * b;
ty_max = (y1 - oy) * b;
} else {
ty_min = (y1 - oy) * b;
ty_max = (y0 - oy) * b;
}
double c = 1.0 / dz;
if (c >= 0) {
tz_min = (z0 - oz) * c;
tz_max = (z1 - oz) * c;
} else {
tz_min = (z1 - oz) * c;
tz_max = (z0 - oz) * c;
}
double t0, t1;
int face_in, face_out;
// find largest entering t value
if (tx_min > ty_min) {
t0 = tx_min;
face_in = (a >= 0.0) ? 0 : 3;
} else {
t0 = ty_min;
face_in = (b >= 0.0) ? 1 : 4;
}
if (tz_min > t0) {
t0 = tz_min;
face_in = (c >= 0.0) ? 2 : 5;
}
// find smallest exiting t value
if (tx_max < ty_max) {
t1 = tx_max;
face_out = (a >= 0.0) ? 3 : 0;
} else {
t1 = ty_max;
face_out = (b >= 0.0) ? 4 : 1;
}
if (tz_max < t1) {
t1 = tz_max;
face_out = (c >= 0.0) ? 5 : 2;
}
if (t0 < t1 && t1 > EPSILON) { // condition for a hit
if (t0 > EPSILON) {
tmin = t0; // ray hits outside surface
sr.normal = GetNormal(face_in);
}
else {
tmin = t1; // ray hits inside surface
sr.normal = GetNormal(face_out);
}
sr.local_hit_point = ray.ori + tmin * ray.dir;
return true;
} else {
return false;
}
}
bool Box::ShadowHit(const Ray& ray, float& tmin) const
{
if (!m_shadows) {
return false;
}
double ox = ray.ori.x; double oy = ray.ori.y; double oz = ray.ori.z;
double dx = ray.dir.x; double dy = ray.dir.y; double dz = ray.dir.z;
double tx_min, ty_min, tz_min;
double tx_max, ty_max, tz_max;
double a = 1.0 / dx;
if (a >= 0) {
tx_min = (x0 - ox) * a;
tx_max = (x1 - ox) * a;
} else {
tx_min = (x1 - ox) * a;
tx_max = (x0 - ox) * a;
}
double b = 1.0 / dy;
if (b >= 0) {
ty_min = (y0 - oy) * b;
ty_max = (y1 - oy) * b;
} else {
ty_min = (y1 - oy) * b;
ty_max = (y0 - oy) * b;
}
double c = 1.0 / dz;
if (c >= 0) {
tz_min = (z0 - oz) * c;
tz_max = (z1 - oz) * c;
} else {
tz_min = (z1 - oz) * c;
tz_max = (z0 - oz) * c;
}
double t0, t1;
int face_in, face_out;
// find largest entering t value
if (tx_min > ty_min) {
t0 = tx_min;
face_in = (a >= 0.0) ? 0 : 3;
} else {
t0 = ty_min;
face_in = (b >= 0.0) ? 1 : 4;
}
if (tz_min > t0) {
t0 = tz_min;
face_in = (c >= 0.0) ? 2 : 5;
}
// find smallest exiting t value
if (tx_max < ty_max) {
t1 = tx_max;
face_out = (a >= 0.0) ? 3 : 0;
} else {
t1 = ty_max;
face_out = (b >= 0.0) ? 4 : 1;
}
if (tz_max < t1) {
t1 = tz_max;
face_out = (c >= 0.0) ? 5 : 2;
}
if (t0 < t1 && t1 > EPSILON) { // condition for a hit
if (t0 > EPSILON)
tmin = static_cast<float>(t0); // ray hits outside surface
else
tmin = static_cast<float>(t1); // ray hits inside surface
return true;
} else {
return false;
}
}
AABB Box::GetBoundingBox() const
{
AABB aabb;
aabb.x0 = x0;
aabb.y0 = y0;
aabb.z0 = z0;
aabb.x1 = x1;
aabb.y1 = y1;
aabb.z1 = z1;
return aabb;
}
void Box::SetSize(const Point3D& min, const Point3D& max)
{
x0 = min.x;
y0 = min.y;
z0 = min.z;
x1 = max.x;
y1 = max.y;
z1 = max.z;
}
Normal Box::GetNormal(const int face_hit) const
{
switch (face_hit)
{
case 0: return (Normal(-1, 0, 0)); // -x face
case 1: return (Normal(0, -1, 0)); // -y face
case 2: return (Normal(0, 0, -1)); // -z face
case 3: return (Normal(1, 0, 0)); // +x face
case 4: return (Normal(0, 1, 0)); // +y face
case 5: return (Normal(0, 0, 1)); // +z face
default: return Normal(-999, -999, -999);
}
}
} | 18.592105 | 69 | 0.538099 |
5039bf2a4c5eb2fd363d549f3197c97c53c2b558 | 1,142 | cpp | C++ | viewastrattapubblicazionestampata.cpp | mtodescato/ProgettoPAO | b73e871381e56d6b2917db8a7d227213c514f35b | [
"BSD-3-Clause"
] | null | null | null | viewastrattapubblicazionestampata.cpp | mtodescato/ProgettoPAO | b73e871381e56d6b2917db8a7d227213c514f35b | [
"BSD-3-Clause"
] | null | null | null | viewastrattapubblicazionestampata.cpp | mtodescato/ProgettoPAO | b73e871381e56d6b2917db8a7d227213c514f35b | [
"BSD-3-Clause"
] | null | null | null | #include "viewastrattapubblicazionestampata.h"
viewAstrattaPubblicazioneStampata::viewAstrattaPubblicazioneStampata(astrattaPubblicazione *p , QWidget* parent): viewAstrattaPubblicazione(p,parent){}
void viewAstrattaPubblicazioneStampata::caricaCampiDati() {
viewAstrattaPubblicazione::caricaCampiDati();
astrattaPubblicazioneStampata* tmp = dynamic_cast<astrattaPubblicazioneStampata*>(pub);
casaEditrice = new QLineEdit(QString::fromStdString(tmp->getCasaEditrice()),this);
viewLayout->addRow("Casa editrice: ", casaEditrice);
casaEditrice->setCursorPosition(0);
connect(casaEditrice,SIGNAL(textEdited(QString)),this,SLOT(valueChanged()));
}
void viewAstrattaPubblicazioneStampata::setEditablility(bool editable) {
viewAstrattaPubblicazione::setEditablility(editable);
casaEditrice->setReadOnly(!editable);
}
bool viewAstrattaPubblicazioneStampata::checkAndSet() {
astrattaPubblicazioneStampata* tmp = dynamic_cast<astrattaPubblicazioneStampata*>(pub);
if(viewAstrattaPubblicazione::checkAndSet()) {
tmp->setCasaEditrice(casaEditrice->text().toStdString());
return true;
}
else
return false;
}
| 40.785714 | 151 | 0.801226 |
503c2a584d5c9e29ceb89ad561296769117282b3 | 900 | cpp | C++ | Chapter_4_Mathematical_Logical_Bitwise_and_Shift_Operators/Program3.cpp | othneildrew/CPP-Programming-Practices | 27a20c00b395446a7d2e0dd4b199f4cd9e35591b | [
"MIT"
] | 1 | 2020-12-03T15:26:20.000Z | 2020-12-03T15:26:20.000Z | Chapter_4_Mathematical_Logical_Bitwise_and_Shift_Operators/Program3.cpp | othneildrew/CPP-Programming-Practices | 27a20c00b395446a7d2e0dd4b199f4cd9e35591b | [
"MIT"
] | null | null | null | Chapter_4_Mathematical_Logical_Bitwise_and_Shift_Operators/Program3.cpp | othneildrew/CPP-Programming-Practices | 27a20c00b395446a7d2e0dd4b199f4cd9e35591b | [
"MIT"
] | null | null | null | // Chapter 4: Program 3
/***
Write a C++ program to read diameter of a circle. Find perimeter and area
of the circle.
**/
#include <iostream>
#include <math.h>
#include <string>
using namespace std;
int main(void)
{
const double PI = 3.141592;
double Diameter, Radius, Perimeter, Area;
cout << "\n\t This program finds the perimeter and area of a circle";
cout << "\n\t To get started, please enter the diameter of the circle \n";
cin >> Diameter;
// Calculate perimeter and area using diameter and radius
Perimeter = Diameter * PI;
Radius = Diameter / 2;
Area = pow(Diameter, 2) * PI;
// Display correct values
cout << "Using a diameter of " << Diameter << endl;
cout << "The Perimeter is = " << Perimeter << endl;
cout << "The Area is = " << Area << endl;
system("pause");
return 0;
}
// Code written by: Othneil Drew
| 25 | 78 | 0.625556 |
50408d093de66e680842e2a1f4f0f26a9a96ebbf | 1,569 | cpp | C++ | oneflow/api/python/framework/py_distribute.cpp | jackalcooper/oneflow-1 | 16d261ea52a56c28db8e79dbbc79032b4804d09e | [
"Apache-2.0"
] | 2 | 2021-09-10T00:19:49.000Z | 2021-11-16T11:27:20.000Z | oneflow/api/python/framework/py_distribute.cpp | jackalcooper/oneflow-1 | 16d261ea52a56c28db8e79dbbc79032b4804d09e | [
"Apache-2.0"
] | null | null | null | oneflow/api/python/framework/py_distribute.cpp | jackalcooper/oneflow-1 | 16d261ea52a56c28db8e79dbbc79032b4804d09e | [
"Apache-2.0"
] | null | null | null | /*
Copyright 2020 The OneFlow Authors. All rights reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
#include <pybind11/pybind11.h>
#include "oneflow/core/common/container_util.h"
#include "oneflow/api/python/of_api_registry.h"
#include "oneflow/core/framework/py_distribute.h"
namespace py = pybind11;
namespace oneflow {
namespace compatible_py {
ONEFLOW_API_PYBIND11_MODULE("distribute", m) {
py::class_<Distribute, std::shared_ptr<Distribute>>(m, "Distribute");
py::class_<AutoDistribute, Distribute, std::shared_ptr<AutoDistribute>>(m, "AutoDistribute");
py::class_<BroadcastDistribute, Distribute, std::shared_ptr<BroadcastDistribute>>(
m, "BroadcastDistribute");
py::class_<SplitDistribute, Distribute, std::shared_ptr<SplitDistribute>>(m, "SplitDistribute")
.def_property_readonly("axis", &SplitDistribute::axis);
m.def("auto", &GlobalAutoDistribute);
m.def("broadcast", &GlobalBroadcastDistribute);
m.def("split", [](int axis) { return GlobalSplitDistribute(axis).GetPtrOrThrow(); });
}
} // namespace compatible_py
} // namespace oneflow
| 37.357143 | 97 | 0.765456 |
504493f429a04b09093b61d7db8abfe5b45161f9 | 4,993 | cpp | C++ | kmean-segmentation.cpp | erikj23/segmentation-context | 72e51cf54092bbbe87a2aa1c85e595fbf927b53f | [
"MIT"
] | null | null | null | kmean-segmentation.cpp | erikj23/segmentation-context | 72e51cf54092bbbe87a2aa1c85e595fbf927b53f | [
"MIT"
] | null | null | null | kmean-segmentation.cpp | erikj23/segmentation-context | 72e51cf54092bbbe87a2aa1c85e595fbf927b53f | [
"MIT"
] | null | null | null |
// 11 2019, Authors:
// Jeremy Deng
// Erik Maldonado
//std
#include <String>
#include <iostream>
#include <direct.h>
//opencv
#include <opencv2/core.hpp>
#include <opencv2/highgui.hpp>
#include <opencv2/imgproc.hpp>
//namespace
using namespace cv;
using namespace std;
//k mean constant
const int ITER = 10;
const double EPSILON = 1.0;
const int ATTEMPTS = 2;
// assumptions:
// img: valid image matrix in opencv
// rectangle: rectangle are smaller than img window
// outcome: outputing image with grabcuts segments
Mat _grabCut(const Mat& img, Rect rectangle) {
//initializing the matrix for grabcut
Mat results;
Mat background_m, foreground_m;
//grab cut
grabCut(img, results, rectangle, background_m, foreground_m, 1, GC_INIT_WITH_RECT);
compare(results, GC_PR_FGD, results, CMP_EQ);
//making the foreground objects
Mat foreground(img.size(), CV_8UC3, Scalar(0, 0, 0));
img.copyTo(foreground, results);
return foreground;
}
// assumptions:
// input: valid image file loaded in opencv
// file_dir: correct directory of the image
// cluster_size: integer values: [2-20]
// outcome: outputing the image into segments and write to disk
void segmentation(Mat& input, const string& file_dir, const int& cluster_size) {
//read in the image and make a copy
Mat img = input.clone();
// convert image pixel to float & reshape to a [3 x W*H] Mat
// (so every pixel is on a row of it's own)
Mat data;
img.convertTo(data, CV_32F);
data = data.reshape(1, static_cast<int>(data.total()));
// do kmeans
Mat labels, centers;
int clusters = cluster_size;
kmeans(data, clusters, labels, TermCriteria(TermCriteria::EPS + TermCriteria::MAX_ITER, ITER, EPSILON), ATTEMPTS,
KMEANS_RANDOM_CENTERS, centers);
// reshape labels and cluster centers to a single row of Vec3f pixels
centers = centers.reshape(3, centers.rows);
data = data.reshape(3, data.rows);
//for each cluster, outputing the segments
for (int center_id = 0; center_id < clusters; center_id++) {
Mat temp = data.clone();
Vec3f* pointer = temp.ptr<Vec3f>();
for (int i = 0; i < temp.rows; i++) {
if (center_id == labels.at<int>(i)) {
//pointer[i] = centers.at<Vec3f>(center_id);
}
else {
pointer[i] = Vec3f{ 0,0,0 };
}
}
string output_dir = format("./segments/%s/%s_kmean%d_%d.jpg", file_dir.c_str(), file_dir.c_str(), clusters, center_id);
temp = temp.reshape(3, img.rows);
temp.convertTo(temp, CV_8U);
imwrite(output_dir, temp);
}
// replace pixel values with their center value:
Vec3f* p = data.ptr<Vec3f>();
for (int i = 0; i < data.rows; i++) {
int center_id = labels.at<int>(i);
p[i] = centers.at<Vec3f>(center_id);
}
// back to 2d, and uchar:
img = data.reshape(3, img.rows);
img.convertTo(img, CV_8U);
//display the k mean result and output into the segment directory
//namedWindow("Original Image");
//imshow("Original Image", ocv);
imwrite(format("./segments/%s/%s_kmean%d_full.jpg", file_dir.c_str(), file_dir.c_str(), clusters), img);
}
int main(int argc, char* argv[])
{
//assumption that the imgage
string filename = "./images/background.jpg";
string file_dir = filename.substr(9, filename.substr(9).find("."));
string create_dir = format("./segments/%s", file_dir.c_str());
//making the folder for output
auto t = _mkdir(format("./segments/%s", file_dir.c_str()).c_str());
auto a = _mkdir(format("./output/%s", file_dir.c_str()).c_str());
Mat img = imread(filename);
segmentation(img, file_dir, 2);
//cutting the image in five window
Rect quadrant1(10, 10, img.cols / 2 - 10, img.rows / 2 - 10);
Rect quadrant4(img.cols / 2 + 10, img.rows / 2 + 10, img.cols / 2 - 10, img.rows / 2 - 10);
Rect quadrant3(10, img.rows / 2 + 10, img.cols / 2 - 10, img.rows / 2 - 10);
Rect quadrant2(img.cols / 2 + 10, 10, img.cols / 2 - 10, img.rows / 2 - 10);
//using the window located in the center and have a width of col*0.75, height of row*0.75
Rect center(static_cast<int>(img.cols * 0.25 / 2), static_cast<int>(img.rows * 0.25 / 2), static_cast<int>(img.cols * 0.75), static_cast<int>(img.rows * 0.75));
//initializing directory for each cut
string gc_outputfile_dir1 = format("./segments/%s/%s_gc_%s.jpg", file_dir.c_str(), file_dir.c_str(), "quadrant1");
string gc_outputfile_dir2 = format("./segments/%s/%s_gc_%s.jpg", file_dir.c_str(), file_dir.c_str(), "quadrant2");
string gc_outputfile_dir3 = format("./segments/%s/%s_gc_%s.jpg", file_dir.c_str(), file_dir.c_str(), "quadrant3");
string gc_outputfile_dir4 = format("./segments/%s/%s_gc_%s.jpg", file_dir.c_str(), file_dir.c_str(), "quadrant4");
string gc_outputfile_dir5 = format("./segments/%s/%s_gc_%s.jpg", file_dir.c_str(), file_dir.c_str(), "center");
imwrite(gc_outputfile_dir1, _grabCut(img, quadrant1));
imwrite(gc_outputfile_dir2, _grabCut(img, quadrant2));
imwrite(gc_outputfile_dir3, _grabCut(img, quadrant3));
imwrite(gc_outputfile_dir4, _grabCut(img, quadrant4));
imwrite(gc_outputfile_dir5, _grabCut(img, center));
return 0;
}
| 34.673611 | 161 | 0.694773 |
50534627e9e01b4312b826745b1493b5659a67cb | 471 | hpp | C++ | src/Util/ImGui.hpp | D3r3k23/DrkCraft | 5eaae66f558ce84f18de702b4227ca8d2cfe534f | [
"MIT"
] | 1 | 2022-02-10T04:41:57.000Z | 2022-02-10T04:41:57.000Z | src/Util/ImGui.hpp | D3r3k23/DrkCraft | 5eaae66f558ce84f18de702b4227ca8d2cfe534f | [
"MIT"
] | null | null | null | src/Util/ImGui.hpp | D3r3k23/DrkCraft | 5eaae66f558ce84f18de702b4227ca8d2cfe534f | [
"MIT"
] | null | null | null | #ifndef DRK_UTIL_IMGUI_HPP
#define DRK_UTIL_IMGUI_HPP
#include "Core/Base.hpp"
#include <imgui/imgui.h>
#include <string_view>
namespace DrkCraft::DrkImGui
{
void BeginFullscreen(std::string_view name, ImGuiWindowFlags flags=0);
void BeginCentered(std::string_view name, const ImVec2& size, ImGuiWindowFlags flags=0);
void TextCentered(std::string_view text);
bool ButtonCentered(const char* text, const ImVec2& size);
}
#endif // DRK_UTIL_IMGUI_HPP
| 24.789474 | 92 | 0.766454 |
5053ea1a70f91478eda466acf7088a52a44b6e56 | 1,030 | hpp | C++ | include/deferred/detail/deferred_type_helper.hpp | JohnJocoo/deferred_heap | 700510b62bec42c77b52016ac15091b77d5dc619 | [
"BSL-1.0"
] | null | null | null | include/deferred/detail/deferred_type_helper.hpp | JohnJocoo/deferred_heap | 700510b62bec42c77b52016ac15091b77d5dc619 | [
"BSL-1.0"
] | null | null | null | include/deferred/detail/deferred_type_helper.hpp | JohnJocoo/deferred_heap | 700510b62bec42c77b52016ac15091b77d5dc619 | [
"BSL-1.0"
] | null | null | null | #pragma once
#include <typeinfo>
namespace def::detail
{
struct memory_chunk_header;
/// Base for helper for deferred-enabled type.
class type_helper
{
public:
explicit type_helper(const std::type_info& info,
std::size_t bytes_object,
std::size_t bytes_allocator)
: type_info{info}
, bytes_per_object{bytes_object}
, bytes_per_allocator{bytes_allocator}
{ }
/// Traverse through deferred pointers known to
/// deferred-enabled type and recursively mark them as visited.
virtual void mark_recursive(memory_chunk_header&) const = 0;
/// Run destructor(s).
void destroy(memory_chunk_header&) const;
/// Free memory.
virtual void deallocate(memory_chunk_header*) const = 0;
private:
virtual void destroy_impl(memory_chunk_header&) const = 0;
public:
const std::type_info& type_info;
const std::size_t bytes_per_object;
const std::size_t bytes_per_allocator;
}; // class type_helper
} // namespace def::detail
| 23.953488 | 67 | 0.691262 |
50558d1556bcc275404f44ab2c051caf2b0aac33 | 10,708 | cpp | C++ | SPHINXsys/src/shared/particles/base_particles.cpp | SoftwareImpacts/SIMPAC-2020-34 | eb2d69e61548eaa11b5a9c20e312d135c5d857f5 | [
"Apache-2.0"
] | 2 | 2020-09-24T07:39:22.000Z | 2021-04-24T22:12:49.000Z | SPHINXsys/src/shared/particles/base_particles.cpp | SoftwareImpacts/SIMPAC-2020-34 | eb2d69e61548eaa11b5a9c20e312d135c5d857f5 | [
"Apache-2.0"
] | null | null | null | SPHINXsys/src/shared/particles/base_particles.cpp | SoftwareImpacts/SIMPAC-2020-34 | eb2d69e61548eaa11b5a9c20e312d135c5d857f5 | [
"Apache-2.0"
] | null | null | null | /**
* @file base_particles.cpp
* @brief Definition of funcitons declared in base_particles.h
* @author Xiangyu Hu and Chi Zhang
* @version 0.1
*/
/**
* @file base_particles.cpp
* @author Luhui Han, Chi ZHang and Xiangyu Hu
* @version 0.1
*/
#include "base_particles.h"
#include "base_material.h"
#include "base_body.h"
#include "all_particle_generators.h"
#include "mesh_cell_linked_list.h"
namespace SPH
{
//=================================================================================================//
size_t BaseParticleData::total_number_of_particles_ = 0;
//=================================================================================================//
BaseParticleData::BaseParticleData()
: vel_n_(0), pos_n_(0), pos_0_(0), Vol_(0), Vol_0_(0), sigma_0_(0),
dvel_dt_others_(0), dvel_dt_(0), is_sortable_(true),
particle_id_(0)
{
total_number_of_particles_++;
}
//=================================================================================================//
BaseParticleData::BaseParticleData(Vecd position, Real Vol_0, Real sigma_0)
: vel_n_(0), pos_n_(position), pos_0_(position), Vol_(Vol_0), Vol_0_(Vol_0),
sigma_0_(sigma_0), dvel_dt_others_(0), dvel_dt_(0), is_sortable_(true), particle_id_(0)
{
total_number_of_particles_++;
}
//=================================================================================================//
BaseParticles::BaseParticles(SPHBody* body, BaseMaterial* base_material)
: body_(body), base_material_(base_material),
body_name_(body->GetBodyName()), speed_max_(0.0),
signal_speed_max_(0.0)
{
body->base_particles_ = this;
base_material->assignParticles(this);
body->base_mesh_cell_linked_list_->assignParticles(this);
ParticleGenerator* particle_generator;
switch (body->particle_generator_op_)
{
case ParticlesGeneratorOps::lattice: {
particle_generator = new ParticleGeneratorLattice(*body);
break;
}
case ParticlesGeneratorOps::direct: {
particle_generator = new ParticleGeneratorDirect(*body);
break;
}
case ParticlesGeneratorOps::regularized: {
particle_generator = new ParticleGeneratorRegularized(*body);
break;
}
default: {
std::cout << "\n FAILURE: the type of particle generator is undefined!" << std::endl;
std::cout << __FILE__ << ':' << __LINE__ << std::endl;
exit(1);
break;
}
}
particle_generator->CreateBaseParticles(this);
delete particle_generator;
real_particles_bound_ = body_->number_of_particles_;
number_of_ghost_particles_ = 0;
body->AllocateMemoryCellLinkedList();
}
//=================================================================================================//
BaseParticles::BaseParticles(SPHBody* body)
: BaseParticles(body, new BaseMaterial()) {}
//=================================================================================================//
void BaseParticles::InitializeABaseParticle(Vecd pnt, Real Vol_0, Real sigma_0)
{
size_t particle_index = base_particle_data_.size();
base_particle_data_.push_back(BaseParticleData(pnt, Vol_0, sigma_0));
base_particle_data_[particle_index].particle_id_ = particle_index;
}
//=================================================================================================//
void BaseParticles::AddABufferParticle()
{
size_t particle_index = base_particle_data_.size();
base_particle_data_.push_back(BaseParticleData());
base_particle_data_[particle_index].particle_id_ = particle_index;
}
//=================================================================================================//
void BaseParticles::CopyFromAnotherParticle(size_t this_particle_index, size_t another_particle_index)
{
size_t particle_id = base_particle_data_[this_particle_index].particle_id_;
base_particle_data_[this_particle_index] = base_particle_data_[another_particle_index];
base_particle_data_[this_particle_index].particle_id_ = particle_id;
}
//=================================================================================================//
void BaseParticles::UpdateFromAnotherParticle(size_t this_particle_index, size_t another_particle_index)
{
base_particle_data_[this_particle_index].pos_n_ = base_particle_data_[another_particle_index].pos_n_;
base_particle_data_[this_particle_index].vel_n_ = base_particle_data_[another_particle_index].vel_n_;
}
//=================================================================================================//
void BaseParticles::swapParticles(size_t this_particle_index, size_t that_particle_index)
{
std::swap(base_particle_data_[this_particle_index], base_particle_data_[that_particle_index]);
}
//=================================================================================================//
bool BaseParticles::isSwappingAllowed(size_t this_particle_index, size_t that_particle_index)
{
return base_particle_data_[this_particle_index].is_sortable_
&& base_particle_data_[that_particle_index].is_sortable_;
}
//=================================================================================================//
size_t BaseParticles ::insertAGhostParticle(size_t index_particle_i)
{
number_of_ghost_particles_ += 1;
size_t expected_size = real_particles_bound_ + number_of_ghost_particles_;
size_t expected_particle_index = expected_size - 1;
if (expected_size <= base_particle_data_.size()) {
CopyFromAnotherParticle(expected_particle_index, index_particle_i);
base_particle_data_[expected_particle_index].particle_id_
= base_particle_data_[index_particle_i].particle_id_;
}
else {
AddABufferParticle();
CopyFromAnotherParticle(expected_particle_index, index_particle_i);
base_particle_data_[expected_particle_index].particle_id_
= base_particle_data_[index_particle_i].particle_id_;
}
return expected_particle_index;
}
//=================================================================================================//
SPHBody* BaseParticles::getSPHBody()
{
return body_;
}
//=================================================================================================//
void BaseParticles::WriteParticlesToVtuFile(ofstream& output_file)
{
size_t number_of_particles = body_->number_of_particles_;
//write coordinates of particles
output_file << " <Points>\n";
output_file << " <DataArray Name=\"Position\" type=\"Float32\" NumberOfComponents=\"3\" Format=\"ascii\">\n";
output_file << " ";
for (size_t i = 0; i != number_of_particles; ++i) {
Vec3d particle_position = upgradeToVector3D(base_particle_data_[i].pos_n_);
output_file << particle_position[0] << " " << particle_position[1] << " " << particle_position[2] << " ";
}
output_file << std::endl;
output_file << " </DataArray>\n";
output_file << " </Points>\n";
//write data of particles
output_file << " <PointData Vectors=\"vector\">\n";
output_file << " <DataArray Name=\"Particle_ID\" type=\"Int32\" Format=\"ascii\">\n";
output_file << " ";
for (size_t i = 0; i != number_of_particles; ++i) {
output_file << i << " ";
}
output_file << std::endl;
output_file << " </DataArray>\n";
output_file << " <DataArray Name=\"Number Density\" type=\"Float32\" Format=\"ascii\">\n";
output_file << " ";
for (size_t i = 0; i != number_of_particles; ++i) {
output_file << fixed << setprecision(9) << base_particle_data_[i].sigma_0_ << " ";
}
output_file << std::endl;
output_file << " </DataArray>\n";
base_material_->WriteMaterialPropertyToVtuFile(output_file);
output_file << " <DataArray Name=\"Velocity\" type=\"Float32\" NumberOfComponents=\"3\" Format=\"ascii\">\n";
output_file << " ";
for (size_t i = 0; i != number_of_particles; ++i) {
Vec3d particle_velocity = upgradeToVector3D(base_particle_data_[i].vel_n_);
output_file << particle_velocity[0] << " " << particle_velocity[1] << " " << particle_velocity[2] << " ";
}
output_file << std::endl;
output_file << " </DataArray>\n";
}
//=================================================================================================//
void BaseParticles::WriteToXmlForReloadParticle(std::string &filefullpath)
{
const SimTK::String xml_name("particles_xml"), ele_name("particles");
unique_ptr<XmlEngine> reload_xml(new XmlEngine(xml_name, ele_name));
for (size_t i = 0; i != body_->number_of_particles_; ++i)
{
reload_xml->CreatXmlElement("particle");
reload_xml->AddAttributeToElement<Vecd>("Position", base_particle_data_[i].pos_n_);
reload_xml->AddAttributeToElement<Real>("Volume", base_particle_data_[i].Vol_);
reload_xml->AddAttributeToElement<Real>("NumberDensity", base_particle_data_[i].sigma_0_);
reload_xml->AddElementToXmlDoc();
}
reload_xml->WriteToXmlFile(filefullpath);
}
//=================================================================================================//
void BaseParticles::ReadFromXmlForReloadParticle(std::string &filefullpath)
{
size_t number_of_particles = 0;
unique_ptr<XmlEngine> read_xml(new XmlEngine());
read_xml->LoadXmlFile(filefullpath);
SimTK::Xml::element_iterator ele_ite_ = read_xml->root_element_.element_begin();
for (; ele_ite_ != read_xml->root_element_.element_end(); ++ele_ite_)
{
Vecd position = read_xml->GetRequiredAttributeValue<Vecd>(ele_ite_, "Position");
base_particle_data_[number_of_particles].pos_n_ = position;
Real volume = read_xml->GetRequiredAttributeValue<Real>(ele_ite_, "Volume");
base_particle_data_[number_of_particles].Vol_ = volume;
Real sigma = read_xml->GetRequiredAttributeValue<Real>(ele_ite_, "NumberDensity");
base_particle_data_[number_of_particles].sigma_0_ = sigma;
number_of_particles++;
}
if(number_of_particles != base_particle_data_.size())
{
std::cout << "\n Error: reload particle number does not matrch" << std::endl;
std::cout << __FILE__ << ':' << __LINE__ << std::endl;
exit(1);
}
}
//=================================================================================================//
BaseParticles* BaseParticles::PointToThisObject()
{
return this;
}
//=================================================================================================//
void BaseParticles::mirrorInAxisDirection(size_t particle_index_i, Vecd body_bound, int axis_direction)
{
BaseParticleData& base_particle_data_i = base_particle_data_[particle_index_i];
base_particle_data_i.pos_n_[axis_direction]
= 2.0 * body_bound[axis_direction] - base_particle_data_i.pos_n_[axis_direction];
base_particle_data_i.vel_n_[axis_direction] *= -1.0;
}
//=================================================================================================//
}
| 43.004016 | 115 | 0.607677 |
5055bedb072381a75762b2d8ba9b253cba5b000f | 4,331 | cpp | C++ | src/test/value_parser_path_test.cpp | RichardCory/svgpp | 801e0142c61c88cf2898da157fb96dc04af1b8b0 | [
"BSL-1.0"
] | 428 | 2015-01-05T17:13:54.000Z | 2022-03-31T08:25:47.000Z | src/test/value_parser_path_test.cpp | andrew2015/svgpp | 1d2f15ab5e1ae89e74604da08f65723f06c28b3b | [
"BSL-1.0"
] | 61 | 2015-01-08T14:32:27.000Z | 2021-12-06T16:55:11.000Z | src/test/value_parser_path_test.cpp | andrew2015/svgpp | 1d2f15ab5e1ae89e74604da08f65723f06c28b3b | [
"BSL-1.0"
] | 90 | 2015-05-19T04:56:46.000Z | 2022-03-26T16:42:50.000Z | #include <svgpp/parser/path_data.hpp>
// Only compilation is checked
using namespace svgpp;
namespace
{
struct PathContext1
{
public:
void path_move_to(double x, double y, tag::coordinate::absolute)
{}
void path_line_to(double x, double y, tag::coordinate::absolute)
{}
void path_cubic_bezier_to(
double x1, double y1,
double x2, double y2,
double x, double y,
tag::coordinate::absolute)
{}
void path_quadratic_bezier_to(
double x1, double y1,
double x, double y,
tag::coordinate::absolute)
{}
void path_elliptical_arc_to(
double rx, double ry, double x_axis_rotation,
bool large_arc_flag, bool sweep_flag,
double x, double y,
tag::coordinate::absolute)
{}
void path_close_subpath()
{}
void path_exit()
{}
};
struct PathContext2
{
void path_move_to(double x, double y, tag::coordinate::absolute)
{}
void path_line_to(double x, double y, tag::coordinate::absolute)
{}
void path_line_to_ortho(double coord, bool horizontal, tag::coordinate::absolute)
{}
void path_cubic_bezier_to(double x1, double y1,
double x2, double y2,
double x, double y,
tag::coordinate::absolute)
{}
void path_cubic_bezier_to(
double x2, double y2,
double x, double y,
tag::coordinate::absolute)
{}
void path_quadratic_bezier_to(
double x1, double y1,
double x, double y,
tag::coordinate::absolute)
{}
void path_quadratic_bezier_to(
double x, double y,
tag::coordinate::absolute)
{}
void path_elliptical_arc_to(
double rx, double ry, double x_axis_rotation,
bool large_arc_flag, bool sweep_flag,
double x, double y,
tag::coordinate::absolute)
{}
void path_move_to(double x, double y, tag::coordinate::relative)
{}
void path_line_to(double x, double y, tag::coordinate::relative)
{}
void path_line_to_ortho(double coord, bool horizontal, tag::coordinate::relative)
{}
void path_cubic_bezier_to(double x1, double y1,
double x2, double y2,
double x, double y,
tag::coordinate::relative)
{}
void path_cubic_bezier_to(
double x2, double y2,
double x, double y,
tag::coordinate::relative)
{}
void path_quadratic_bezier_to(
double x1, double y1,
double x, double y,
tag::coordinate::relative)
{}
void path_quadratic_bezier_to(
double x, double y,
tag::coordinate::relative)
{}
void path_elliptical_arc_to(
double rx, double ry, double x_axis_rotation,
bool large_arc_flag, bool sweep_flag,
double x, double y,
tag::coordinate::relative)
{}
void path_close_subpath()
{}
void path_exit()
{}
};
}
void check_path()
{
std::string testStr;
{
PathContext1 ctx;
value_parser<tag::type::path_data>::parse(
tag::attribute::d(), ctx, testStr, tag::source::attribute());
}
{
PathContext2 ctx;
value_parser<
tag::type::path_data,
path_policy<policy::path::raw>
>::parse(
tag::attribute::d(), ctx, testStr, tag::source::attribute());
}
} | 28.682119 | 87 | 0.471946 |
506105a73ca0d4f36849cca455ce3168ace87b90 | 2,920 | cpp | C++ | src/GUI/GHGUINotchedSliderMonitorXMLLoader.cpp | GoldenHammerSoftware/GH | 757213f479c0fc80ed1a0f59972bf3e9d92b7526 | [
"MIT"
] | null | null | null | src/GUI/GHGUINotchedSliderMonitorXMLLoader.cpp | GoldenHammerSoftware/GH | 757213f479c0fc80ed1a0f59972bf3e9d92b7526 | [
"MIT"
] | null | null | null | src/GUI/GHGUINotchedSliderMonitorXMLLoader.cpp | GoldenHammerSoftware/GH | 757213f479c0fc80ed1a0f59972bf3e9d92b7526 | [
"MIT"
] | null | null | null | // Copyright Golden Hammer Software
#include "GHGUINotchedSliderMonitorXMLLoader.h"
#include "GHGUINotchedSliderMonitor.h"
#include "GHXMLNode.h"
#include "GHPlatform/GHDebugMessage.h"
#include "GHXMLObjFactory.h"
GHGUINotchedSliderMonitorXMLLoader::GHGUINotchedSliderMonitorXMLLoader(GHPropertyContainer& appProps, const GHXMLObjFactory& xmlObjFactory, const GHStringIdFactory& hashtable)
: mAppProps(appProps)
, mXMLObjFactory(xmlObjFactory)
, mIdFactory(hashtable)
{
}
//<guiNotchedSliderMonitor prop = "GP_DIFFICULTYSLIDERVAL">
// <notches>
// <notch val = "0">
// <transitions>
// <transitionsGoHere/>
// </transitions>
// </notch>
// </notches>
//</guiNotchedSliderMonitor/>
void* GHGUINotchedSliderMonitorXMLLoader::create(const GHXMLNode& node, GHPropertyContainer& extraData) const
{
GHIdentifier propId;
if (!node.readAttrIdentifier("prop", propId, mIdFactory))
{
GHDebugMessage::outputString("Failed to load a guiNotchedSliderMonitor because there is no \"prop\" identifier to monitor");
return 0;
}
GHGUINotchedSliderMonitor* ret = 0;
const GHXMLNode* notchesNode = node.getChild("notches", false);
if (notchesNode)
{
ret = new GHGUINotchedSliderMonitor(mAppProps, propId);
bool didLoadAnyNotches = false;
const std::vector<GHXMLNode*>& notchesList = notchesNode->getChildren();
size_t numNotches = notchesList.size();
for (size_t i = 0; i < numNotches; ++i)
{
const GHXMLNode& notchNode = *notchesList[i];
float val = 0;
if (notchNode.readAttrFloat("val", val))
{
didLoadAnyNotches = true;
GHGUINotchedSliderMonitor::Notch& notch = ret->createNotch(val);
const GHXMLNode* transitionListNode = notchNode.getChild("transitions", false);
if (transitionListNode)
{
const std::vector<GHXMLNode*>& transitionList = transitionListNode->getChildren();
size_t numTransitions = transitionList.size();
notch.mTransitions.reserve(numTransitions);
for (size_t j = 0; j < numTransitions; ++j)
{
const GHXMLNode& transitionNode = *transitionList[j];
GHTransition* transition = (GHTransition*)mXMLObjFactory.load(transitionNode, &extraData);
if (transition)
{
notch.mTransitions.push_back(transition);
}
else
{
GHDebugMessage::outputString("Failed to load a transition in a guiNotchedSliderMonitor. XML Node Name: %s", transitionNode.getName().getChars());
}
}
}
}
else
{
GHDebugMessage::outputString("Failed to load a notch in a guiNotchedSliderMonitor because it did not have a \"val\" attribute");
}
}
if (!didLoadAnyNotches)
{
delete ret;
ret = 0;
GHDebugMessage::outputString("Failed to load a guiNotchedSliderMonitor because no notches were able to be loaded");
}
}
else
{
GHDebugMessage::outputString("Failed to load a guiNotchedSliderMonitor because there is no \"notches\" xml node");
}
return ret;
}
| 31.397849 | 175 | 0.719521 |
50667bb533ec77b5b334e531e0a1994367d5e6f8 | 729 | cpp | C++ | rtx/core/material/lambert.cpp | musyoku/chainer-gqn-playground | 657bb931d2c531ff8f078fcb1686bbf1999afa7f | [
"MIT"
] | 28 | 2018-09-06T18:08:28.000Z | 2021-12-19T13:30:41.000Z | rtx/core/material/lambert.cpp | musyoku/chainer-gqn-playground | 657bb931d2c531ff8f078fcb1686bbf1999afa7f | [
"MIT"
] | 3 | 2019-03-01T02:50:15.000Z | 2019-06-25T08:12:21.000Z | rtx/core/material/lambert.cpp | musyoku/chainer-gqn-playground | 657bb931d2c531ff8f078fcb1686bbf1999afa7f | [
"MIT"
] | 8 | 2018-10-26T12:05:52.000Z | 2019-09-04T05:14:24.000Z | #include "lambert.h"
#include "../header/enum.h"
#include "../header/struct.h"
#include <cstring>
namespace rtx {
LambertMaterial::LambertMaterial(float albedo)
{
_albedo = albedo;
}
float LambertMaterial::albedo() const
{
return _albedo;
}
int LambertMaterial::type() const
{
return RTXMaterialTypeLambert;
}
int LambertMaterial::attribute_bytes() const
{
return sizeof(rtxLambertMaterialAttribute);
}
void LambertMaterial::serialize_attributes(rtx::array<rtxMaterialAttributeByte>& array, int offset) const
{
rtxLambertMaterialAttribute attr;
attr.albedo = _albedo;
rtxMaterialAttributeByte* pointer = array.data();
std::memcpy(&pointer[offset], &attr, sizeof(rtxLambertMaterialAttribute));
}
} | 24.3 | 105 | 0.748971 |
506c250b70618bfcc89ad1ff716504527bdbcba2 | 315 | cpp | C++ | json-parser002/lib/json_null.cpp | syohex/cpp-study | 598c2afbe77c6d4ba88f549d3e99f97b5bf81acb | [
"MIT"
] | null | null | null | json-parser002/lib/json_null.cpp | syohex/cpp-study | 598c2afbe77c6d4ba88f549d3e99f97b5bf81acb | [
"MIT"
] | null | null | null | json-parser002/lib/json_null.cpp | syohex/cpp-study | 598c2afbe77c6d4ba88f549d3e99f97b5bf81acb | [
"MIT"
] | null | null | null | #include "json_null.h"
JsonNull::JsonNull() : JsonValue(JsonType::kNull) {
}
bool JsonNull::IsNull() const noexcept {
return true;
}
bool JsonNull::operator==(const JsonValue &value) const noexcept {
return type_ == value.Type();
}
std::nullptr_t JsonNull::Value() const noexcept {
return nullptr;
}
| 19.6875 | 66 | 0.695238 |
506dfecc2144a37e75afd887e1b31649f9366d3d | 407 | cpp | C++ | src/processor.cpp | zenocoz/SystemMonitor | a2a96d6b8061085a6ab19c40cf26cd732bebaf7f | [
"MIT"
] | null | null | null | src/processor.cpp | zenocoz/SystemMonitor | a2a96d6b8061085a6ab19c40cf26cd732bebaf7f | [
"MIT"
] | null | null | null | src/processor.cpp | zenocoz/SystemMonitor | a2a96d6b8061085a6ab19c40cf26cd732bebaf7f | [
"MIT"
] | null | null | null | #include "processor.h"
#include <vector>
#include <string>
#include "linux_parser.h"
using std::stof;
using std::string;
using std::to_string;
using std::vector;
using namespace LinuxParser;
float Processor::Utilization() {
vector<string> cpu = LinuxParser::CpuUtilization();
// utilization = active/total
utilization_ = stof(cpu[1])/stof(cpu[2]);
return utilization_;
} | 18.5 | 55 | 0.683047 |
506ef4cf2c88601c2d36fd1a64a0e4ca520d25ad | 1,586 | hpp | C++ | rds/src/rds_3.hpp | epfl-lasa/rds | 574b3881dbaf4fdcd785dd96ba4c451928454b40 | [
"MIT"
] | 12 | 2020-08-18T09:01:50.000Z | 2022-03-17T19:53:30.000Z | rds/src/rds_3.hpp | epfl-lasa/rds | 574b3881dbaf4fdcd785dd96ba4c451928454b40 | [
"MIT"
] | null | null | null | rds/src/rds_3.hpp | epfl-lasa/rds | 574b3881dbaf4fdcd785dd96ba4c451928454b40 | [
"MIT"
] | 1 | 2021-08-25T13:12:55.000Z | 2021-08-25T13:12:55.000Z | #ifndef RDS_3_HPP
#define RDS_3_HPP
#include "geometry.hpp"
#include "capsule.hpp"
#include <vector>
namespace Geometry2D
{
struct RDS3
{
RDS3(float tau, float delta, float v_max);
void computeCorrectedVelocity(const Capsule& robot_shape, const Vec2& p_ref, const Vec2& v_nominal_p_ref,
const std::vector<AdditionalPrimitives2D::Circle>& objects, Vec2* v_corrected_p_ref);
void computeCorrectedVelocity(const AdditionalPrimitives2D::Circle& robot_shape, const Vec2& p_ref,
const Vec2& v_nominal_p_ref, const std::vector<AdditionalPrimitives2D::Circle>& circle_objects,
const std::vector<Capsule>& capsule_objects, Vec2* v_corrected_p_ref);
float tau, delta, v_max, v_max_sqrt_2;
std::vector<Geometry2D::HalfPlane2> constraints;
private:
void generateConstraints(const Capsule& robot_shape, const Vec2& p_ref, const Vec2& v_nominal_p_ref,
const std::vector<AdditionalPrimitives2D::Circle>& objects, std::vector<HalfPlane2>* constraints);
void generateConstraints(const AdditionalPrimitives2D::Circle& robot_shape, const Vec2& p_ref,
const Vec2& v_nominal_p_ref, const std::vector<AdditionalPrimitives2D::Circle>& circle_objects,
const std::vector<Capsule>& capsule_objects, std::vector<HalfPlane2>* constraints);
void generateAndAddConstraint(const Vec2& robot_point, float robot_radius,
const Vec2& object_point, float object_radius, const Vec2& p_ref,
const Vec2& v_nominal_p_ref, std::vector<HalfPlane2>* constraints);
void solve(const Vec2& v_nominal, std::vector<HalfPlane2>& constraints, Vec2* v_corrected);
};
}
#endif | 36.883721 | 107 | 0.77995 |
507098b06484c39551ae4b05fd71ecee34241a0a | 1,078 | cpp | C++ | core/dawn_player/error.cpp | lxrite/DawnPlayer | ba3c7f1f01d7609213492f4c9ba4a91454fb7365 | [
"MIT"
] | 55 | 2015-03-22T16:19:03.000Z | 2022-03-18T18:11:39.000Z | core/dawn_player/error.cpp | lxrite/DawnPlayer | ba3c7f1f01d7609213492f4c9ba4a91454fb7365 | [
"MIT"
] | 2 | 2015-04-09T07:42:08.000Z | 2015-07-26T02:56:06.000Z | core/dawn_player/error.cpp | lxrite/DawnPlayer | ba3c7f1f01d7609213492f4c9ba4a91454fb7365 | [
"MIT"
] | 11 | 2015-04-29T04:52:19.000Z | 2019-12-31T09:36:53.000Z | /*
* error.cpp:
*
* Copyright (C) 2015-2017 Light Lin <blog.poxiao.me> All Rights Reserved.
*
*/
#include "error.hpp"
namespace dawn_player {
open_error::open_error(const std::string& what_arg, open_error_code ec)
: what_msg(what_arg), error_code(ec)
{}
const char* open_error::what() const
{
return this->what_msg.c_str();
}
open_error_code open_error::code() const
{
return this->error_code;
}
get_sample_error::get_sample_error(const std::string& what_arg, get_sample_error_code ec)
: what_msg(what_arg), error_code(ec)
{}
const char* get_sample_error::what() const {
return this->what_msg.c_str();
}
get_sample_error_code get_sample_error::code() const {
return this->error_code;
}
seek_error::seek_error(const std::string& what_arg, seek_error_code ec)
: what_msg(what_arg), error_code(ec)
{}
const char* seek_error::what() const
{
return this->what_msg.c_str();
}
seek_error_code seek_error::code() const
{
return this->error_code;
}
} // namespace dawn_player
| 20.339623 | 90 | 0.67718 |
507124ab12997218d83444d5919d7225bc69a457 | 996 | cpp | C++ | UVa 10454 - Trexpression/sample/10454 - Trexpression.cpp | tadvi/uva | 0ac0cbdf593879b4fb02a3efc09adbb031cb47d5 | [
"MIT"
] | 1 | 2020-11-24T03:17:21.000Z | 2020-11-24T03:17:21.000Z | UVa 10454 - Trexpression/sample/10454 - Trexpression.cpp | tadvi/uva | 0ac0cbdf593879b4fb02a3efc09adbb031cb47d5 | [
"MIT"
] | null | null | null | UVa 10454 - Trexpression/sample/10454 - Trexpression.cpp | tadvi/uva | 0ac0cbdf593879b4fb02a3efc09adbb031cb47d5 | [
"MIT"
] | 1 | 2021-04-11T16:22:31.000Z | 2021-04-11T16:22:31.000Z | #include <stdio.h>
#include <string.h>
#include <algorithm>
using namespace std;
const int MAXN = 256;
long long dp[MAXN][MAXN];
char s[MAXN];
long long dfs(int l, int r) {
if (l == r) return 1;
if (dp[l][r] != -1) return dp[l][r];
long long &ret = dp[l][r];
ret = 0;
int left = 0, o1 = 0, o2 = 0;
for (int i = l; i <= r; i++) {
if (s[i] == '(')
left++;
else if (s[i] == ')')
left--;
else {
if (left == 0) {
if (s[i] == '+')
o1 = 1;
if (s[i] == '*')
o2 = 1;
}
}
}
if (o1 == 0 && o2 == 0)
ret += dfs(l+1, r-1);
for (int i = l; i <= r; i++) {
if (s[i] == '(')
left++;
else if (s[i] == ')')
left--;
else {
if (left == 0) {
if (s[i] == '+')
ret += dfs(l, i-1) * dfs(i+1, r);
if (s[i] == '*' && o1 == 0)
ret += dfs(l, i-1) * dfs(i+1, r);
}
}
}
return ret;
}
int main() {
while (gets(s)) {
memset(dp, -1, sizeof(dp));
long long v = dfs(0, strlen(s) - 1);
printf("%lld\n", v);
}
return 0;
}
| 17.785714 | 38 | 0.422691 |
5072d895de952d882d7d0940f0497c0c83e79859 | 17,031 | cc | C++ | lib/matrices/wimax_864_0_66B.cc | iamviji/wimax_ldpc_lib | e07f102eb9eefb5c906345ec024aa08f7db871e9 | [
"MIT"
] | 8 | 2018-10-29T14:56:05.000Z | 2022-02-10T09:42:21.000Z | lib/matrices/wimax_864_0_66B.cc | iamviji/wimax_ldpc_lib | e07f102eb9eefb5c906345ec024aa08f7db871e9 | [
"MIT"
] | null | null | null | lib/matrices/wimax_864_0_66B.cc | iamviji/wimax_ldpc_lib | e07f102eb9eefb5c906345ec024aa08f7db871e9 | [
"MIT"
] | 4 | 2018-10-16T20:12:56.000Z | 2020-10-19T07:37:05.000Z | #include "matrices.h"
#ifdef Z_36
unsigned int wimax_864_0_66B_D = 35;
unsigned int wimax_864_0_66B_X = 6;
int16_t wimax_864_0_66B[288][11] = {
{0, 79, 161, 234, 301, 390, 449, 509, 611, 612, -1},
{1, 80, 162, 235, 302, 391, 450, 510, 576, 613, -1},
{2, 81, 163, 236, 303, 392, 451, 511, 577, 614, -1},
{3, 82, 164, 237, 304, 393, 452, 512, 578, 615, -1},
{4, 83, 165, 238, 305, 394, 453, 513, 579, 616, -1},
{5, 84, 166, 239, 306, 395, 454, 514, 580, 617, -1},
{6, 85, 167, 240, 307, 360, 455, 515, 581, 618, -1},
{7, 86, 168, 241, 308, 361, 456, 516, 582, 619, -1},
{8, 87, 169, 242, 309, 362, 457, 517, 583, 620, -1},
{9, 88, 170, 243, 310, 363, 458, 518, 584, 621, -1},
{10, 89, 171, 244, 311, 364, 459, 519, 585, 622, -1},
{11, 90, 172, 245, 312, 365, 460, 520, 586, 623, -1},
{12, 91, 173, 246, 313, 366, 461, 521, 587, 624, -1},
{13, 92, 174, 247, 314, 367, 462, 522, 588, 625, -1},
{14, 93, 175, 248, 315, 368, 463, 523, 589, 626, -1},
{15, 94, 176, 249, 316, 369, 464, 524, 590, 627, -1},
{16, 95, 177, 250, 317, 370, 465, 525, 591, 628, -1},
{17, 96, 178, 251, 318, 371, 466, 526, 592, 629, -1},
{18, 97, 179, 216, 319, 372, 467, 527, 593, 630, -1},
{19, 98, 144, 217, 320, 373, 432, 528, 594, 631, -1},
{20, 99, 145, 218, 321, 374, 433, 529, 595, 632, -1},
{21, 100, 146, 219, 322, 375, 434, 530, 596, 633, -1},
{22, 101, 147, 220, 323, 376, 435, 531, 597, 634, -1},
{23, 102, 148, 221, 288, 377, 436, 532, 598, 635, -1},
{24, 103, 149, 222, 289, 378, 437, 533, 599, 636, -1},
{25, 104, 150, 223, 290, 379, 438, 534, 600, 637, -1},
{26, 105, 151, 224, 291, 380, 439, 535, 601, 638, -1},
{27, 106, 152, 225, 292, 381, 440, 536, 602, 639, -1},
{28, 107, 153, 226, 293, 382, 441, 537, 603, 640, -1},
{29, 72, 154, 227, 294, 383, 442, 538, 604, 641, -1},
{30, 73, 155, 228, 295, 384, 443, 539, 605, 642, -1},
{31, 74, 156, 229, 296, 385, 444, 504, 606, 643, -1},
{32, 75, 157, 230, 297, 386, 445, 505, 607, 644, -1},
{33, 76, 158, 231, 298, 387, 446, 506, 608, 645, -1},
{34, 77, 159, 232, 299, 388, 447, 507, 609, 646, -1},
{35, 78, 160, 233, 300, 389, 448, 508, 610, 647, -1},
{61, 141, 192, 253, 330, 409, 483, 558, 612, 648, -1},
{62, 142, 193, 254, 331, 410, 484, 559, 613, 649, -1},
{63, 143, 194, 255, 332, 411, 485, 560, 614, 650, -1},
{64, 108, 195, 256, 333, 412, 486, 561, 615, 651, -1},
{65, 109, 196, 257, 334, 413, 487, 562, 616, 652, -1},
{66, 110, 197, 258, 335, 414, 488, 563, 617, 653, -1},
{67, 111, 198, 259, 336, 415, 489, 564, 618, 654, -1},
{68, 112, 199, 260, 337, 416, 490, 565, 619, 655, -1},
{69, 113, 200, 261, 338, 417, 491, 566, 620, 656, -1},
{70, 114, 201, 262, 339, 418, 492, 567, 621, 657, -1},
{71, 115, 202, 263, 340, 419, 493, 568, 622, 658, -1},
{36, 116, 203, 264, 341, 420, 494, 569, 623, 659, -1},
{37, 117, 204, 265, 342, 421, 495, 570, 624, 660, -1},
{38, 118, 205, 266, 343, 422, 496, 571, 625, 661, -1},
{39, 119, 206, 267, 344, 423, 497, 572, 626, 662, -1},
{40, 120, 207, 268, 345, 424, 498, 573, 627, 663, -1},
{41, 121, 208, 269, 346, 425, 499, 574, 628, 664, -1},
{42, 122, 209, 270, 347, 426, 500, 575, 629, 665, -1},
{43, 123, 210, 271, 348, 427, 501, 540, 630, 666, -1},
{44, 124, 211, 272, 349, 428, 502, 541, 631, 667, -1},
{45, 125, 212, 273, 350, 429, 503, 542, 632, 668, -1},
{46, 126, 213, 274, 351, 430, 468, 543, 633, 669, -1},
{47, 127, 214, 275, 352, 431, 469, 544, 634, 670, -1},
{48, 128, 215, 276, 353, 396, 470, 545, 635, 671, -1},
{49, 129, 180, 277, 354, 397, 471, 546, 636, 672, -1},
{50, 130, 181, 278, 355, 398, 472, 547, 637, 673, -1},
{51, 131, 182, 279, 356, 399, 473, 548, 638, 674, -1},
{52, 132, 183, 280, 357, 400, 474, 549, 639, 675, -1},
{53, 133, 184, 281, 358, 401, 475, 550, 640, 676, -1},
{54, 134, 185, 282, 359, 402, 476, 551, 641, 677, -1},
{55, 135, 186, 283, 324, 403, 477, 552, 642, 678, -1},
{56, 136, 187, 284, 325, 404, 478, 553, 643, 679, -1},
{57, 137, 188, 285, 326, 405, 479, 554, 644, 680, -1},
{58, 138, 189, 286, 327, 406, 480, 555, 645, 681, -1},
{59, 139, 190, 287, 328, 407, 481, 556, 646, 682, -1},
{60, 140, 191, 252, 329, 408, 482, 557, 647, 683, -1},
{3, 104, 167, 226, 319, 366, 444, 531, 648, 684, -1},
{4, 105, 168, 227, 320, 367, 445, 532, 649, 685, -1},
{5, 106, 169, 228, 321, 368, 446, 533, 650, 686, -1},
{6, 107, 170, 229, 322, 369, 447, 534, 651, 687, -1},
{7, 72, 171, 230, 323, 370, 448, 535, 652, 688, -1},
{8, 73, 172, 231, 288, 371, 449, 536, 653, 689, -1},
{9, 74, 173, 232, 289, 372, 450, 537, 654, 690, -1},
{10, 75, 174, 233, 290, 373, 451, 538, 655, 691, -1},
{11, 76, 175, 234, 291, 374, 452, 539, 656, 692, -1},
{12, 77, 176, 235, 292, 375, 453, 504, 657, 693, -1},
{13, 78, 177, 236, 293, 376, 454, 505, 658, 694, -1},
{14, 79, 178, 237, 294, 377, 455, 506, 659, 695, -1},
{15, 80, 179, 238, 295, 378, 456, 507, 660, 696, -1},
{16, 81, 144, 239, 296, 379, 457, 508, 661, 697, -1},
{17, 82, 145, 240, 297, 380, 458, 509, 662, 698, -1},
{18, 83, 146, 241, 298, 381, 459, 510, 663, 699, -1},
{19, 84, 147, 242, 299, 382, 460, 511, 664, 700, -1},
{20, 85, 148, 243, 300, 383, 461, 512, 665, 701, -1},
{21, 86, 149, 244, 301, 384, 462, 513, 666, 702, -1},
{22, 87, 150, 245, 302, 385, 463, 514, 667, 703, -1},
{23, 88, 151, 246, 303, 386, 464, 515, 668, 704, -1},
{24, 89, 152, 247, 304, 387, 465, 516, 669, 705, -1},
{25, 90, 153, 248, 305, 388, 466, 517, 670, 706, -1},
{26, 91, 154, 249, 306, 389, 467, 518, 671, 707, -1},
{27, 92, 155, 250, 307, 390, 432, 519, 672, 708, -1},
{28, 93, 156, 251, 308, 391, 433, 520, 673, 709, -1},
{29, 94, 157, 216, 309, 392, 434, 521, 674, 710, -1},
{30, 95, 158, 217, 310, 393, 435, 522, 675, 711, -1},
{31, 96, 159, 218, 311, 394, 436, 523, 676, 712, -1},
{32, 97, 160, 219, 312, 395, 437, 524, 677, 713, -1},
{33, 98, 161, 220, 313, 360, 438, 525, 678, 714, -1},
{34, 99, 162, 221, 314, 361, 439, 526, 679, 715, -1},
{35, 100, 163, 222, 315, 362, 440, 527, 680, 716, -1},
{0, 101, 164, 223, 316, 363, 441, 528, 681, 717, -1},
{1, 102, 165, 224, 317, 364, 442, 529, 682, 718, -1},
{2, 103, 166, 225, 318, 365, 443, 530, 683, 719, -1},
{46, 120, 210, 262, 357, 397, 489, 553, 684, 720, -1},
{47, 121, 211, 263, 358, 398, 490, 554, 685, 721, -1},
{48, 122, 212, 264, 359, 399, 491, 555, 686, 722, -1},
{49, 123, 213, 265, 324, 400, 492, 556, 687, 723, -1},
{50, 124, 214, 266, 325, 401, 493, 557, 688, 724, -1},
{51, 125, 215, 267, 326, 402, 494, 558, 689, 725, -1},
{52, 126, 180, 268, 327, 403, 495, 559, 690, 726, -1},
{53, 127, 181, 269, 328, 404, 496, 560, 691, 727, -1},
{54, 128, 182, 270, 329, 405, 497, 561, 692, 728, -1},
{55, 129, 183, 271, 330, 406, 498, 562, 693, 729, -1},
{56, 130, 184, 272, 331, 407, 499, 563, 694, 730, -1},
{57, 131, 185, 273, 332, 408, 500, 564, 695, 731, -1},
{58, 132, 186, 274, 333, 409, 501, 565, 696, 732, -1},
{59, 133, 187, 275, 334, 410, 502, 566, 697, 733, -1},
{60, 134, 188, 276, 335, 411, 503, 567, 698, 734, -1},
{61, 135, 189, 277, 336, 412, 468, 568, 699, 735, -1},
{62, 136, 190, 278, 337, 413, 469, 569, 700, 736, -1},
{63, 137, 191, 279, 338, 414, 470, 570, 701, 737, -1},
{64, 138, 192, 280, 339, 415, 471, 571, 702, 738, -1},
{65, 139, 193, 281, 340, 416, 472, 572, 703, 739, -1},
{66, 140, 194, 282, 341, 417, 473, 573, 704, 740, -1},
{67, 141, 195, 283, 342, 418, 474, 574, 705, 741, -1},
{68, 142, 196, 284, 343, 419, 475, 575, 706, 742, -1},
{69, 143, 197, 285, 344, 420, 476, 540, 707, 743, -1},
{70, 108, 198, 286, 345, 421, 477, 541, 708, 744, -1},
{71, 109, 199, 287, 346, 422, 478, 542, 709, 745, -1},
{36, 110, 200, 252, 347, 423, 479, 543, 710, 746, -1},
{37, 111, 201, 253, 348, 424, 480, 544, 711, 747, -1},
{38, 112, 202, 254, 349, 425, 481, 545, 712, 748, -1},
{39, 113, 203, 255, 350, 426, 482, 546, 713, 749, -1},
{40, 114, 204, 256, 351, 427, 483, 547, 714, 750, -1},
{41, 115, 205, 257, 352, 428, 484, 548, 715, 751, -1},
{42, 116, 206, 258, 353, 429, 485, 549, 716, 752, -1},
{43, 117, 207, 259, 354, 430, 486, 550, 717, 753, -1},
{44, 118, 208, 260, 355, 431, 487, 551, 718, 754, -1},
{45, 119, 209, 261, 356, 396, 488, 552, 719, 755, -1},
{8, 82, 149, 227, 312, 369, 450, 527, 720, 756, -1},
{9, 83, 150, 228, 313, 370, 451, 528, 721, 757, -1},
{10, 84, 151, 229, 314, 371, 452, 529, 722, 758, -1},
{11, 85, 152, 230, 315, 372, 453, 530, 723, 759, -1},
{12, 86, 153, 231, 316, 373, 454, 531, 724, 760, -1},
{13, 87, 154, 232, 317, 374, 455, 532, 725, 761, -1},
{14, 88, 155, 233, 318, 375, 456, 533, 726, 762, -1},
{15, 89, 156, 234, 319, 376, 457, 534, 727, 763, -1},
{16, 90, 157, 235, 320, 377, 458, 535, 728, 764, -1},
{17, 91, 158, 236, 321, 378, 459, 536, 729, 765, -1},
{18, 92, 159, 237, 322, 379, 460, 537, 730, 766, -1},
{19, 93, 160, 238, 323, 380, 461, 538, 731, 767, -1},
{20, 94, 161, 239, 288, 381, 462, 539, 732, 768, -1},
{21, 95, 162, 240, 289, 382, 463, 504, 733, 769, -1},
{22, 96, 163, 241, 290, 383, 464, 505, 734, 770, -1},
{23, 97, 164, 242, 291, 384, 465, 506, 735, 771, -1},
{24, 98, 165, 243, 292, 385, 466, 507, 736, 772, -1},
{25, 99, 166, 244, 293, 386, 467, 508, 737, 773, -1},
{26, 100, 167, 245, 294, 387, 432, 509, 738, 774, -1},
{27, 101, 168, 246, 295, 388, 433, 510, 739, 775, -1},
{28, 102, 169, 247, 296, 389, 434, 511, 740, 776, -1},
{29, 103, 170, 248, 297, 390, 435, 512, 741, 777, -1},
{30, 104, 171, 249, 298, 391, 436, 513, 742, 778, -1},
{31, 105, 172, 250, 299, 392, 437, 514, 743, 779, -1},
{32, 106, 173, 251, 300, 393, 438, 515, 744, 780, -1},
{33, 107, 174, 216, 301, 394, 439, 516, 745, 781, -1},
{34, 72, 175, 217, 302, 395, 440, 517, 746, 782, -1},
{35, 73, 176, 218, 303, 360, 441, 518, 747, 783, -1},
{0, 74, 177, 219, 304, 361, 442, 519, 748, 784, -1},
{1, 75, 178, 220, 305, 362, 443, 520, 749, 785, -1},
{2, 76, 179, 221, 306, 363, 444, 521, 750, 786, -1},
{3, 77, 144, 222, 307, 364, 445, 522, 751, 787, -1},
{4, 78, 145, 223, 308, 365, 446, 523, 752, 788, -1},
{5, 79, 146, 224, 309, 366, 447, 524, 753, 789, -1},
{6, 80, 147, 225, 310, 367, 448, 525, 754, 790, -1},
{7, 81, 148, 226, 311, 368, 449, 526, 755, 791, -1},
{47, 132, 200, 257, 324, 407, 495, 540, 756, 792, -1},
{48, 133, 201, 258, 325, 408, 496, 541, 757, 793, -1},
{49, 134, 202, 259, 326, 409, 497, 542, 758, 794, -1},
{50, 135, 203, 260, 327, 410, 498, 543, 759, 795, -1},
{51, 136, 204, 261, 328, 411, 499, 544, 760, 796, -1},
{52, 137, 205, 262, 329, 412, 500, 545, 761, 797, -1},
{53, 138, 206, 263, 330, 413, 501, 546, 762, 798, -1},
{54, 139, 207, 264, 331, 414, 502, 547, 763, 799, -1},
{55, 140, 208, 265, 332, 415, 503, 548, 764, 800, -1},
{56, 141, 209, 266, 333, 416, 468, 549, 765, 801, -1},
{57, 142, 210, 267, 334, 417, 469, 550, 766, 802, -1},
{58, 143, 211, 268, 335, 418, 470, 551, 767, 803, -1},
{59, 108, 212, 269, 336, 419, 471, 552, 768, 804, -1},
{60, 109, 213, 270, 337, 420, 472, 553, 769, 805, -1},
{61, 110, 214, 271, 338, 421, 473, 554, 770, 806, -1},
{62, 111, 215, 272, 339, 422, 474, 555, 771, 807, -1},
{63, 112, 180, 273, 340, 423, 475, 556, 772, 808, -1},
{64, 113, 181, 274, 341, 424, 476, 557, 773, 809, -1},
{65, 114, 182, 275, 342, 425, 477, 558, 774, 810, -1},
{66, 115, 183, 276, 343, 426, 478, 559, 775, 811, -1},
{67, 116, 184, 277, 344, 427, 479, 560, 776, 812, -1},
{68, 117, 185, 278, 345, 428, 480, 561, 777, 813, -1},
{69, 118, 186, 279, 346, 429, 481, 562, 778, 814, -1},
{70, 119, 187, 280, 347, 430, 482, 563, 779, 815, -1},
{71, 120, 188, 281, 348, 431, 483, 564, 780, 816, -1},
{36, 121, 189, 282, 349, 396, 484, 565, 781, 817, -1},
{37, 122, 190, 283, 350, 397, 485, 566, 782, 818, -1},
{38, 123, 191, 284, 351, 398, 486, 567, 783, 819, -1},
{39, 124, 192, 285, 352, 399, 487, 568, 784, 820, -1},
{40, 125, 193, 286, 353, 400, 488, 569, 785, 821, -1},
{41, 126, 194, 287, 354, 401, 489, 570, 786, 822, -1},
{42, 127, 195, 252, 355, 402, 490, 571, 787, 823, -1},
{43, 128, 196, 253, 356, 403, 491, 572, 788, 824, -1},
{44, 129, 197, 254, 357, 404, 492, 573, 789, 825, -1},
{45, 130, 198, 255, 358, 405, 493, 574, 790, 826, -1},
{46, 131, 199, 256, 359, 406, 494, 575, 791, 827, -1},
{12, 72, 149, 237, 319, 361, 434, 523, 576, 792, 828},
{13, 73, 150, 238, 320, 362, 435, 524, 577, 793, 829},
{14, 74, 151, 239, 321, 363, 436, 525, 578, 794, 830},
{15, 75, 152, 240, 322, 364, 437, 526, 579, 795, 831},
{16, 76, 153, 241, 323, 365, 438, 527, 580, 796, 832},
{17, 77, 154, 242, 288, 366, 439, 528, 581, 797, 833},
{18, 78, 155, 243, 289, 367, 440, 529, 582, 798, 834},
{19, 79, 156, 244, 290, 368, 441, 530, 583, 799, 835},
{20, 80, 157, 245, 291, 369, 442, 531, 584, 800, 836},
{21, 81, 158, 246, 292, 370, 443, 532, 585, 801, 837},
{22, 82, 159, 247, 293, 371, 444, 533, 586, 802, 838},
{23, 83, 160, 248, 294, 372, 445, 534, 587, 803, 839},
{24, 84, 161, 249, 295, 373, 446, 535, 588, 804, 840},
{25, 85, 162, 250, 296, 374, 447, 536, 589, 805, 841},
{26, 86, 163, 251, 297, 375, 448, 537, 590, 806, 842},
{27, 87, 164, 216, 298, 376, 449, 538, 591, 807, 843},
{28, 88, 165, 217, 299, 377, 450, 539, 592, 808, 844},
{29, 89, 166, 218, 300, 378, 451, 504, 593, 809, 845},
{30, 90, 167, 219, 301, 379, 452, 505, 594, 810, 846},
{31, 91, 168, 220, 302, 380, 453, 506, 595, 811, 847},
{32, 92, 169, 221, 303, 381, 454, 507, 596, 812, 848},
{33, 93, 170, 222, 304, 382, 455, 508, 597, 813, 849},
{34, 94, 171, 223, 305, 383, 456, 509, 598, 814, 850},
{35, 95, 172, 224, 306, 384, 457, 510, 599, 815, 851},
{0, 96, 173, 225, 307, 385, 458, 511, 600, 816, 852},
{1, 97, 174, 226, 308, 386, 459, 512, 601, 817, 853},
{2, 98, 175, 227, 309, 387, 460, 513, 602, 818, 854},
{3, 99, 176, 228, 310, 388, 461, 514, 603, 819, 855},
{4, 100, 177, 229, 311, 389, 462, 515, 604, 820, 856},
{5, 101, 178, 230, 312, 390, 463, 516, 605, 821, 857},
{6, 102, 179, 231, 313, 391, 464, 517, 606, 822, 858},
{7, 103, 144, 232, 314, 392, 465, 518, 607, 823, 859},
{8, 104, 145, 233, 315, 393, 466, 519, 608, 824, 860},
{9, 105, 146, 234, 316, 394, 467, 520, 609, 825, 861},
{10, 106, 147, 235, 317, 395, 432, 521, 610, 826, 862},
{11, 107, 148, 236, 318, 360, 433, 522, 611, 827, 863},
{36, 125, 184, 274, 355, 416, 497, 555, 611, 828, -1},
{37, 126, 185, 275, 356, 417, 498, 556, 576, 829, -1},
{38, 127, 186, 276, 357, 418, 499, 557, 577, 830, -1},
{39, 128, 187, 277, 358, 419, 500, 558, 578, 831, -1},
{40, 129, 188, 278, 359, 420, 501, 559, 579, 832, -1},
{41, 130, 189, 279, 324, 421, 502, 560, 580, 833, -1},
{42, 131, 190, 280, 325, 422, 503, 561, 581, 834, -1},
{43, 132, 191, 281, 326, 423, 468, 562, 582, 835, -1},
{44, 133, 192, 282, 327, 424, 469, 563, 583, 836, -1},
{45, 134, 193, 283, 328, 425, 470, 564, 584, 837, -1},
{46, 135, 194, 284, 329, 426, 471, 565, 585, 838, -1},
{47, 136, 195, 285, 330, 427, 472, 566, 586, 839, -1},
{48, 137, 196, 286, 331, 428, 473, 567, 587, 840, -1},
{49, 138, 197, 287, 332, 429, 474, 568, 588, 841, -1},
{50, 139, 198, 252, 333, 430, 475, 569, 589, 842, -1},
{51, 140, 199, 253, 334, 431, 476, 570, 590, 843, -1},
{52, 141, 200, 254, 335, 396, 477, 571, 591, 844, -1},
{53, 142, 201, 255, 336, 397, 478, 572, 592, 845, -1},
{54, 143, 202, 256, 337, 398, 479, 573, 593, 846, -1},
{55, 108, 203, 257, 338, 399, 480, 574, 594, 847, -1},
{56, 109, 204, 258, 339, 400, 481, 575, 595, 848, -1},
{57, 110, 205, 259, 340, 401, 482, 540, 596, 849, -1},
{58, 111, 206, 260, 341, 402, 483, 541, 597, 850, -1},
{59, 112, 207, 261, 342, 403, 484, 542, 598, 851, -1},
{60, 113, 208, 262, 343, 404, 485, 543, 599, 852, -1},
{61, 114, 209, 263, 344, 405, 486, 544, 600, 853, -1},
{62, 115, 210, 264, 345, 406, 487, 545, 601, 854, -1},
{63, 116, 211, 265, 346, 407, 488, 546, 602, 855, -1},
{64, 117, 212, 266, 347, 408, 489, 547, 603, 856, -1},
{65, 118, 213, 267, 348, 409, 490, 548, 604, 857, -1},
{66, 119, 214, 268, 349, 410, 491, 549, 605, 858, -1},
{67, 120, 215, 269, 350, 411, 492, 550, 606, 859, -1},
{68, 121, 180, 270, 351, 412, 493, 551, 607, 860, -1},
{69, 122, 181, 271, 352, 413, 494, 552, 608, 861, -1},
{70, 123, 182, 272, 353, 414, 495, 553, 609, 862, -1},
{71, 124, 183, 273, 354, 415, 496, 554, 610, 863, -1}
};
#endif | 57.151007 | 59 | 0.509424 |
5074b492e1d6cad9623d045c0e74c142a9cf7662 | 299 | cpp | C++ | c2017/wd/wd186/main.cpp | wmjtxt/c-exercise | d22336460cab825dd7ae98297bbe46febedfcece | [
"MIT"
] | null | null | null | c2017/wd/wd186/main.cpp | wmjtxt/c-exercise | d22336460cab825dd7ae98297bbe46febedfcece | [
"MIT"
] | null | null | null | c2017/wd/wd186/main.cpp | wmjtxt/c-exercise | d22336460cab825dd7ae98297bbe46febedfcece | [
"MIT"
] | null | null | null | #include <iostream>
#include <stdio.h>
using namespace std;
int main()
{
char a[100], b[100];
gets(a);
gets(b);
int lena = -1, i = 0;
while(a[++lena] != '\0');
while(b[i] != '\0'){
a[lena++] = b[i++];
}
a[lena] = '\0';
cout << a << endl;
return 0;
}
| 15.736842 | 29 | 0.441472 |
5077ad214c26a83540c8a9dd7d899a649af72049 | 18,125 | cxx | C++ | main/stoc/source/proxy_factory/proxyfac.cxx | Grosskopf/openoffice | 93df6e8a695d5e3eac16f3ad5e9ade1b963ab8d7 | [
"Apache-2.0"
] | 679 | 2015-01-06T06:34:58.000Z | 2022-03-30T01:06:03.000Z | main/stoc/source/proxy_factory/proxyfac.cxx | Grosskopf/openoffice | 93df6e8a695d5e3eac16f3ad5e9ade1b963ab8d7 | [
"Apache-2.0"
] | 102 | 2017-11-07T08:51:31.000Z | 2022-03-17T12:13:49.000Z | main/stoc/source/proxy_factory/proxyfac.cxx | Grosskopf/openoffice | 93df6e8a695d5e3eac16f3ad5e9ade1b963ab8d7 | [
"Apache-2.0"
] | 331 | 2015-01-06T11:40:55.000Z | 2022-03-14T04:07:51.000Z | /**************************************************************
*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*
*************************************************************/
// MARKER(update_precomp.py): autogen include statement, do not remove
#include "precompiled_stoc.hxx"
#include "osl/diagnose.h"
#include "osl/interlck.h"
#include "osl/doublecheckedlocking.h"
#include "osl/mutex.hxx"
#include "rtl/ref.hxx"
#include "uno/dispatcher.hxx"
#include "uno/data.h"
#include "uno/mapping.hxx"
#include "uno/environment.hxx"
#include "typelib/typedescription.hxx"
#include "cppuhelper/exc_hlp.hxx"
#include "cppuhelper/implbase2.hxx"
#include "cppuhelper/implementationentry.hxx"
#include "cppuhelper/factory.hxx"
#include "com/sun/star/lang/XServiceInfo.hpp"
#include "com/sun/star/registry/XRegistryKey.hpp"
#include "com/sun/star/reflection/XProxyFactory.hpp"
#include "com/sun/star/uno/RuntimeException.hpp"
#define OUSTR(x) ::rtl::OUString( RTL_CONSTASCII_USTRINGPARAM(x) )
#define SERVICE_NAME "com.sun.star.reflection.ProxyFactory"
#define IMPL_NAME "com.sun.star.comp.reflection.ProxyFactory"
using namespace ::com::sun::star;
using namespace ::com::sun::star::uno;
using ::rtl::OUString;
namespace
{
static rtl_StandardModuleCount g_moduleCount = MODULE_COUNT_INIT;
static OUString proxyfac_getImplementationName()
{
return OUSTR(IMPL_NAME);
}
static Sequence< OUString > proxyfac_getSupportedServiceNames()
{
OUString str_name = OUSTR(SERVICE_NAME);
return Sequence< OUString >( &str_name, 1 );
}
//==============================================================================
struct FactoryImpl : public ::cppu::WeakImplHelper2< lang::XServiceInfo,
reflection::XProxyFactory >
{
Environment m_uno_env;
Environment m_cpp_env;
Mapping m_uno2cpp;
Mapping m_cpp2uno;
UnoInterfaceReference binuno_queryInterface(
UnoInterfaceReference const & unoI,
typelib_InterfaceTypeDescription * pTypeDescr );
FactoryImpl();
virtual ~FactoryImpl();
// XServiceInfo
virtual OUString SAL_CALL getImplementationName()
throw (RuntimeException);
virtual sal_Bool SAL_CALL supportsService( const OUString & rServiceName )
throw (RuntimeException);
virtual Sequence< OUString > SAL_CALL getSupportedServiceNames()
throw (RuntimeException);
// XProxyFactory
virtual Reference< XAggregation > SAL_CALL createProxy(
Reference< XInterface > const & xTarget )
throw (RuntimeException);
};
//______________________________________________________________________________
UnoInterfaceReference FactoryImpl::binuno_queryInterface(
UnoInterfaceReference const & unoI,
typelib_InterfaceTypeDescription * pTypeDescr )
{
// init queryInterface() td
static typelib_TypeDescription * s_pQITD = 0;
if (s_pQITD == 0)
{
::osl::MutexGuard aGuard( ::osl::Mutex::getGlobalMutex() );
if (s_pQITD == 0)
{
typelib_TypeDescription * pTXInterfaceDescr = 0;
TYPELIB_DANGER_GET(
&pTXInterfaceDescr,
::getCppuType( reinterpret_cast< Reference< XInterface >
const * >(0) ).getTypeLibType() );
typelib_TypeDescription * pQITD = 0;
typelib_typedescriptionreference_getDescription(
&pQITD, reinterpret_cast< typelib_InterfaceTypeDescription * >(
pTXInterfaceDescr )->ppAllMembers[ 0 ] );
TYPELIB_DANGER_RELEASE( pTXInterfaceDescr );
OSL_DOUBLE_CHECKED_LOCKING_MEMORY_BARRIER();
s_pQITD = pQITD;
}
}
else
{
OSL_DOUBLE_CHECKED_LOCKING_MEMORY_BARRIER();
}
void * args[ 1 ];
args[ 0 ] = &reinterpret_cast< typelib_TypeDescription * >(
pTypeDescr )->pWeakRef;
uno_Any ret_val, exc_space;
uno_Any * exc = &exc_space;
unoI.dispatch( s_pQITD, &ret_val, args, &exc );
if (exc == 0)
{
UnoInterfaceReference ret;
if (ret_val.pType->eTypeClass == typelib_TypeClass_INTERFACE)
{
ret.set( *reinterpret_cast< uno_Interface ** >(ret_val.pData),
SAL_NO_ACQUIRE );
typelib_typedescriptionreference_release( ret_val.pType );
}
else
{
uno_any_destruct( &ret_val, 0 );
}
return ret;
}
else
{
// exception occurred:
OSL_ENSURE(
typelib_typedescriptionreference_isAssignableFrom(
::getCppuType( reinterpret_cast<
RuntimeException const * >(0) ).getTypeLibType(),
exc->pType ),
"### RuntimeException expected!" );
Any cpp_exc;
uno_type_copyAndConvertData(
&cpp_exc, exc, ::getCppuType( &cpp_exc ).getTypeLibType(),
m_uno2cpp.get() );
uno_any_destruct( exc, 0 );
::cppu::throwException( cpp_exc );
OSL_ASSERT( 0 ); // way of no return
return UnoInterfaceReference(); // for dummy
}
}
//==============================================================================
struct ProxyRoot : public ::cppu::OWeakAggObject
{
// XAggregation
virtual Any SAL_CALL queryAggregation( Type const & rType )
throw (RuntimeException);
virtual ~ProxyRoot();
inline ProxyRoot( ::rtl::Reference< FactoryImpl > const & factory,
Reference< XInterface > const & xTarget );
::rtl::Reference< FactoryImpl > m_factory;
private:
UnoInterfaceReference m_target;
};
//==============================================================================
struct binuno_Proxy : public uno_Interface
{
oslInterlockedCount m_nRefCount;
::rtl::Reference< ProxyRoot > m_root;
UnoInterfaceReference m_target;
OUString m_oid;
TypeDescription m_typeDescr;
inline binuno_Proxy(
::rtl::Reference< ProxyRoot > const & root,
UnoInterfaceReference const & target,
OUString const & oid, TypeDescription const & typeDescr );
};
extern "C"
{
//------------------------------------------------------------------------------
static void SAL_CALL binuno_proxy_free(
uno_ExtEnvironment * pEnv, void * pProxy )
{
(void) pEnv; // avoid warning about unused parameter
binuno_Proxy * proxy = static_cast< binuno_Proxy * >(
reinterpret_cast< uno_Interface * >( pProxy ) );
OSL_ASSERT( proxy->m_root->m_factory->m_uno_env.get()->pExtEnv == pEnv );
delete proxy;
}
//------------------------------------------------------------------------------
static void SAL_CALL binuno_proxy_acquire( uno_Interface * pUnoI )
{
binuno_Proxy * that = static_cast< binuno_Proxy * >( pUnoI );
if (osl_incrementInterlockedCount( &that->m_nRefCount ) == 1)
{
// rebirth of zombie
uno_ExtEnvironment * uno_env =
that->m_root->m_factory->m_uno_env.get()->pExtEnv;
OSL_ASSERT( uno_env != 0 );
(*uno_env->registerProxyInterface)(
uno_env, reinterpret_cast< void ** >( &pUnoI ), binuno_proxy_free,
that->m_oid.pData,
reinterpret_cast< typelib_InterfaceTypeDescription * >(
that->m_typeDescr.get() ) );
OSL_ASSERT( that == static_cast< binuno_Proxy * >( pUnoI ) );
}
}
//------------------------------------------------------------------------------
static void SAL_CALL binuno_proxy_release( uno_Interface * pUnoI )
{
binuno_Proxy * that = static_cast< binuno_Proxy * >( pUnoI );
if (osl_decrementInterlockedCount( &that->m_nRefCount ) == 0)
{
uno_ExtEnvironment * uno_env =
that->m_root->m_factory->m_uno_env.get()->pExtEnv;
OSL_ASSERT( uno_env != 0 );
(*uno_env->revokeInterface)( uno_env, pUnoI );
}
}
//------------------------------------------------------------------------------
static void SAL_CALL binuno_proxy_dispatch(
uno_Interface * pUnoI, const typelib_TypeDescription * pMemberType,
void * pReturn, void * pArgs [], uno_Any ** ppException )
{
binuno_Proxy * that = static_cast< binuno_Proxy * >( pUnoI );
switch (reinterpret_cast< typelib_InterfaceMemberTypeDescription const * >(
pMemberType )->nPosition)
{
case 0: // queryInterface()
{
try
{
Type const & rType =
*reinterpret_cast< Type const * >( pArgs[ 0 ] );
Any ret( that->m_root->queryInterface( rType ) );
uno_type_copyAndConvertData(
pReturn, &ret, ::getCppuType( &ret ).getTypeLibType(),
that->m_root->m_factory->m_cpp2uno.get() );
*ppException = 0; // no exc
}
catch (RuntimeException &)
{
Any exc( ::cppu::getCaughtException() );
uno_type_any_constructAndConvert(
*ppException, const_cast< void * >(exc.getValue()),
exc.getValueTypeRef(),
that->m_root->m_factory->m_cpp2uno.get() );
}
break;
}
case 1: // acquire()
binuno_proxy_acquire( pUnoI );
*ppException = 0; // no exc
break;
case 2: // release()
binuno_proxy_release( pUnoI );
*ppException = 0; // no exc
break;
default:
that->m_target.dispatch( pMemberType, pReturn, pArgs, ppException );
break;
}
}
}
//______________________________________________________________________________
inline binuno_Proxy::binuno_Proxy(
::rtl::Reference< ProxyRoot > const & root,
UnoInterfaceReference const & target,
OUString const & oid, TypeDescription const & typeDescr )
: m_nRefCount( 1 ),
m_root( root ),
m_target( target ),
m_oid( oid ),
m_typeDescr( typeDescr )
{
uno_Interface::acquire = binuno_proxy_acquire;
uno_Interface::release = binuno_proxy_release;
uno_Interface::pDispatcher = binuno_proxy_dispatch;
}
//______________________________________________________________________________
ProxyRoot::~ProxyRoot()
{
}
//______________________________________________________________________________
inline ProxyRoot::ProxyRoot(
::rtl::Reference< FactoryImpl > const & factory,
Reference< XInterface > const & xTarget )
: m_factory( factory )
{
m_factory->m_cpp2uno.mapInterface(
reinterpret_cast< void ** >( &m_target.m_pUnoI ), xTarget.get(),
::getCppuType( &xTarget ) );
OSL_ENSURE( m_target.is(), "### mapping interface failed!" );
}
//______________________________________________________________________________
Any ProxyRoot::queryAggregation( Type const & rType )
throw (RuntimeException)
{
Any ret( OWeakAggObject::queryAggregation( rType ) );
if (! ret.hasValue())
{
typelib_TypeDescription * pTypeDescr = 0;
TYPELIB_DANGER_GET( &pTypeDescr, rType.getTypeLibType() );
try
{
Reference< XInterface > xProxy;
uno_ExtEnvironment * cpp_env = m_factory->m_cpp_env.get()->pExtEnv;
OSL_ASSERT( cpp_env != 0 );
// mind a new delegator, calculate current root:
Reference< XInterface > xRoot(
static_cast< OWeakObject * >(this), UNO_QUERY_THROW );
OUString oid;
(*cpp_env->getObjectIdentifier)( cpp_env, &oid.pData, xRoot.get() );
OSL_ASSERT( oid.getLength() > 0 );
(*cpp_env->getRegisteredInterface)(
cpp_env, reinterpret_cast< void ** >( &xProxy ),
oid.pData, reinterpret_cast<
typelib_InterfaceTypeDescription * >(pTypeDescr) );
if (! xProxy.is())
{
// perform query on target:
UnoInterfaceReference proxy_target(
m_factory->binuno_queryInterface(
m_target, reinterpret_cast<
typelib_InterfaceTypeDescription * >(pTypeDescr) ) );
if (proxy_target.is())
{
// ensure root's object entries:
UnoInterfaceReference root;
m_factory->m_cpp2uno.mapInterface(
reinterpret_cast< void ** >( &root.m_pUnoI ),
xRoot.get(), ::getCppuType( &xRoot ) );
UnoInterfaceReference proxy(
// ref count initially 1:
new binuno_Proxy( this, proxy_target, oid, pTypeDescr ),
SAL_NO_ACQUIRE );
uno_ExtEnvironment * uno_env =
m_factory->m_uno_env.get()->pExtEnv;
OSL_ASSERT( uno_env != 0 );
(*uno_env->registerProxyInterface)(
uno_env, reinterpret_cast< void ** >( &proxy.m_pUnoI ),
binuno_proxy_free, oid.pData,
reinterpret_cast< typelib_InterfaceTypeDescription * >(
pTypeDescr ) );
m_factory->m_uno2cpp.mapInterface(
reinterpret_cast< void ** >( &xProxy ),
proxy.get(), pTypeDescr );
}
}
if (xProxy.is())
ret.setValue( &xProxy, pTypeDescr );
}
catch (...) // finally
{
TYPELIB_DANGER_RELEASE( pTypeDescr );
throw;
}
TYPELIB_DANGER_RELEASE( pTypeDescr );
}
return ret;
}
//##############################################################################
//______________________________________________________________________________
FactoryImpl::FactoryImpl()
{
OUString uno = OUSTR(UNO_LB_UNO);
OUString cpp = OUSTR(CPPU_CURRENT_LANGUAGE_BINDING_NAME);
uno_getEnvironment(
reinterpret_cast< uno_Environment ** >( &m_uno_env ), uno.pData, 0 );
OSL_ENSURE( m_uno_env.is(), "### cannot get binary uno env!" );
uno_getEnvironment(
reinterpret_cast< uno_Environment ** >( &m_cpp_env ), cpp.pData, 0 );
OSL_ENSURE( m_cpp_env.is(), "### cannot get C++ uno env!" );
uno_getMapping(
reinterpret_cast< uno_Mapping ** >( &m_uno2cpp ),
m_uno_env.get(), m_cpp_env.get(), 0 );
OSL_ENSURE( m_uno2cpp.is(), "### cannot get bridge uno <-> C++!" );
uno_getMapping(
reinterpret_cast< uno_Mapping ** >( &m_cpp2uno ),
m_cpp_env.get(), m_uno_env.get(), 0 );
OSL_ENSURE( m_cpp2uno.is(), "### cannot get bridge C++ <-> uno!" );
g_moduleCount.modCnt.acquire( &g_moduleCount.modCnt );
}
//______________________________________________________________________________
FactoryImpl::~FactoryImpl()
{
g_moduleCount.modCnt.release( &g_moduleCount.modCnt );
}
// XProxyFactory
//______________________________________________________________________________
Reference< XAggregation > FactoryImpl::createProxy(
Reference< XInterface > const & xTarget )
throw (RuntimeException)
{
return new ProxyRoot( this, xTarget );
}
// XServiceInfo
//______________________________________________________________________________
OUString FactoryImpl::getImplementationName()
throw (RuntimeException)
{
return proxyfac_getImplementationName();;
}
//______________________________________________________________________________
sal_Bool FactoryImpl::supportsService( const OUString & rServiceName )
throw (RuntimeException)
{
Sequence< OUString > const & rSNL = getSupportedServiceNames();
OUString const * pArray = rSNL.getConstArray();
for ( sal_Int32 nPos = rSNL.getLength(); nPos--; )
{
if (rServiceName.equals( pArray[ nPos ] ))
return true;
}
return false;
}
//______________________________________________________________________________
Sequence< OUString > FactoryImpl::getSupportedServiceNames()
throw(::com::sun::star::uno::RuntimeException)
{
return proxyfac_getSupportedServiceNames();
}
//==============================================================================
static Reference< XInterface > SAL_CALL proxyfac_create(
Reference< XComponentContext > const & )
throw (Exception)
{
Reference< XInterface > xRet;
{
::osl::MutexGuard guard( ::osl::Mutex::getGlobalMutex() );
static WeakReference < XInterface > rwInstance;
xRet = rwInstance;
if (! xRet.is())
{
xRet = static_cast< ::cppu::OWeakObject * >(new FactoryImpl);
rwInstance = xRet;
}
}
return xRet;
}
static ::cppu::ImplementationEntry g_entries [] =
{
{
proxyfac_create, proxyfac_getImplementationName,
proxyfac_getSupportedServiceNames, ::cppu::createSingleComponentFactory,
&g_moduleCount.modCnt, 0
},
{ 0, 0, 0, 0, 0, 0 }
};
}
extern "C"
{
sal_Bool SAL_CALL component_canUnload( TimeValue * pTime )
{
return g_moduleCount.canUnload( &g_moduleCount, pTime );
}
void SAL_CALL component_getImplementationEnvironment(
const sal_Char ** ppEnvTypeName, uno_Environment ** )
{
*ppEnvTypeName = CPPU_CURRENT_LANGUAGE_BINDING_NAME;
}
void * SAL_CALL component_getFactory(
const sal_Char * pImplName, void * pServiceManager, void * pRegistryKey )
{
return ::cppu::component_getFactoryHelper(
pImplName, pServiceManager, pRegistryKey, g_entries );
}
}
| 33.941948 | 80 | 0.613517 |
507cdeacfef76c4f63da9a526dbb2de19e2ae25d | 5,139 | cpp | C++ | src/vulkan/vulkan-upload.cpp | Impulse21/nvrhi | f272a6595dd0768a8e3419f0075f0edf40d00391 | [
"MIT"
] | 2 | 2021-08-28T23:02:30.000Z | 2021-08-28T23:26:21.000Z | src/vulkan/vulkan-upload.cpp | Impulse21/nvrhi | f272a6595dd0768a8e3419f0075f0edf40d00391 | [
"MIT"
] | null | null | null | src/vulkan/vulkan-upload.cpp | Impulse21/nvrhi | f272a6595dd0768a8e3419f0075f0edf40d00391 | [
"MIT"
] | null | null | null | /*
* Copyright (c) 2014-2021, NVIDIA CORPORATION. All rights reserved.
*
* 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 "vulkan-backend.h"
#include <nvrhi/common/misc.h>
namespace nvrhi::vulkan
{
std::shared_ptr<BufferChunk> UploadManager::CreateChunk(uint64_t size)
{
std::shared_ptr<BufferChunk> chunk = std::make_shared<BufferChunk>();
if (m_IsScratchBuffer)
{
BufferDesc desc;
desc.byteSize = size;
desc.cpuAccess = CpuAccessMode::None;
desc.debugName = "ScratchBufferChunk";
chunk->buffer = m_Device->createBuffer(desc);
chunk->mappedMemory = nullptr;
chunk->bufferSize = size;
}
else
{
BufferDesc desc;
desc.byteSize = size;
desc.cpuAccess = CpuAccessMode::Write;
desc.debugName = "UploadChunk";
// The upload manager buffers are used in buildTopLevelAccelStruct to store instance data
desc.isAccelStructBuildInput = m_Device->queryFeatureSupport(Feature::RayTracingAccelStruct);
chunk->buffer = m_Device->createBuffer(desc);
chunk->mappedMemory = m_Device->mapBuffer(chunk->buffer, CpuAccessMode::Write);
chunk->bufferSize = size;
}
return chunk;
}
bool UploadManager::suballocateBuffer(uint64_t size, Buffer** pBuffer, uint64_t* pOffset, void** pCpuVA,
uint64_t currentVersion, uint32_t alignment)
{
std::shared_ptr<BufferChunk> chunkToRetire;
if (m_CurrentChunk)
{
uint64_t alignedOffset = align(m_CurrentChunk->writePointer, (uint64_t)alignment);
uint64_t endOfDataInChunk = alignedOffset + size;
if (endOfDataInChunk <= m_CurrentChunk->bufferSize)
{
m_CurrentChunk->writePointer = endOfDataInChunk;
*pBuffer = checked_cast<Buffer*>(m_CurrentChunk->buffer.Get());
*pOffset = alignedOffset;
if (pCpuVA && m_CurrentChunk->mappedMemory)
*pCpuVA = (char*)m_CurrentChunk->mappedMemory + alignedOffset;
return true;
}
chunkToRetire = m_CurrentChunk;
m_CurrentChunk.reset();
}
CommandQueue queue = VersionGetQueue(currentVersion);
uint64_t completedInstance = m_Device->queueGetCompletedInstance(queue);
for (auto it = m_ChunkPool.begin(); it != m_ChunkPool.end(); ++it)
{
std::shared_ptr<BufferChunk> chunk = *it;
if (VersionGetSubmitted(chunk->version)
&& VersionGetInstance(chunk->version) <= completedInstance)
{
chunk->version = 0;
}
if (chunk->version == 0 && chunk->bufferSize >= size)
{
m_ChunkPool.erase(it);
m_CurrentChunk = chunk;
break;
}
}
if (chunkToRetire)
{
m_ChunkPool.push_back(chunkToRetire);
}
if (!m_CurrentChunk)
{
uint64_t sizeToAllocate = align(std::max(size, m_DefaultChunkSize), BufferChunk::c_sizeAlignment);
if ((m_MemoryLimit > 0) && (m_AllocatedMemory + sizeToAllocate > m_MemoryLimit))
return false;
m_CurrentChunk = CreateChunk(sizeToAllocate);
}
m_CurrentChunk->version = currentVersion;
m_CurrentChunk->writePointer = size;
*pBuffer = checked_cast<Buffer*>(m_CurrentChunk->buffer.Get());
*pOffset = 0;
if (pCpuVA)
*pCpuVA = m_CurrentChunk->mappedMemory;
return true;
}
void UploadManager::submitChunks(uint64_t currentVersion, uint64_t submittedVersion)
{
if (m_CurrentChunk)
{
m_ChunkPool.push_back(m_CurrentChunk);
m_CurrentChunk.reset();
}
for (const auto& chunk : m_ChunkPool)
{
if (chunk->version == currentVersion)
chunk->version = submittedVersion;
}
}
} | 34.26 | 110 | 0.622884 |
5081c7d33af9647d83b7b6a0905c91a566c1685a | 856 | cpp | C++ | codeforces/587div3/B.cpp | xenowits/cp | 963b3c7df65b5328d5ce5ef894a46691afefb98c | [
"MIT"
] | null | null | null | codeforces/587div3/B.cpp | xenowits/cp | 963b3c7df65b5328d5ce5ef894a46691afefb98c | [
"MIT"
] | null | null | null | codeforces/587div3/B.cpp | xenowits/cp | 963b3c7df65b5328d5ce5ef894a46691afefb98c | [
"MIT"
] | null | null | null | #include<bits/stdc++.h>
using namespace std;
#define fori(i,a,b) for (long int i = a; i <= b ; ++i)
#define ford(i,a,b) for(long int i = a;i >= b ; --i)
#define mk make_pair
#define mod 1000000007
#define pb push_back
#define vec vector<long long int>
#define ll long long
#define rnd mt19937_64 rng(chrono::high_resolution_clock::now().time_since_epoch().count())
#define pi pair<long long int,long long int>
#define sc second
#define fs first
int main()
{
ios_base::sync_with_stdio(false);
cin.tie(NULL);
ll n,temp;
cin >> n;
vector<pi> v;
fori(i,1,n)
{
cin >> temp;
v.pb(mk(temp,i));
}
sort(v.begin(), v.end());
reverse(v.begin(), v.end());
ll ans = 0, hell = 0;
fori(i,0,n-1)
{
ans += (v[i].fs*hell);
hell += 1;
}
cout << ans+n << endl;
fori(i,0,n-1)
cout << v[i].sc << " ";
return 0;
}
| 17.12 | 91 | 0.593458 |
5088bd07be39f03921292ee9a9af76c4f3883ed7 | 1,067 | cpp | C++ | competitive programming/leetcode/905. Sort Array By Parity.cpp | kashyap99saksham/Code | 96658d0920eb79c007701d2a3cc9dbf453d78f96 | [
"MIT"
] | 16 | 2020-06-02T19:22:45.000Z | 2022-02-05T10:35:28.000Z | competitive programming/leetcode/905. Sort Array By Parity.cpp | codezoned/Code | de91ffc7ef06812a31464fb40358e2436734574c | [
"MIT"
] | null | null | null | competitive programming/leetcode/905. Sort Array By Parity.cpp | codezoned/Code | de91ffc7ef06812a31464fb40358e2436734574c | [
"MIT"
] | 2 | 2020-08-27T17:40:06.000Z | 2022-02-05T10:33:52.000Z | Given an array A of non-negative integers, return an array consisting of all the even elements of A, followed by all the odd elements of A.
You may return any answer array that satisfies this condition.
Example 1:
Input: [3,1,2,4]
Output: [2,4,3,1]
The outputs [4,2,3,1], [2,4,1,3], and [4,2,1,3] would also be accepted.
Note:
1 <= A.length <= 5000
0 <= A[i] <= 5000
// Without extra space
class Solution {
public:
vector<int> sortArrayByParity(vector<int>& A) {
int n=A.size();
int j=0;
for(int i=0;i<n;i++){
if(A[i]%2==0){
swap(A[i], A[j]);
j++;
}
}
return A;
}
};
// Extra space
class Solution {
public:
vector<int> sortArrayByParity(vector<int>& A) {
int n=A.size();
vector<int> res(n);
int start=0, last=n-1;
for(int i=0;i<n;i++){
if(A[i]%2==0){
res[start++]=A[i];
} else {
res[last--]=A[i];
}
}
return res;
}
};
| 16.936508 | 139 | 0.492971 |
5089af9edf6629885ea3f89dd4f8105bc13337a7 | 1,585 | hpp | C++ | infra/util/Allocator.hpp | oguzcanphilips/embeddedinfralib | f1b083d61a34d123d34ab7cd51267377aa2f7855 | [
"Unlicense"
] | 54 | 2019-04-02T14:42:54.000Z | 2022-03-20T23:02:19.000Z | infra/util/Allocator.hpp | oguzcanphilips/embeddedinfralib | f1b083d61a34d123d34ab7cd51267377aa2f7855 | [
"Unlicense"
] | 32 | 2019-03-26T06:57:29.000Z | 2022-03-25T00:04:44.000Z | infra/util/Allocator.hpp | oguzcanphilips/embeddedinfralib | f1b083d61a34d123d34ab7cd51267377aa2f7855 | [
"Unlicense"
] | 20 | 2019-03-25T15:49:49.000Z | 2022-03-20T23:02:22.000Z | #ifndef INFRA_ALLOCATOR_HPP
#define INFRA_ALLOCATOR_HPP
#include <memory>
namespace infra
{
class AllocatorBase
{
protected:
AllocatorBase() = default;
AllocatorBase(const AllocatorBase& other) = delete;
AllocatorBase& operator=(const AllocatorBase& other) = delete;
~AllocatorBase() = default;
public:
virtual void Deallocate(void* object) = 0;
};
class Deallocator
{
public:
Deallocator() = default;
explicit Deallocator(AllocatorBase& allocator);
void operator()(void* object);
private:
AllocatorBase* allocator = nullptr;
};
template<class T>
using UniquePtr = std::unique_ptr<T, Deallocator>;
template<class T>
UniquePtr<T> MakeUnique(T* object, AllocatorBase& allocator);
template<class T, class ConstructionArgs>
class Allocator;
template<class T, class... ConstructionArgs>
class Allocator<T, void(ConstructionArgs...)>
: public AllocatorBase
{
public:
virtual UniquePtr<T> Allocate(ConstructionArgs... args) = 0;
protected:
~Allocator() = default;
};
//// Implementation ////
inline Deallocator::Deallocator(AllocatorBase& allocator)
: allocator(&allocator)
{}
inline void Deallocator::operator()(void* object)
{
allocator->Deallocate(object);
}
template<class T>
UniquePtr<T> MakeUnique(T* object, AllocatorBase& allocator)
{
return infra::UniquePtr<T>(object, Deallocator(allocator));
}
}
#endif
| 22.323944 | 70 | 0.634069 |
50906cdb433c4f11ffd5eb9ae7025dfe569be67a | 5,564 | cxx | C++ | templates/ws/src/clan/lang.cxx | roadnarrows-robotics/rnmake | 6446cda6b36d66f6ee945db128a052caaf9c89ee | [
"MIT"
] | null | null | null | templates/ws/src/clan/lang.cxx | roadnarrows-robotics/rnmake | 6446cda6b36d66f6ee945db128a052caaf9c89ee | [
"MIT"
] | null | null | null | templates/ws/src/clan/lang.cxx | roadnarrows-robotics/rnmake | 6446cda6b36d66f6ee945db128a052caaf9c89ee | [
"MIT"
] | null | null | null | /*! \file
*
* \brief Languages spoken back in the day.
*
* \pkgfile{@FILENAME@}
* \pkgcomponent{Application,clan}
* \author @PKG_AUTHOR@
*
* \LegalBegin
* @PKG_LICENSE@
* \LegalEnd
*/
#include <string>
#include "@PKG_NAME@/stone_tools.h"
#include "@PKG_NAME@/fire.h"
#include "utils.h"
#include "grammar.h"
#include "lang.h"
namespace clan
{
namespace troglodese
{
/*!
* \brief The Troglodese language.
*
* This is the static component of the language.
*
* \sa clan::Grammar::load
*/
Language Troglodese =
{
// name
"Troglodese",
// dictionary symbols
{ "s:Terry the Terror Bird",
"s:A rock",
"s:CLAN[Trog, Mini Trog, Baby Trog]",
"s:ADULTS[Trog]",
"s:URCHINS[Mini Trog]",
"s:CAVIES[Baby Trog]",
"v:DAILY_TASKS[gathers, grinds, makes, builds, cooks, eats, sleeps]",
"v:DANGEROUS[hunts, scavenges]",
"v:LOCOMOTION[walks, ambles, trots, runs]",
"v:CREEP[crawls, creeps, waddles]",
"v:steals",
"v:ROCKS[rolls, drops, is thrown]",
"v:is",
"v:is feeling",
"v:is a",
"v:likes",
"v:not like",
"o:PREY[glyptodon, capybara, titi monkey, hippidion, "
"lestodon ground sloth, toxodon]",
"o:GATHERED[grubs, tool stones, wood, eggs, termites, teosinte, "
"quinoa, amaranth]",
"o:CARRION[rotting gomphothere thigh, arctotherium rump, "
"questionable carrion]",
"o:STONE_TOOLS_MADE[broken stone]",
"o:FOOD[glyptodon, capybara, titi monkey, hippidion, "
"lestodon ground sloth, toxodon, grubs, eggs, termites, "
"teosinte, quinoa, amaranth, rotting gomphothere thigh, "
"arctotherium rump, questionable carrion]",
"o:COOKING_FOOD[glyptodon, capybara, titi monkey, hippidion, "
"lestodon ground sloth, toxodon, eggs, "
"rotting gomphothere thigh, arctotherium rump, "
"questionable carrion]",
"o:GRINDING_FOOD[teosinte, quinoa, amaranth]",
"o:EMOTION[happy, sad, mad, an existential crisis]",
"o:a fire",
"o:a troglodyte",
"o:LOOT[table scraps, a rock, a troglodyte]",
"o:DEST[to the cave, along the river, in the forest, backwards]",
"o:ART[cave painting, hand shadow puppet, shell ornament, shiny rock]",
"p:by the tail",
"p:at the creek",
"p:using a stick",
"p:WHEN[at dawn, when sun up high, when me hungry]",
"p:with a stalk of grass",
"p:WITH_WEAPON[with hands and teeth, with a rock, with a hand axe, "
"with old spear, by abusive name calling]",
"p:FIRE_METHOD[with fuel oxygen heat as like triangle]",
},
// production rules
{ "s:ADULTS -> v:DAILY_TASKS",
"s:ADULTS -> v:LOCOMOTION",
"s:ADULTS -> v:DANGEROUS",
"s:URCHINS -> v:DAILY_TASKS",
"s:URCHINS -> v:LOCOMOTION",
"s:CAVIES -> v:CREEP",
"s:CLAN -> v:is feeling",
"s:Terry the Terror Bird -> v:steals",
"s:A rock -> v:ROCKS",
"s:CLAN -> v:likes",
"s:CLAN -> v:not like",
"v:is -> o:a troglodyte",
"v:is feeling -> o:EMOTION",
"v:hunts -> o:PREY",
"v:scavenges -> o:CARRION",
"v:gathers -> o:GATHERED",
"v:gathers -> p:using a stick",
"v:makes -> o:STONE_TOOLS_MADE",
"v:builds -> o:a fire",
"v:eats -> o:FOOD",
"v:grinds -> o:GRINDING_FOOD",
"v:cooks -> o:COOKING_FOOD",
"v:steals -> o:LOOT",
"v:LOCOMOTION -> o:DEST",
"v:likes -> o:ART",
"v:not like -> o:ART",
"o:PREY -> p:WHEN",
"o:PREY -> p:WITH_WEAPON",
"o:GATHERED -> p:WHEN",
"o:grubs -> p:using a stick",
"o:termites -> p:with a stalk of grass",
"o:a fire -> p:FIRE_METHOD",
}
};
bool add_stone_tools(Grammar &g)
{
STONE_TOOL first = STONE_TOOL((int)STONE_TOOL_UNKNOWN + 1);
STONE_TOOL numof = NUMOF_STONE_TOOLS;
STONE_TOOL made[] =
{
STONE_TOOL_HAMMERSTONE, STONE_TOOL_FLAKE, STONE_TOOL_HAND_AXE,
STONE_TOOL_BLADE, STONE_TOOL_POINT, STONE_TOOL_AWL,
STONE_TOOL_SCRAPPER, STONE_TOOL_BURIN,
STONE_TOOL_UNKNOWN
};
STONE_TOOL grind[] =
{
STONE_TOOL_QUERN, STONE_TOOL_MULLER, STONE_TOOL_UNKNOWN
};
STONE_TOOL discard[] = {STONE_TOOL_CORE, STONE_TOOL_UNKNOWN};
//StrVec names;
StrVec vec;
int tool;
//for(tool=first; tool<numof; ++tool)
//{
// names.push_back(name_of_stone_tool((STONE_TOOL)tool));
//}
//if( !g.add_symbol(Grammar::ESVO::SUBJECT, "STONE_TOOLS", names) )
//{
// return false;
//}
for(tool=0; made[tool]!=STONE_TOOL_UNKNOWN; ++tool)
{
vec.push_back(name_of_stone_tool(made[tool]));
}
if( !g.add_symbol(Grammar::ESVO::OBJECT, "STONE_TOOLS_MADE", vec) )
{
return false;
}
return true;
}
bool add_fire(Grammar &g)
{
int way;
StrVec methods;
for(way=0; way<num_ways_me_get_fire(); ++way)
{
methods.push_back(me_get_fire(way));
}
if( !g.add_symbol(Grammar::ESVO::PVP, "FIRE_METHOD", methods) )
{
return false;
}
return true;
}
} // namespace troglodese
} // namespace clan
| 28.387755 | 79 | 0.550324 |
509162b1e05af53522a2ceacc5e9f25212b7add7 | 1,862 | hpp | C++ | Simple++/MemoryAllocation.hpp | Oriode/Simpleplusplus | 2ba44eeab5078d6dab66bdefdf73617696b8cb2e | [
"Apache-2.0"
] | null | null | null | Simple++/MemoryAllocation.hpp | Oriode/Simpleplusplus | 2ba44eeab5078d6dab66bdefdf73617696b8cb2e | [
"Apache-2.0"
] | null | null | null | Simple++/MemoryAllocation.hpp | Oriode/Simpleplusplus | 2ba44eeab5078d6dab66bdefdf73617696b8cb2e | [
"Apache-2.0"
] | null | null | null |
MemoryAllocation::MemoryAllocation( void ) {
}
MemoryAllocation::MemoryAllocation( unsigned long memoryAddress, unsigned long memorySize, const StringASCII & allocationFileName, unsigned int lineNumber ) {
this -> memoryAddress = memoryAddress;
this -> memorySize = memorySize;
this -> allocationFileName = allocationFileName;
this -> allocationLineNumber = lineNumber;
this -> bAllocated = true;
}
MemoryAllocation::~MemoryAllocation( void ) {
}
void MemoryAllocation::setAllocationFileName( const StringASCII & fileName ) {
this -> allocationFileName = fileName;
}
void MemoryAllocation::setAllocationLineNumber( int lineNumber ) {
this -> allocationFileName = lineNumber;
}
void MemoryAllocation::setDeleteFileName( const StringASCII & fileName ) {
this -> deleteFileName = fileName;
}
void MemoryAllocation::setDeleteLineNumber( int lineNumber ) {
this -> deleteLineNumber = lineNumber;
}
void MemoryAllocation::setMemoryAddress( unsigned long long address ) {
this -> memoryAddress = address;
}
void MemoryAllocation::setMemorySize( unsigned long long size ) {
this -> memorySize = size;
}
const StringASCII & MemoryAllocation::getAllocationFileName() const {
return this -> allocationFileName;
}
int MemoryAllocation::getAllocationLineNumber() const {
return this -> allocationLineNumber;
}
const StringASCII & MemoryAllocation::getDeleteFileName() const {
return this -> deleteFileName;
}
int MemoryAllocation::getDeleteLineNumber() const {
return this -> deleteLineNumber;
}
unsigned long long MemoryAllocation::getMemoryAddress() const {
return this -> memoryAddress;
}
unsigned long long MemoryAllocation::getMemorySize() const {
return this -> memorySize;
}
bool MemoryAllocation::isAllocated() const {
return this -> bAllocated;
}
void MemoryAllocation::setAllocated( bool value ) {
this -> bAllocated = value;
}
| 25.861111 | 158 | 0.767991 |
5092b7a93fb0f11d68b4be55fba304143508ec79 | 3,454 | cc | C++ | homeworks/NonConformingCrouzeixRaviartFiniteElements/templates/test/nonconformingcrouzeixraviartfiniteelements_test.cc | padomu/NPDECODES | d2bc5b0d2d5e76e4d5b8ab6948c82f902211182e | [
"MIT"
] | 15 | 2019-04-29T11:28:56.000Z | 2022-03-22T05:10:58.000Z | homeworks/NonConformingCrouzeixRaviartFiniteElements/templates/test/nonconformingcrouzeixraviartfiniteelements_test.cc | padomu/NPDECODES | d2bc5b0d2d5e76e4d5b8ab6948c82f902211182e | [
"MIT"
] | 12 | 2020-02-29T15:05:58.000Z | 2022-02-21T13:51:07.000Z | homeworks/NonConformingCrouzeixRaviartFiniteElements/templates/test/nonconformingcrouzeixraviartfiniteelements_test.cc | padomu/NPDECODES | d2bc5b0d2d5e76e4d5b8ab6948c82f902211182e | [
"MIT"
] | 26 | 2020-01-09T15:59:23.000Z | 2022-03-24T16:27:33.000Z | /**
* @file
* @brief NPDE homework NonConformingCrouzeixRaviartFiniteElements code
* @author Anian Ruoss
* @date 18.03.2019
* @copyright Developed at ETH Zurich
*/
#include <gtest/gtest.h>
#include <lf/base/base.h>
#include <lf/mesh/mesh.h>
#include <lf/mesh/test_utils/test_meshes.h>
#include <Eigen/Core>
#include "../crfespace.h"
#include "../crl2errordirichletbvp.h"
using namespace NonConformingCrouzeixRaviartFiniteElements;
TEST(CRReferenceFiniteElement, RefEl) {
CRReferenceFiniteElement cr_ref_el;
EXPECT_TRUE(cr_ref_el.RefEl() == lf::base::RefEl::kTria());
}
TEST(CRReferenceFiniteElement, Degree) {
CRReferenceFiniteElement cr_ref_el;
EXPECT_EQ(cr_ref_el.Degree(), 1);
}
TEST(CRReferenceFiniteElement, NumRefShapeFunctions) {
CRReferenceFiniteElement cr_ref_el;
EXPECT_EQ(cr_ref_el.NumRefShapeFunctions(), 3);
EXPECT_EQ(cr_ref_el.NumRefShapeFunctions(0), 0);
EXPECT_EQ(cr_ref_el.NumRefShapeFunctions(1), 1);
EXPECT_EQ(cr_ref_el.NumRefShapeFunctions(2), 0);
EXPECT_EQ(cr_ref_el.NumRefShapeFunctions(1, 0), 1);
EXPECT_EQ(cr_ref_el.NumRefShapeFunctions(1, 1), 1);
EXPECT_EQ(cr_ref_el.NumRefShapeFunctions(1, 2), 1);
}
TEST(CRReferenceFiniteElement, EvalReferenceShapeFunctions) {
CRReferenceFiniteElement cr_ref_el;
Eigen::MatrixXd ref_coords(2, 3);
ref_coords << 0, 1, 2, 3, 4, 5;
Eigen::MatrixXd ref_fun_evals(3, 3);
ref_fun_evals << -5, -7, -9, 5, 9, 13, 1, -1, -3;
EXPECT_EQ(cr_ref_el.EvalReferenceShapeFunctions(ref_coords), ref_fun_evals);
}
TEST(CRReferenceFiniteElement, GradientsReferenceShapeFunctions) {
CRReferenceFiniteElement cr_ref_el;
Eigen::MatrixXd ref_coords(2, 3);
ref_coords << 0, 1, 2, 3, 4, 5;
Eigen::MatrixXd ref_fun_grads(3, 6);
ref_fun_grads << 0, -2, 0, -2, 0, -2, 2, 2, 2, 2, 2, 2, -2, 0, -2, 0, -2, 0;
EXPECT_EQ(cr_ref_el.GradientsReferenceShapeFunctions(ref_coords),
ref_fun_grads);
}
TEST(CRReferenceFiniteElement, EvaluationNodes) {
CRReferenceFiniteElement cr_ref_el;
Eigen::MatrixXd eval_nodes(2, 3);
eval_nodes << .5, .5, 0, 0, .5, .5;
EXPECT_EQ(cr_ref_el.EvaluationNodes(), eval_nodes);
}
TEST(CRReferenceFiniteElement, NumEvaluationNodes) {
CRReferenceFiniteElement cr_ref_el;
EXPECT_EQ(cr_ref_el.NumEvaluationNodes(), 3);
}
TEST(CRReferenceFiniteElement, NodalValuesToDofs) {
CRReferenceFiniteElement cr_ref_el;
Eigen::MatrixXd nodvals(1, 3);
nodvals << 0, 1, 2;
EXPECT_EQ(cr_ref_el.NodalValuesToDofs(nodvals), nodvals);
}
TEST(CRFeSpace, Constructor) {
std::shared_ptr<lf::mesh::Mesh> mesh_ptr =
lf::mesh::test_utils::GenerateHybrid2DTestMesh(3);
CRFeSpace fe_space(mesh_ptr);
EXPECT_EQ(fe_space.ShapeFunctionLayout(lf::base::RefEl::kSegment()), nullptr);
EXPECT_EQ(typeid(*(fe_space.ShapeFunctionLayout(lf::base::RefEl::kTria()))),
typeid(CRReferenceFiniteElement));
EXPECT_EQ(fe_space.ShapeFunctionLayout(lf::base::RefEl::kQuad()), nullptr);
}
TEST(NonConformingCrouzeixRaviartFiniteElements,
L2errorCRDiscretizationDirichletBVP) {
std::vector<double> l2_errors = {0.0227969, 0.00579489, 0.0014546923,
0.000364046};
// Loop over meshes
for (int i = 1; i <= 4; ++i) {
std::string mesh_file = CURRENT_SOURCE_DIR "/../../meshes/refined_square" +
std::to_string(i) + ".msh";
EXPECT_FLOAT_EQ(L2errorCRDiscretizationDirichletBVP(mesh_file),
l2_errors[i - 1]);
}
}
| 30.034783 | 80 | 0.718587 |
5092c1c3cc00fc3ec505ba5fe0f40c04f6f003dd | 1,891 | hpp | C++ | lab_4/matrixline_methods.hpp | DrStarland/bmstu_AA_2020 | acbb0c76d5763c06db0230025423e0fbb4382a9f | [
"Apache-2.0"
] | null | null | null | lab_4/matrixline_methods.hpp | DrStarland/bmstu_AA_2020 | acbb0c76d5763c06db0230025423e0fbb4382a9f | [
"Apache-2.0"
] | null | null | null | lab_4/matrixline_methods.hpp | DrStarland/bmstu_AA_2020 | acbb0c76d5763c06db0230025423e0fbb4382a9f | [
"Apache-2.0"
] | null | null | null | #ifndef MATRIXLINE_METHODS_HPP
#define MATRIXLINE_METHODS_HPP
#include "matrix.h"
template <typename T>
Matrix<T>::MatrixLine::MatrixLine(size_t len) : MatrixLine(len, nullptr) {}
template <typename T>
Matrix<T>::MatrixLine::MatrixLine(MatrixLine &©) { this->_move(std::move(copy)); }
template <typename T>
Matrix<T>::MatrixLine::MatrixLine(const MatrixLine ©) : MatrixLine(copy.m_len, ©) {}
template <typename T>
Matrix<T>::MatrixLine::MatrixLine(size_t n, const MatrixLine* source) {
this->m_len = n, this->alloc_ptr();
if (source != nullptr)
for (size_t i = 0; i < this->m_len; i++)
this->m_ptr[i] = source->m_ptr[i];
}
template <typename T>
void Matrix<T>::MatrixLine::alloc_ptr() {
T* temp = new (std::nothrow) T[m_len];
time_t _time = time(NULL);
if (!temp)
throw MemoryException(__FILE__, typeid(*this).name(), __LINE__, ctime(&_time));
m_ptr = shared_ptr<T[]> (temp);
}
template <typename T>
typename Matrix<T>::MatrixLine& Matrix<T>::MatrixLine::operator=(MatrixLine&& copy) {
this->_move(std::move(copy));
return *this;
}
template <typename T>
T& Matrix<T>::MatrixLine::operator[](size_t ind) {
time_t _time = time(NULL);
if (this->m_len <= ind)
throw IndexException(__FILE__, typeid(*this).name(), __LINE__, ctime(&_time));
return this->m_ptr[ind];
}
template <typename T>
const T& Matrix<T>::MatrixLine::operator[](size_t ind) const {
time_t _time = time(NULL);
if (this->m_len <= ind)
throw IndexException(__FILE__, typeid(*this).name(), __LINE__, ctime(&_time));
return this->m_ptr[ind];
}
template <typename T>
void Matrix<T>::MatrixLine::_move(MatrixLine &©) {
this->m_len = copy.m_len, this->m_ptr = copy.m_ptr;
copy.m_ptr = nullptr, copy.m_len = 0;
}
#endif // MATRIXLINE_METHODS_HPP
| 32.603448 | 93 | 0.649392 |
50a14eb15659a1a668e106113a140777c86b501d | 5,979 | cpp | C++ | test/android/jni.cpp | 10110111/GLFFT | 78176d4480bc3675327bf2bcfd80d5dae1820081 | [
"MIT"
] | 176 | 2015-08-17T20:47:10.000Z | 2022-03-30T09:14:33.000Z | test/android/jni.cpp | 10110111/GLFFT | 78176d4480bc3675327bf2bcfd80d5dae1820081 | [
"MIT"
] | 6 | 2017-09-21T15:55:44.000Z | 2020-11-07T03:15:44.000Z | test/android/jni.cpp | 10110111/GLFFT | 78176d4480bc3675327bf2bcfd80d5dae1820081 | [
"MIT"
] | 28 | 2016-02-28T04:37:50.000Z | 2022-02-27T12:35:55.000Z | /* Copyright (C) 2015 Hans-Kristian Arntzen <maister@archlinux.us>
*
* 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 "glfft_gl_interface.hpp"
#include "glfft_context.hpp"
#include "glfft_cli.hpp"
#include <GLES2/gl2ext.h>
#include <EGL/egl.h>
#include <EGL/eglext.h>
#include "net_themaister_glfft_Native.h"
#include <memory>
#include <vector>
using namespace GLFFT;
using namespace std;
struct AndroidEGLContext : GLContext
{
EGLContext ctx = EGL_NO_CONTEXT;
EGLSurface surf = EGL_NO_SURFACE;
EGLDisplay dpy = EGL_NO_SURFACE;
EGLConfig conf = 0;
~AndroidEGLContext()
{
if (dpy)
{
teardown();
eglMakeCurrent(dpy, EGL_NO_SURFACE, EGL_NO_SURFACE, EGL_NO_CONTEXT);
if (ctx)
eglDestroyContext(dpy, ctx);
if (surf)
eglDestroySurface(dpy, surf);
eglTerminate(dpy);
}
}
};
unique_ptr<Context> GLFFT::create_cli_context()
{
unique_ptr<AndroidEGLContext> egl(new AndroidEGLContext);
static const EGLint attr[] = {
EGL_RENDERABLE_TYPE, EGL_OPENGL_ES2_BIT,
EGL_SURFACE_TYPE, EGL_PBUFFER_BIT,
EGL_RED_SIZE, 1,
EGL_GREEN_SIZE, 1,
EGL_BLUE_SIZE, 1,
EGL_ALPHA_SIZE, 0,
EGL_DEPTH_SIZE, 0,
EGL_STENCIL_SIZE, 0,
EGL_NONE,
};
static const EGLint context_attr[] = {
EGL_CONTEXT_CLIENT_VERSION, 3,
EGL_NONE,
};
static const EGLint surface_attr[] = {
EGL_WIDTH, 64,
EGL_HEIGHT, 64,
EGL_NONE,
};
egl->dpy = eglGetDisplay(EGL_DEFAULT_DISPLAY);
if (egl->dpy == EGL_NO_DISPLAY)
{
egl->log("Failed to create display.\n");
return nullptr;
}
eglInitialize(egl->dpy, nullptr, nullptr);
EGLint num_configs = 0;
eglChooseConfig(egl->dpy, attr, &egl->conf, 1, &num_configs);
if (num_configs != 1)
{
egl->log("Failed to get EGL config.\n");
return nullptr;
}
egl->ctx = eglCreateContext(egl->dpy, egl->conf, EGL_NO_CONTEXT, context_attr);
if (egl->ctx == EGL_NO_CONTEXT)
{
egl->log("Failed to create GLES context.\n");
return nullptr;
}
egl->surf = eglCreatePbufferSurface(egl->dpy, egl->conf, surface_attr);
if (egl->surf == EGL_NO_SURFACE)
{
egl->log("Failed to create Pbuffer surface.\n");
return nullptr;
}
if (!eglMakeCurrent(egl->dpy, egl->surf, egl->surf, egl->ctx))
{
egl->log("Failed to make EGL context current.\n");
return nullptr;
}
const char *version = reinterpret_cast<const char*>(glGetString(GL_VERSION));
unsigned major = 0, minor = 0;
sscanf(version, "OpenGL ES %u.%u", &major, &minor);
unsigned ctx_version = major * 1000 + minor;
if (ctx_version < 3001)
{
egl->log("OpenGL ES 3.1 not supported (got %u.%u context).\n",
major, minor);
return nullptr;
}
egl->log("Version: %s\n", version);
return unique_ptr<Context>(move(egl));
}
void glfft_log(const char *fmt, ...)
{
va_list va;
va_start(va, fmt);
__android_log_vprint(ANDROID_LOG_INFO, "GLFFT", fmt, va);
va_end(va);
#ifdef GLFFT_CLI_ASYNC
char buffer[16 * 1024];
va_start(va, fmt);
vsnprintf(buffer, sizeof(buffer), fmt, va);
GLFFT::get_async_task()->push_message(buffer);
#endif
}
static int start_task(const vector<const char*> &argv)
{
GLFFT::set_async_task([argv] {
return GLFFT::cli_main(
GLFFT::get_async_context(),
argv.size() - 1, (char**)argv.data());
});
GLFFT::get_async_task()->start();
return 0;
}
JNIEXPORT jint JNICALL Java_net_themaister_glfft_Native_beginRunTestSuiteTask(JNIEnv *, jclass)
{
vector<const char*> argv = {
"glfft_cli",
"test",
"--test-all",
nullptr,
};
return start_task(argv);
}
JNIEXPORT jint JNICALL Java_net_themaister_glfft_Native_beginBenchTask
(JNIEnv *, jclass)
{
vector<const char*> argv = {
"glfft_cli",
"bench",
"--width",
"2048",
"--height",
"2048",
"--fp16",
nullptr,
};
return start_task(argv);
}
JNIEXPORT jstring JNICALL Java_net_themaister_glfft_Native_pull
(JNIEnv *env, jclass)
{
string str;
auto *task = GLFFT::get_async_task();
bool ret = task->pull(str);
return ret ? env->NewStringUTF(str.c_str()) : nullptr;
}
JNIEXPORT jint JNICALL Java_net_themaister_glfft_Native_getExitCode
(JNIEnv *, jclass)
{
auto *task = GLFFT::get_async_task();
return task->get_exit_code();
}
JNIEXPORT jint JNICALL Java_net_themaister_glfft_Native_isComplete
(JNIEnv *, jclass)
{
auto *task = GLFFT::get_async_task();
return task->is_completed();
}
JNIEXPORT void JNICALL Java_net_themaister_glfft_Native_endTask
(JNIEnv *, jclass)
{
GLFFT::end_async_task();
}
| 26.811659 | 129 | 0.646596 |
50a3fa8ab19998e82f47f1c1c383e3b87fac989a | 1,752 | hpp | C++ | src/ScreenServer.hpp | RobinSinghNanda/Home-assistant-display | 6f59104012c0956b54d4b55e190aa89941c2c1af | [
"MIT"
] | 2 | 2020-10-23T19:53:56.000Z | 2020-11-06T08:59:48.000Z | src/ScreenServer.hpp | RobinSinghNanda/Home-assistant-display | 6f59104012c0956b54d4b55e190aa89941c2c1af | [
"MIT"
] | null | null | null | src/ScreenServer.hpp | RobinSinghNanda/Home-assistant-display | 6f59104012c0956b54d4b55e190aa89941c2c1af | [
"MIT"
] | null | null | null | #ifndef __SCREENSERVER_H__
#define __SCREENSERVER_H__
#include "Arduino.h"
#include "TFT_eSPI.h"
//====================================================================================
// Definitions
//====================================================================================
#define PIXEL_TIMEOUT 100 // 100ms Time-out between pixel requests
#define START_TIMEOUT 10000 // 10s Maximum time to wait at start transfer
#define BITS_PER_PIXEL 16 // 24 for RGB colour format, 16 for 565 colour format
// File names must be alpha-numeric characters (0-9, a-z, A-Z) or "/" underscore "_"
// other ascii characters are stripped out by client, including / generates
// sub-directories
#define DEFAULT_FILENAME "tft_screenshots/screenshot" // In case none is specified
#define FILE_TYPE "png" // jpg, bmp, png, tif are valid
// Filename extension
// '#' = add incrementing number, '@' = add timestamp, '%' add millis() timestamp,
// '*' = add nothing
// '@' and '%' will generate new unique filenames, so beware of cluttering up your
// hard drive with lots of images! The PC client sketch is set to limit the number of
// saved images to 1000 and will then prompt for a restart.
#define FILE_EXT '@'
// Number of pixels to send in a burst (minimum of 1), no benefit above 8
// NPIXELS values and render times:
// NPIXELS 1 = use readPixel() = >5s and 16 bit pixels only
// NPIXELS >1 using rectRead() 2 = 1.75s, 4 = 1.68s, 8 = 1.67s
#define NPIXELS 8 // Must be integer division of both TFT width and TFT height
bool screenServer(void);
bool screenServer(String filename);
bool serialScreenServer(String filename);
void sendParameters(String filename);
#endif // __SCREENSERVER_H__ | 42.731707 | 86 | 0.639269 |
50a45c4fbd2c43884473a27479cb5a6ba43ee08e | 2,841 | cpp | C++ | Sources/Elastos/Frameworks/Droid/Base/Core/src/elastos/droid/media/tv/CTvStreamConfigBuilder.cpp | jingcao80/Elastos | d0f39852356bdaf3a1234743b86364493a0441bc | [
"Apache-2.0"
] | 7 | 2017-07-13T10:34:54.000Z | 2021-04-16T05:40:35.000Z | Sources/Elastos/Frameworks/Droid/Base/Core/src/elastos/droid/media/tv/CTvStreamConfigBuilder.cpp | jingcao80/Elastos | d0f39852356bdaf3a1234743b86364493a0441bc | [
"Apache-2.0"
] | null | null | null | Sources/Elastos/Frameworks/Droid/Base/Core/src/elastos/droid/media/tv/CTvStreamConfigBuilder.cpp | jingcao80/Elastos | d0f39852356bdaf3a1234743b86364493a0441bc | [
"Apache-2.0"
] | 9 | 2017-07-13T12:33:20.000Z | 2021-06-19T02:46:48.000Z | //=========================================================================
// Copyright (C) 2012 The Elastos Open Source 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.
//=========================================================================
#include "elastos/droid/media/tv/CTvStreamConfigBuilder.h"
#include "elastos/droid/media/tv/CTvStreamConfig.h"
using Elastos::Core::CInteger32;
namespace Elastos {
namespace Droid {
namespace Media {
namespace Tv {
CAR_INTERFACE_IMPL(CTvStreamConfigBuilder, Object, ITvStreamConfigBuilder)
CAR_OBJECT_IMPL(CTvStreamConfigBuilder)
CTvStreamConfigBuilder::CTvStreamConfigBuilder()
{
}
CTvStreamConfigBuilder::~CTvStreamConfigBuilder()
{
}
ECode CTvStreamConfigBuilder::constructor()
{
return NOERROR;
}
ECode CTvStreamConfigBuilder::StreamId(
/* [in] */ Int32 streamId)
{
return CInteger32::New(streamId, (IInteger32**)&mStreamId);
}
ECode CTvStreamConfigBuilder::Type(
/* [in] */ Int32 type)
{
return CInteger32::New(type, (IInteger32**)&mType);
}
ECode CTvStreamConfigBuilder::MaxWidth(
/* [in] */ Int32 maxWidth)
{
return CInteger32::New(maxWidth, (IInteger32**)&mMaxWidth);
}
ECode CTvStreamConfigBuilder::MaxHeight(
/* [in] */ Int32 maxHeight)
{
return CInteger32::New(maxHeight, (IInteger32**)&mMaxHeight);
}
ECode CTvStreamConfigBuilder::Generation(
/* [in] */ Int32 generation)
{
return CInteger32::New(generation, (IInteger32**)&mGeneration);
}
ECode CTvStreamConfigBuilder::Build(
/* [out] */ ITvStreamConfig** result)
{
VALIDATE_NOT_NULL(result)
*result = NULL;
if (mStreamId == NULL || mType == NULL || mMaxWidth == NULL
|| mMaxHeight == NULL || mGeneration == NULL) {
// throw new UnsupportedOperationException();
return E_UNSUPPORTED_OPERATION_EXCEPTION;
}
AutoPtr<CTvStreamConfig> config;
CTvStreamConfig::NewByFriend((CTvStreamConfig**)&config);
mStreamId->GetValue(&config->mStreamId);
mType->GetValue(&config->mType);
mMaxWidth->GetValue(&config->mMaxWidth);
mMaxHeight->GetValue(&config->mMaxHeight);
mGeneration->GetValue(&config->mGeneration);
*result = ITvStreamConfig::Probe(config);
REFCOUNT_ADD(*result)
return NOERROR;
}
} // namespace Tv
} // namespace Media
} // namepsace Droid
} // namespace Elastos
| 28.128713 | 75 | 0.67969 |
50a62b87724180c6555f2d0fdc10c3b01f22255d | 2,388 | cpp | C++ | dia/ParserEditorUndoCommand.cpp | BKEngine/Creator | 5cc08fb828866cfa970951a14e41c38ecd471a8d | [
"CNRI-Python"
] | 25 | 2016-11-20T15:33:09.000Z | 2022-02-22T09:35:20.000Z | dia/ParserEditorUndoCommand.cpp | BKEngine/Creator | 5cc08fb828866cfa970951a14e41c38ecd471a8d | [
"CNRI-Python"
] | 3 | 2017-05-25T23:19:44.000Z | 2019-07-10T02:18:58.000Z | dia/ParserEditorUndoCommand.cpp | BKEngine/Creator | 5cc08fb828866cfa970951a14e41c38ecd471a8d | [
"CNRI-Python"
] | 8 | 2016-12-23T22:40:04.000Z | 2021-08-09T04:43:11.000Z | #include "ParserEditorUndoCommand.h"
#include "ParserEditorTreeModel.h"
#include "ParserEditorTreeItem.h"
InsertRowsCommand::InsertRowsCommand(ParserEditorTreeModel *model, int row, int count, const QModelIndex &parent)
: model(model)
, row(row)
, count(count)
, parent(parent)
{
}
void InsertRowsCommand::undo()
{
model->removeRowsInternal(row, count, parent);
}
void InsertRowsCommand::redo()
{
model->insertRowsInternal(row, count, parent);
}
RemoveRowsCommand::RemoveRowsCommand(ParserEditorTreeModel *model, int row, int count, const QModelIndex &parent)
: model(model)
, row(row)
, count(count)
, parent(parent)
{
items = model->itemsForRows(row, count, parent);
for (auto &&item : items)
{
item = item->duplicate();
}
}
RemoveRowsCommand::~RemoveRowsCommand()
{
qDeleteAll(items);
}
void RemoveRowsCommand::undo()
{
QList<ParserEditorTreeItem *> items;
for (auto item : this->items)
{
items << item->duplicate();
}
model->insertDataInternal(row, items, parent);
}
void RemoveRowsCommand::redo()
{
model->removeRowsInternal(row, count, parent);
}
InsertDataCommand::InsertDataCommand(ParserEditorTreeModel * model, int row, const QList<ParserEditorTreeItem*>& items, const QModelIndex & parent)
: model(model)
, row(row)
, items(items)
, parent(parent)
{
}
InsertDataCommand::~InsertDataCommand()
{
qDeleteAll(items);
}
void InsertDataCommand::undo()
{
model->removeRowsInternal(row, items.count(), parent);
}
void InsertDataCommand::redo()
{
QList<ParserEditorTreeItem *> items;
for (auto item : this->items)
{
items << item->duplicate();
}
model->insertDataInternal(row, items, parent);
}
ModifyDataCommand::ModifyDataCommand(ParserEditorTreeModel *model, const QModelIndex &index, const QVariant &data)
: model(model)
, index(index)
, data(data)
{
oldData = model->data(index, Qt::DisplayRole);
}
void ModifyDataCommand::undo()
{
model->setDataInternal(index, oldData);
}
void ModifyDataCommand::redo()
{
model->setDataInternal(index, data);
}
ChangeTypeCommand::ChangeTypeCommand(ParserEditorTreeModel *model, const QModelIndex &index, const QVariant &data)
: model(model)
, index(index)
, data(data)
{
item = model->item(index)->duplicate();
}
ChangeTypeCommand::~ChangeTypeCommand()
{
delete item;
}
void ChangeTypeCommand::undo()
{
}
void ChangeTypeCommand::redo()
{
model->setDataInternal(index, data);
}
| 19.258065 | 147 | 0.730318 |
50a9bcb4065cd1238e71b3334375115a91c76786 | 32,206 | cpp | C++ | trace_generator/src/gettrace.cpp | hcp922/ramulator | 337132dae4b9a2f99dbb78254b52d34e78122a70 | [
"MIT"
] | null | null | null | trace_generator/src/gettrace.cpp | hcp922/ramulator | 337132dae4b9a2f99dbb78254b52d34e78122a70 | [
"MIT"
] | null | null | null | trace_generator/src/gettrace.cpp | hcp922/ramulator | 337132dae4b9a2f99dbb78254b52d34e78122a70 | [
"MIT"
] | null | null | null | /*
* This file contains an ISA-portable PIN tool for tracing memory accesses.
*/
#include <stdio.h>
#include <iostream>
#include <string>
#include <sstream>
#include <unistd.h>
#include <fstream>
#include "pin.H"
#include "Cache.h"
#include "Cache.cpp"
#include "Config.h"
#include "Config.cpp"
#include "PPFileParser.cpp"
ofstream trace;
//Statistics
static UINT64 total = 0;
static UINT64 recorded_instr = 0;
static UINT64 recorded_instr_int = 0;
static UINT64 mem_req = 0;
static UINT64 filtered = 0;
static UINT64 num_ifetch = 0;
static UINT64 filt_ifetch = 0;
static int num_slices = 1;
static UINT64 c_total = 0;
static UINT64 read_count = 0;
static UINT64 write_count = 0;
static UINT64 read_hit = 0;
static UINT64 write_hit = 0;
static UINT64 icache_hit = 0;
bool full_sim = false;
bool mem_filtered = true;
bool mem2_filtered = true;
static int bbl_cnt = 0;
static bool control= false;
static bool record = false;
static std::list<PSlice*> * slices = new std::list<PSlice*>();
static std::map<Point *,long unsigned int> * execount = new std::map<Point * , long unsigned int>();
static std::map<std::string,IMG> * images = new std::map<std::string,IMG>();
static long unsigned int seq_number=0;
static std::map<string,long unsigned int> * dependency = new std::map<string,long unsigned int>();
static std::list<Request> * reqList = new std::list<Request>();
static std::list<long unsigned int> * depList = new std::list<long unsigned int>();
static std::list<std::list<string> *> * deletelist = new std::list<std::list<string> *>();
static std::list<Cache *> * caches = new std::list<Cache *>();
static std::list<REG> * compRRegs = new std::list<REG>();
//options
static KNOB<string> KnobTraceFile(KNOB_MODE_WRITEONCE , "pintool","t","trace.out","specify trace output file name.");
static KNOB<string> KnobStatsFile(KNOB_MODE_WRITEONCE , "pintool","s","stats.out","specify stats output file name.");
static KNOB<string> KnobConfigFile(KNOB_MODE_WRITEONCE , "pintool","c","Cache.cfg","specify config file name.");
static KNOB<string> KnobMode(KNOB_MODE_WRITEONCE, "pintool", "mode","cpu","specify the mode of the output trace.");
static KNOB<BOOL> KnobPhysicalAddress(KNOB_MODE_WRITEONCE,"pintool","paddr","0", "generate traces with physical addresses.");
static KNOB<string> KnobPinPoints(KNOB_MODE_WRITEONCE, "pintool", "ppoints", "", "set the pinpoints output file.");
//static KNOB<string> KnobSimpoints(KNOB_MODE_WRITEONCE, "pintool", "points", "", "set the simpoint file.");
static KNOB<string> KnobCoverage(KNOB_MODE_WRITEONCE, "pintool", "cvg", "", "set the coverage.");
static KNOB<BOOL> KnobFastOption(KNOB_MODE_WRITEONCE, "pintool", "fast", "0", "enable the fast simulation mode.");
//cache options
//L1
static KNOB<int> KnobL1Size(KNOB_MODE_WRITEONCE, "pintool", "l1_size","-1","specify the size of the first level cache as power of two.");
static KNOB<int> KnobL1Assoc(KNOB_MODE_WRITEONCE, "pintool", "l1_assoc","-1","specify the associativity of the first level cache as power of two.");
static KNOB<int> KnobL1BlockSize(KNOB_MODE_WRITEONCE, "pintool", "l1_block_size","-1","specify the block size of the first level cache as power of two.");
//L2
static KNOB<int> KnobL2Size(KNOB_MODE_WRITEONCE, "pintool", "l2_size","-1","specify the size of the second level cache as power of two.");
static KNOB<int> KnobL2Assoc(KNOB_MODE_WRITEONCE, "pintool", "l2_assoc","-1","specify the associativity of the second level cache as power of two.");
static KNOB<int> KnobL2BlockSize(KNOB_MODE_WRITEONCE, "pintool", "l2_block_size","-1","specify the block size of the second level cache as power of two.");
//L3
static KNOB<int> KnobL3Size(KNOB_MODE_WRITEONCE, "pintool", "l3_size","-1","specify the size of the third level cache as power of two.");
static KNOB<int> KnobL3Assoc(KNOB_MODE_WRITEONCE, "pintool", "l3_assoc","-1","specify the associativity of the third level cache as power of two.");
static KNOB<int> KnobL3BlockSize(KNOB_MODE_WRITEONCE, "pintool", "l3_block_size","-1","specify the block size of the third level cache as power of two.");
//icache and dcache
static KNOB<BOOL> KnobIFEnable(KNOB_MODE_WRITEONCE, "pintool", "ifetch", "1", "enable the instruction cache.");
static KNOB<BOOL> KnobDCEnable(KNOB_MODE_WRITEONCE, "pintool", "dcache", "1", "enable the instruction cache.");
static KNOB<BOOL> KnobDebugPrints(KNOB_MODE_WRITEONCE, "pintool", "debug", "0", "enable debug prints.");
static KNOB<long unsigned int> KnobISize(KNOB_MODE_WRITEONCE, "pintool", "intervalsize", "100000000", "enable debug prints.");
//Instruction Cache and Instruction Fetch
static KNOB<BOOL> KnobICEnable(KNOB_MODE_WRITEONCE, "pintool", "icache", "1", "enable the instruction cache.");
static KNOB<int> KnobICSize(KNOB_MODE_WRITEONCE, "pintool", "ic_size","-1","specify the size of the instruction cache as power of two.");
static KNOB<int> KnobICAssoc(KNOB_MODE_WRITEONCE, "pintool", "ic_assoc","-1","specify the associativity of the instruction cache as power of two.");
static KNOB<int> KnobICBlockSize(KNOB_MODE_WRITEONCE, "pintool", "ic_block_size","-1","specify the block size of the instruction cache as power of two.");
//options end.
Cache * first;
Cache * icache;
#define PAGEMAP_LENGTH 8 // pagemap contains 8 bytes of info for each virtual page
#define PAGE_SHIFT 12 // change if the page size is different than 4KB.
FILE * addr_file;
FILE *pagemap;
void finish(){
//Close the files and delete the data structures
trace.close();
if(KnobPhysicalAddress.Value()){
fclose(pagemap);
}
for(std::map<Point *, long unsigned int>::iterator it=execount->begin();it!=execount->end();++it) {
delete it->first;
}
delete execount;
//This should always print "Slices empty: 1"
if(KnobDebugPrints.Value())
printf("Slices empty : %d\n",slices->empty());
delete slices;
delete images;
delete dependency;
delete reqList;
delete depList;
for(std::list<std::list<string> *>::iterator it = deletelist->begin();it!=deletelist->end();++it){
delete *it;
}
delete deletelist;
for(std::list<Cache *>::iterator it=caches->begin();it!=caches->end();++it) {
delete *it;
}
delete caches;
// Start printing the statistics
printf("Total Number of Instructions\t\t\t\t:%lu\t\t(until the end of selected slices for coverage traces.)\n",total);
printf("Total Number of Recorded Instructions\t\t\t:%lu\n", recorded_instr);
printf("Total Number of Recorded Memory Requests\t\t:%lu\n", mem_req);
printf("Total Number of Filtered Memory Requests\t\t:%lu\n", filtered);
printf("Total Number of Recorded IFetch Requests\t\t:%lu\n", num_ifetch);
printf("Total Number of Filtered IFetch Requests\t\t:%lu\n", filt_ifetch);
printf("Number of Slices\t\t\t\t\t:%d\n", num_slices);
}
UINT64 getPhysicalAddr(long unsigned int addr){
//long unsigned limit = 1UL << 33;
//unsigned long get_page_frame_number_of_address(void *addr) {
// Open the pagemap file for the current process
// Seek to the page that the buffer is on
unsigned long offset = addr / getpagesize() * PAGEMAP_LENGTH;
assert(fseek(pagemap, (unsigned long)offset, SEEK_SET) == 0 && "Failed to seek pagemap to proper location");
// The page frame number is in bits 0-54 so read the first 7 bytes and clear the 55th bit
unsigned long page_frame_number = 0;
fread(&page_frame_number, 1, PAGEMAP_LENGTH-1, pagemap);
page_frame_number &= 0x7FFFFFFFFFFFFF;
unsigned long distance_from_page_boundary_of_buffer = addr % getpagesize();
unsigned long physical_addr = (page_frame_number << PAGE_SHIFT) + distance_from_page_boundary_of_buffer;
//fprintf(addr_file,"%lu %lu %lu %lu\n",(long)addr, (long)physical_addr,page_frame_number,offset);
//assert(limit>=physical_addr && "oops");
return physical_addr;
}
void initializeCounters(){
for(std::list<PSlice*>::iterator it=slices->begin();it!=slices->end();++it) {
execount->insert(std::make_pair((*it)->start,0));
execount->insert(std::make_pair((*it)->end,0));
}
}
//returns the counter value for the address if not in the counters return -1.
std::pair<bool, long unsigned int> getCounter(ADDRINT address) {
for(std::map<Point *,long unsigned int>::iterator it = execount->begin();it!=execount->end();++it) {
Point * pt = (*it).first;
if(pt->symbolic){
std::map<string, IMG>::iterator img = images->find(pt->lib_name);
if (img == images->end()) continue;
long unsigned int offset = address - IMG_LowAddress(img->second);
if(offset == pt->offset)
return make_pair(true,(*it).second);
}
else {
if(pt->address == address)
return make_pair(true,(*it).second);
}
}
return make_pair(false, 0);
}
void incrementCounter(ADDRINT address) {
for(std::map<Point *,long unsigned int>::iterator it = execount->begin();it!=execount->end();++it) {
Point * pt = (*it).first;
if(pt->symbolic){
std::map<string, IMG>::iterator img = images->find(pt->lib_name);
if (img == images->end()) continue;
long unsigned int offset = address - IMG_LowAddress(img->second);
if(offset == pt->offset){
(*it).second++;
}
}
else {
if(pt->address == address)
(*it).second++;
}
}
}
void removeOld(){
for(std::map<string,long unsigned int>::iterator it = dependency->begin();it!=dependency->end();++it) {
if(it->second==seq_number)
dependency->erase(it);
}
}
//update sequence number used for data dependency trace
void updateSeqNumber(){
seq_number++;
if(seq_number==128) seq_number = 0;
}
//reset sequence number used for data dependency traces
void resetSeqNumber(){
seq_number=0;
}
//update data dependency window - returns the old entry with given address (-1 if not exists)
int insertDependency(string regname){
std::map<string,long unsigned int>::iterator it = dependency->find(regname);
int old = -1;
if(it!=dependency->end()) {
old = it->second;
dependency->erase(it);
}
dependency->insert(make_pair(regname, seq_number-1));
return old;
}
//between traces we should reset the window.
void resetDependencyWindow(){
dependency->clear();
resetSeqNumber();
}
//
int getDep(REG regobj){
string reg = REG_StringShort(regobj);
std::map<string, long unsigned int>::iterator it = dependency->find(reg);
if(it!=dependency->end())
return it->second;
return -1;
}
//updates the execution count list for the starting and ending points in slices.
void updateCounters(ADDRINT address){
incrementCounter(address);
}
string getCompDependency(REG read_base, REG read2_base, REG read_index, REG read2_index){
for(std::list<REG>::iterator it = compRRegs->begin();it!=compRRegs->end();++it) {
if(!mem_filtered && (strcmp(REG_StringShort(*it).c_str(), REG_StringShort(read_base).c_str())==0
|| strcmp(REG_StringShort(*it).c_str(), REG_StringShort(read_index).c_str())==0)) {
continue;
}
if(!mem2_filtered && (strcmp(REG_StringShort(*it).c_str(), REG_StringShort(read2_base).c_str())==0
|| strcmp(REG_StringShort(*it).c_str(), REG_StringShort(read2_index).c_str())==0)) {
continue;
}
int dep = getDep((*it));
if(dep!=-1) {
depList->push_back(dep);
}
}
depList->sort();
depList->unique();
stringstream compDep;
for(std::list<long unsigned int>::iterator it = depList->begin();it!=depList->end();++it) {
compDep << " " << *it;
}
depList->clear();
return compDep.str();
}
BOOL checkLimits(ADDRINT address) {
if(full_sim) return true;
bool isInLimits=false;
if(control) { //we are in the slice limits but this could be the end point.
/*
Point * pt = slices->front()->end;
if(pt->symbolic){ //shared lib
std::map<string, IMG>::iterator img = images->find(pt->lib_name);
if (img == images->end()) return false;
long unsigned int offset = address - IMG_LowAddress(img->second);
if(offset == pt->offset && getCounter(address).first && pt->execount == getCounter(address).second) {
control = false;
trace.close();
PSlice * slc = slices->front();
delete slc;
slices->pop_front();
if(KnobDebugPrints.Value()) {
printf("[DEBUG] Remaining Slices:\n");
for(std::list<PSlice *>::iterator it=slices->begin();it!=slices->end();it++) {
printf("%s\n",(*it)->dump_content().c_str());
}
}
if(slices->empty()) {
if(KnobDebugPrints.Value())
printf("No slices left to execute.\n");
finish();
exit(0);
}
}
}
else { //not shared lib
if(pt->address == address && getCounter(address).first && pt->execount == getCounter(address).second)
{
control = false;
trace.close();
PSlice * slc = slices->front();
delete slc;
slices->pop_front();
if(KnobDebugPrints.Value()) {
printf("[DEBUG] Remaining Slices:\n");
for(std::list<PSlice *>::iterator it=slices->begin();it!=slices->end();it++) {
printf("%s\n",(*it)->dump_content().c_str());
}
}
if(slices->empty()){
if(KnobDebugPrints.Value())
printf("No slices left to execute.\n");
finish();
exit(0);
}
}
}
*/
/* 1. Check the recorded instruction count for the current interval
* Remove the current interval,
* close the file,
* reset the recorded instruction count
*/
if (recorded_instr_int == KnobISize.Value()) {
control = false;
trace.close();
PSlice * slc = slices->front();
delete slc;
slices->pop_front();
if(KnobDebugPrints.Value()) {
printf("[DEBUG] Remaining Slices:\n");
for(std::list<PSlice *>::iterator it=slices->begin();it!=slices->end();it++) {
printf("%s\n",(*it)->dump_content().c_str());
}
}
if(slices->empty()){
if(KnobDebugPrints.Value())
printf("[DEBUG] No slices left to execute.\n");
finish();
exit(0);
}
recorded_instr_int=0;
}
isInLimits = true;
}
if(!control) //we are out of the slice limit. But the instruction may be the starting point.
{
if(slices->empty()) return false; //if we dont have any slices left then we won't record any more traces.
Point * pt = slices->front()->start;
if(pt->symbolic) { //shared lib
std::map<string, IMG>::iterator img = images->find(pt->lib_name);
if (img == images->end()) return false;
long unsigned int offset = address - IMG_LowAddress(img->second);
if(offset == pt->offset && getCounter(address).first && pt->execount == getCounter(address).second) {
resetDependencyWindow();
control=true;
if(KnobDebugPrints.Value())
printf("[DEBUG] Started Slice: %d\n",slices->front()->slice);
std::ostringstream tracefilename;
tracefilename << KnobTraceFile.Value() << "." << slices->front()->slice;
trace.open(tracefilename.str().c_str()); //open the new one for the new slice
return true;
}
}
else {
if(pt->address == address && getCounter(address).first && pt->execount == getCounter(address).second)
{
control = true;
if(KnobDebugPrints.Value())
printf("[DEBUG] Started Slice: %d\n",slices->front()->slice);
std::ostringstream tracefilename;
tracefilename << KnobTraceFile.Value() << "." << slices->front()->slice;
trace.open(tracefilename.str().c_str()); //open the new one for the new slice
return true;
}
}
}
if(isInLimits) return true; //if this is the ending point then it should be recorded.
bbl_cnt=0;
return false;
}
VOID RecordInstructionFetch(ADDRINT iaddr){
if(KnobIFEnable.Value()){
ADDRINT phy_iaddr=iaddr;
if (KnobPhysicalAddress.Value())
phy_iaddr = getPhysicalAddr(iaddr);
if(icache!=NULL){
bool hit = icache->send(Request(phy_iaddr, Request::Type::READ),reqList);
if(hit) icache_hit++;
}
else {
reqList->push_back(Request(phy_iaddr, Request::Type::READ));
}
if(record) {
num_ifetch++;
if(reqList->empty()) filt_ifetch++;
for (std::list<Request>::iterator it = reqList->begin(); it != reqList->end(); ++it) {
assert((it->type == Request::Type::READ) && "Instruction fetch should not return a write.");
if(strcmp(KnobMode.Value().c_str(),"cpu")==0) {
if(!KnobICEnable.Value() && !KnobDCEnable.Value())
trace << bbl_cnt << " " << it->addr << " R" << std::endl;
else
trace << bbl_cnt << " " << it->addr << std::endl;
bbl_cnt=0;
} else if (strcmp(KnobMode.Value().c_str(),"datadep")==0) {
removeOld();
trace << seq_number << " READ " << it->addr << std::endl;
updateSeqNumber();
} else
trace << "0x"<< std::hex << it->addr << " R" << std::endl;
}
}
reqList->clear();
}
}
VOID CountTotalInst(ADDRINT address)
{
total++;
bbl_cnt++;
updateCounters(address);
record = checkLimits(address);
if(record) {
recorded_instr++;
recorded_instr_int++;
}
mem_filtered=true;
mem2_filtered=true;
}
//recording read/write requests to the memory
VOID RecordGeneral(VOID * ip, VOID * addr, BOOL isWrite, REG base, REG index, BOOL isfirst){
if(record) mem_req++;
if(isWrite) write_count++;
else read_count++;
UINT64 addr_req = (long)addr;
if(KnobPhysicalAddress.Value()){
UINT64 paddr = getPhysicalAddr((long)addr);
addr_req = paddr;
}
if(first!=NULL) {
bool hit;
if(!isWrite)
hit = first->send(Request(addr_req, Request::Type::READ),reqList);
else
hit = first->send(Request(addr_req, Request::Type::WRITE),reqList);
if(hit && !isWrite)
read_hit++;
else if (hit&&isWrite)
write_hit++;
if(hit && reqList->empty() && record) filtered++;
}
else {
if(isWrite) reqList->push_back(Request(addr_req,Request::Type::WRITE));
else reqList->push_back(Request(addr_req,Request::Type::READ));
}
UINT64 r_addr=0;
UINT64 w_addr=0;
bool w_check = false;
bool r_check = false;
//checking requestlist elements added in send()
//iterating through the list
for (std::list<Request>::iterator it = reqList->begin(); it != reqList->end(); ++it) {
if(it->type == Request::Type::READ) {
r_addr = it->addr;
//assert(r_addr);
r_check = true;
}
else if( it->type == Request::Type::WRITE){
w_addr = it->addr;
w_check = true;
}
}
//update filtered memory op check
if (record && !reqList->empty() && strcmp(KnobMode.Value().c_str(),"datadep")==0) {
if (isfirst)
mem_filtered = false;
else
mem2_filtered = false;
}
//recording the requests
if(record && (r_check || w_check)) {
if(strcmp(KnobMode.Value().c_str(),"cpu")==0) { //Collect CPU traces
if(!KnobDCEnable.Value() && (!KnobICEnable.Value()|| !KnobIFEnable.Value())) { //unfiltered trace
if(r_check) {
trace << bbl_cnt << " " << r_addr << " R" << std::endl;
bbl_cnt=0;
}
if(w_check) {
trace << bbl_cnt << " " << w_addr << " W" << std::endl;
bbl_cnt=0;
}
}
else {
if(!w_check && r_check) {
trace << bbl_cnt << " " << r_addr << std::endl;
}
else if( w_check && r_check )
trace << bbl_cnt << " " << r_addr << " " << w_addr << std::endl; //includes writeback address
assert(!(w_check && !r_check) && "A write should be always with a read request.");
bbl_cnt=0;
}
} else if(strcmp(KnobMode.Value().c_str(),"datadep")==0) { //Collect data dependency included CPU traces
//fprintf(trace,"dependent to reg: base: %s, index: %s\n",REG_StringShort(base).c_str(), REG_StringShort(index).c_str());
stringstream deplist;
int base_seq = getDep(base);
int index_seq = getDep(index);
if(base_seq != -1 || index_seq != -1 ) {
deplist << " :";
if(base_seq != index_seq) {
if(base_seq!=-1) deplist << " " << base_seq;
if(index_seq!=-1) deplist << " " << index_seq;
}
else {
if( base_seq!=-1)
deplist << " " << base_seq;
}
}
// printf("deplist:%s\n",deplist.str().c_str() );
if(r_check) {
removeOld();
trace << seq_number << " READ " << r_addr;
if(deplist.str().length()>1)
trace << deplist.str().c_str();
trace << std::endl;
updateSeqNumber();
}
if(w_check){
removeOld();
trace << seq_number << " WRITE " << w_addr << " : " << (seq_number -1) << std::endl;
updateSeqNumber();
}
} else { //Collect memory traces
if(r_check)
trace << "0x" << std::hex << r_addr << " R" << std::endl;
if(w_check)
trace << "0x" << std::hex << w_addr << " W" << std::endl;
}
}
reqList->clear();
}
//recording COMP
VOID RecordComp(VOID * ip, REG read_base, REG read2_base, REG read_index, REG read2_index){
if(record) {
removeOld();
stringstream deplist;
if(!(mem_filtered && mem2_filtered) || compRRegs->size()>0)
deplist << ":";
if(!mem_filtered && mem2_filtered)
deplist << " " << seq_number-1;
else if(!mem2_filtered && mem_filtered)
deplist << " " << seq_number-1;
else if(!mem_filtered && !mem2_filtered)
deplist << " " << seq_number-1 << " " << seq_number-2;
deplist << getCompDependency( read_base, read2_base, read_index, read2_index);
compRRegs->clear();
if(deplist.str().length()>1)
trace << seq_number << " COMP " << deplist.str().c_str() << std::endl;
else
trace << seq_number << " COMP" << std::endl;
updateSeqNumber();
}
}
VOID UpdateRegisterMap(VOID * ip, REG reg) {
insertDependency(REG_StringShort(reg));
}
VOID UpdateCompRegs(VOID * ip, REG reg) {
if(REG_valid(reg)) {
compRRegs->push_back(reg);
}
}
// Is called for every instruction and instruments reads and writes
VOID Instruction(INS ins, VOID *v)
{
c_total++;
ADDRINT adr = INS_Address(ins);
INS_InsertCall(ins, IPOINT_BEFORE, (AFUNPTR)CountTotalInst,IARG_UINT64, adr,
IARG_END);
INS_InsertCall(ins, IPOINT_BEFORE, (AFUNPTR)RecordInstructionFetch, IARG_UINT64, adr, IARG_END);
// Instruments memory accesses using a predicated call, i.e.
// the instrumentation is called iff the instruction will actually be executed.
//
// On the IA-32 and Intel(R) 64 architectures conditional moves and REP
// prefixed instructions appear as predicated instructions in Pin.
UINT32 memOperands = INS_MemoryOperandCount(ins);
// determine which registers are used for address generation for memory accesses
REG read_base = REG_INVALID();
REG read_index = REG_INVALID();
REG read2_base = REG_INVALID();
REG read2_index = REG_INVALID();
int read_count=0;
if(strcmp(KnobMode.Value().c_str(),"datadep")==0) {
UINT32 opCount = INS_OperandCount(ins);
for(UINT32 op = 0; op < opCount; op++) {
REG base = INS_OperandMemoryBaseReg(ins, op);
REG index = INS_OperandMemoryIndexReg(ins, op);
if(REG_valid(base) || REG_valid(index)) {
assert(read_count<2 && "Memory Operands should be less than 3. right??");
if(read_count==0) {
read_base = base;
read_index = index;
read_count=1;
}
else if( read_count==1) {
read2_base = base;
read2_index = index;
read_count++;
}
}
}
read_count=0;
}
// Iterate over each memory operand of the instruction.
for (UINT32 memOp = 0; memOp < memOperands; memOp++)
{
//determine which register is used for address generation
REG base;
REG index;
if(read_count==0) {
base = read_base;
index= read_index;
read_count++;
}
else {
index= read2_index;
base = read2_base;
}
bool isfirst = (memOp==0);
//issue recording calls for memory operations
if (INS_MemoryOperandIsRead(ins, memOp))
{
INS_InsertPredicatedCall(
ins, IPOINT_BEFORE, (AFUNPTR)RecordGeneral,
IARG_INST_PTR,
IARG_MEMORYOP_EA, memOp,
IARG_BOOL, false,
IARG_UINT32, base,
IARG_UINT32, index,
IARG_BOOL, isfirst,
IARG_END);
}
// Note that in some architectures a single memory operand can be
// both read and written (for instance incl (%eax) on IA-32)
// In that case we instrument it once for read and once for write.
if (INS_MemoryOperandIsWritten(ins, memOp))
{
INS_InsertPredicatedCall(
ins, IPOINT_BEFORE, (AFUNPTR)RecordGeneral,
IARG_INST_PTR,
IARG_MEMORYOP_EA, memOp,
IARG_BOOL, true,
IARG_UINT32, base,
IARG_UINT32, index,
IARG_BOOL, isfirst,
IARG_END);
}
}
//If instruction is not a read or write and collecting data dependency traces
//determine which registers are a dependency (except the ones used in memory accesses)
if(strcmp(KnobMode.Value().c_str(),"datadep")==0) {
for(unsigned int i=0;i<INS_MaxNumRRegs(ins);i++) {
REG reg = INS_RegR(ins,i);
INS_InsertCall(ins,IPOINT_BEFORE, (AFUNPTR)UpdateCompRegs,
IARG_INST_PTR,
IARG_UINT32, reg,
IARG_END);
}
for(unsigned int i=0;i<INS_MaxNumWRegs(ins);i++) {
REG reg = INS_RegW(ins,i);
INS_InsertCall(ins,IPOINT_BEFORE, (AFUNPTR)UpdateCompRegs,
IARG_INST_PTR,
IARG_UINT32, reg,
IARG_END);
}
INS_InsertCall(ins,IPOINT_BEFORE, (AFUNPTR)RecordComp,
IARG_INST_PTR,
IARG_UINT32, read_base,
IARG_UINT32, read2_base,
IARG_UINT32, read_index,
IARG_UINT32, read2_index,
IARG_END);
for(unsigned int i =0;i<INS_MaxNumWRegs(ins);i++) {
REG reg = INS_RegW(ins,i);
INS_InsertPredicatedCall(
ins, IPOINT_BEFORE, (AFUNPTR)UpdateRegisterMap,
IARG_INST_PTR,
IARG_UINT32, reg,
IARG_END);
}
}
}
VOID Fini(INT32 code, VOID *v)
{
finish();
}
/* ===================================================================== */
/* Print Help Message */
/* ===================================================================== */
INT32 Usage()
{
PIN_ERROR( "This Pintool prints a trace of memory accesses\n"
+ KNOB_BASE::StringKnobSummary() + "\n");
return -1;
}
//returns the first slice id.
int setSliceLimits(){
if(!KnobFastOption.Value() && strcmp(KnobCoverage.Value().c_str(),"")==0) return 0;
Parser * parser = new Parser();
parser->parse(KnobPinPoints.Value());
PSlice * first = NULL;
if(KnobFastOption.Value()) {
first = parser->getFastPoint();
if(first==NULL) {
printf("Cannot find any slices, try changing the interval size.\n");
exit(0);
}
slices->push_back(first);
}
else if (strcmp(KnobCoverage.Value().c_str(),"")!=0) {
slices = parser->slices;
num_slices = slices->size();
if(num_slices==0) {
printf("Cannot find any slices, try changing the interval size.\n");
exit(0);
}
if(KnobDebugPrints.Value())
printf("[DEBUG] Content:\n%s\n",parser->dump_content().c_str());
first = slices->front();
}
initializeCounters();
delete parser;
return first ? first->slice : 0;
}
VOID Image(IMG img, VOID * v)
{
images->insert(make_pair(IMG_Name(img),img));
}
/* ===================================================================== */
/* Main */
/* ===================================================================== */
int main(int argc, char *argv[])
{
if(PIN_Init(argc, argv)) return Usage();
IMG_AddInstrumentFunction(Image, 0);
Config cfg(KnobConfigFile.Value().c_str());
control=false; //this is used to check if the instrumented instruction is in the slice for recording the traces.
printf("isize: %ld\n",KnobISize.Value());
if(KnobPhysicalAddress.Value()) {
pagemap = fopen("/proc/self/pagemap", "rb");
}
if(!KnobFastOption.Value() && strcmp(KnobCoverage.Value().c_str(),"")==0) {
full_sim=true;
}
int slice_id=0;
if(!full_sim && strcmp(KnobPinPoints.Value().c_str(),"")!=0) {
slice_id = setSliceLimits();
}
std::ostringstream tracefilename;
if(!slices->empty()){
tracefilename<<KnobTraceFile.Value() << "." << slice_id ;
}
else{ //if we are running the full program
tracefilename <<KnobTraceFile.Value();
trace.open(tracefilename.str().c_str());
}
std::list<CacheParams *> * c_list = cfg.get_caches();
if(c_list->empty()) {
first=NULL;
icache=NULL;
}
else {
Cache * cur = NULL;
for(std::list<CacheParams *>::iterator it = c_list->begin();it!=c_list->end();it++) {
bool isItIC = false;
int csize = (*it)->get_size();
int cassoc = (*it)->get_assoc();
int cblock = (*it)->get_block_size();
Cache::Level lvl;
//command line arguments override the config file values.
switch ((*it)->get_level()) {
case 1:
lvl = Cache::Level::L1;
if(KnobL1Size.Value()>0) csize = 2<<KnobL1Size.Value();
if(KnobL1Assoc.Value()>0) cassoc = 2<<KnobL1Assoc.Value();
if(KnobL1BlockSize.Value()>0) cblock = (2<<KnobL1BlockSize.Value());
break;
case 2:
lvl = Cache::Level::L2;
if(KnobL2Size.Value()>0) csize = (2<<KnobL2Size.Value());
if(KnobL2Assoc.Value()>0) cassoc = (2<<KnobL2Assoc.Value());
if(KnobL2BlockSize.Value()>0) cblock = (2<<KnobL2BlockSize.Value());
break;
case 3:
lvl = Cache::Level::L3;
if(KnobL3Size.Value()>0) csize = (2<<KnobL3Size.Value());
if(KnobL3Assoc.Value()>0) cassoc = (2<<KnobL3Assoc.Value());
if(KnobL3BlockSize.Value()>0) cblock =(2<<KnobL3BlockSize.Value());
break;
case -1:
lvl = Cache::Level::ICache;
isItIC = true;
if(KnobICSize.Value()>0) csize = (2<<KnobICSize.Value());
if(KnobICAssoc.Value()>0) cassoc = (2<<KnobICAssoc.Value());
if(KnobICBlockSize.Value()>0) cblock = (2<<KnobICBlockSize.Value());
break;
default:
printf("A caches level can't be out of the range [1,3]. (-1 for ICache)\n");
exit(0);
}
if(isItIC) {
icache = new Cache(csize,cassoc,cblock,lvl);
//icache->set_next_cache(NULL);
//icache->concatlower(NULL);
icache->set_last_level();
}
else {
Cache * c= new Cache(csize,cassoc,cblock,lvl);
if(cur!=NULL) {
//cur->set_next_cache(c);
cur->concatlower(c);
}
else {
c->set_first_level();
first = c;
}
caches->push_back(c);
cur = c;
}
}
cur->set_last_level();
}
if(!KnobICEnable.Value()) {
icache = NULL;
}
if(!KnobDCEnable.Value()) {
first = NULL;
}
if(KnobDebugPrints.Value()) {
for (auto debug : *caches) {
printf("[DEBUG] Level: %d, next_cache: %lu, is_last_level: %d is_first_level: %d\n",debug->level, debug->higher_cache.size(),
debug->is_llc(),debug->is_first());
}
}
INS_AddInstrumentFunction(Instruction, 0);
PIN_AddFiniFunction(Fini, 0);
// Never returns
PIN_StartProgram();
return 0;
}
| 36.227222 | 155 | 0.609824 |
50ad8d9aaf234fe34a638dc709ead023c6ee48dd | 6,631 | cc | C++ | src/image-utils.cc | kyawakyawa/image-utils | af1ab717da7934555f701067f1d69077a69c35b0 | [
"MIT"
] | null | null | null | src/image-utils.cc | kyawakyawa/image-utils | af1ab717da7934555f701067f1d69077a69c35b0 | [
"MIT"
] | null | null | null | src/image-utils.cc | kyawakyawa/image-utils | af1ab717da7934555f701067f1d69077a69c35b0 | [
"MIT"
] | null | null | null | /*
MIT License
Copyright (c) 2020 kyawakyawa
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 "image-utils.h"
#include <math.h>
#include <algorithm>
#include <iostream>
#ifdef __clang__
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Weverything"
#endif
#if defined(__cplusplus) && __cplusplus >= 201703L && defined(__has_include)
#if __has_include(<filesystem>)
#define GHC_USE_STD_FS
#include <filesystem>
namespace fs = std::filesystem;
#endif
#endif
#ifndef GHC_USE_STD_FS
#include <ghc/filesystem.hpp>
namespace fs = ghc::filesystem;
#endif
#include "stb_image.h"
#include "stb_image_write.h"
#ifdef __clang__
#pragma clang diagnostic pop
#endif
namespace image_utils {
template <typename T>
static T sRGBToLiner(const T c_srgb) {
T c_liner;
if (c_srgb <= static_cast<T>(0.04045)) {
c_liner = c_srgb / static_cast<T>(12.92);
} else {
const T a = static_cast<T>(0.055);
c_liner =
std::pow((c_srgb + a) / (static_cast<T>(1.0) + a), static_cast<T>(2.4));
}
return c_liner;
}
template <typename T>
static T LinerTosRGB(const T c_liner) {
T c_srgb;
if (c_liner <= static_cast<T>(0.0031308)) {
c_srgb = static_cast<T>(12.92) * c_liner;
} else {
const T a = static_cast<T>(0.055);
c_srgb = std::pow((static_cast<T>(1.0) + a) * c_liner,
static_cast<T>(1.0 / 2.4)) -
a;
}
return c_srgb;
}
template <typename T>
static std::tuple<std::vector<T>, size_t, size_t, size_t> LoadImage(
const std::string& filename) {
// TODO : EXR file
int tmp_w = 0;
int tmp_h = 0;
int tmp_c = 0;
float* pixelf = stbi_loadf(filename.c_str(), &tmp_w, &tmp_h, &tmp_c, 0);
const size_t width = (pixelf != nullptr) ? static_cast<size_t>(tmp_w) : 0;
const size_t height = (pixelf != nullptr) ? static_cast<size_t>(tmp_h) : 0;
const size_t channel = (pixelf != nullptr) ? static_cast<size_t>(tmp_c) : 0;
std::vector<T> ret(width * height * channel);
for (size_t i = 0; i < width * height * channel; i++) {
ret[i] = static_cast<T>(pixelf[i]);
}
stbi_image_free(pixelf);
return std::make_tuple(ret, width, height, channel);
}
template <typename T>
std::tuple<std::vector<T>, size_t, size_t, size_t> LoadAndConvertImage(
const std::string& filename, ConvertOption convert_option) {
auto ret = LoadImage<T>(filename);
std::vector<T>& pixels = std::get<0>(ret);
const size_t width = std::get<1>(ret);
const size_t height = std::get<2>(ret);
const size_t channel = std::get<3>(ret);
const fs::path filepath = filename;
const std::string file_extension = filepath.extension();
const bool is_hdr = (file_extension == ".hdr" || file_extension == ".HDR" ||
file_extension == ".exr" || file_extension == ".EXR");
if (convert_option != ConvertOption::FORCE_NO_CONVERT &&
(!is_hdr || convert_option == ConvertOption::FORCE_CONVERT)) {
std::cerr << "Start sRGBToLiner" << std::endl;
for (size_t i = 0; i < width * height; i++) {
for (size_t c = 0; c < std::min<size_t>(channel, 3); c++) {
pixels[i * channel + c] = sRGBToLiner(pixels[i * channel + c]);
}
}
std::cerr << "End sRGBToLiner" << std::endl;
}
return ret;
}
template std::tuple<std::vector<float>, size_t, size_t, size_t>
LoadAndConvertImage(const std::string& filename, ConvertOption convert_option);
template std::tuple<std::vector<double>, size_t, size_t, size_t>
LoadAndConvertImage(const std::string& filename, ConvertOption convert_option);
template <typename T>
bool WritePNG(std::vector<T> pixels, const size_t width, const size_t height,
const size_t channel, const std::string& filename,
ConvertOption convert_option) {
const fs::path filepath = filename;
const std::string file_extension = filepath.extension();
if (file_extension != ".png" && file_extension != ".PNG") {
std::cerr << "warning! the file extension is not \"png\"" << std::endl;
}
if (pixels.size() == 0 || pixels.size() != width * height * channel) {
std::cerr << "the image data is broken" << std::endl;
return false;
}
if (convert_option != ConvertOption::FORCE_NO_CONVERT) {
std::cerr << "Start LinerTosRGB" << std::endl;
for (size_t i = 0; i < width * height; i++) {
for (size_t c = 0; c < std::min<size_t>(channel, 3); c++) {
pixels[i * channel + c] = LinerTosRGB(pixels[i * channel + c]);
}
}
std::cerr << "Finish LinerTosRGB" << std::endl;
}
std::vector<unsigned char> pixel8(width * height * channel);
for (size_t i = 0; i < width * height * channel; i++) {
pixel8[i] = static_cast<unsigned char>(std::max(
static_cast<T>(0.0),
std::min(static_cast<T>(255.0), pixels[i] * static_cast<T>(256.0))));
}
int ret = stbi_write_png(filename.c_str(), int(width), int(height),
int(channel), pixel8.data(), int(width * channel));
if (!ret) {
std::cerr << "faild save image" << std::endl;
return false;
}
std::cerr << "write png file [ " << filename << " ]" << std::endl;
return true;
}
template bool WritePNG(std::vector<float> pixels, const size_t width,
const size_t height, const size_t channel,
const std::string& filename,
ConvertOption convert_option);
template bool WritePNG(std::vector<double> pixels, const size_t width,
const size_t height, const size_t channel,
const std::string& filename,
ConvertOption convert_option);
} // namespace image_utils
| 32.346341 | 80 | 0.655708 |
27084f8412eae86805d019686bfd70a04db14971 | 6,627 | hpp | C++ | dof-mgr/src/Panzer_IntrepidFieldPattern.hpp | hillyuan/Panzer | 13ece3ea4c145c4d7b6339e3ad6332a501932ea8 | [
"BSD-3-Clause"
] | 1 | 2022-03-22T03:49:50.000Z | 2022-03-22T03:49:50.000Z | dof-mgr/src/Panzer_IntrepidFieldPattern.hpp | hillyuan/Panzer | 13ece3ea4c145c4d7b6339e3ad6332a501932ea8 | [
"BSD-3-Clause"
] | null | null | null | dof-mgr/src/Panzer_IntrepidFieldPattern.hpp | hillyuan/Panzer | 13ece3ea4c145c4d7b6339e3ad6332a501932ea8 | [
"BSD-3-Clause"
] | null | null | null | // @HEADER
// ***********************************************************************
//
// Panzer: A partial differential equation assembly
// engine for strongly coupled complex multiphysics systems
// Copyright (2011) Sandia Corporation
//
// Under the terms of Contract DE-AC04-94AL85000 with Sandia Corporation,
// the U.S. Government retains certain rights in this software.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met:
//
// 1. Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
//
// 2. Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in the
// documentation and/or other materials provided with the distribution.
//
// 3. Neither the name of the Corporation nor the names of the
// contributors may be used to endorse or promote products derived from
// this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY SANDIA CORPORATION "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 SANDIA CORPORATION OR THE
// 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.
//
// Questions? Contact Roger P. Pawlowski (rppawlo@sandia.gov) and
// Eric C. Cyr (eccyr@sandia.gov)
// ***********************************************************************
// @HEADER
#ifndef __Panzer_IntrepidFieldPattern_hpp__
#define __Panzer_IntrepidFieldPattern_hpp__
#include "Panzer_FieldPattern.hpp"
// Trilinos includes
#include "Kokkos_Core.hpp"
#include "Kokkos_DynRankView.hpp"
#include "Intrepid2_Basis.hpp"
#include "Phalanx_KokkosDeviceTypes.hpp"
#include "Teuchos_RCP.hpp"
#include <set>
namespace panzer {
/** This is a derived class that specializes based
* on a single intrepid basis function.
*/
class Intrepid2FieldPattern : public FieldPattern {
public:
Intrepid2FieldPattern(const Teuchos::RCP< Intrepid2::Basis<PHX::Device,double,double> > &intrepidBasis);
virtual int getSubcellCount(int dim) const;
virtual const std::vector<int> & getSubcellIndices(int dim, int cellIndex) const;
virtual int getDimension() const;
virtual shards::CellTopology getCellTopology() const;
virtual void getSubcellClosureIndices(int dim,int cellIndex,std::vector<int> & indices) const;
// static functions for examining shards objects
/** For a given sub cell find the set of sub cells at all dimensions contained
* internally. This is inclusive, so that (dim,subCell) will be in the set.
*
* \param[in] cellTopo Parent cell topology being used.
* \param[in] dim Dimension of sub cell
* \param[in] subCell Ordinal of sub cell at specified dimension
* \param[in,out] closure Set of sub cells associated with specified sub cell.
*
* \note Sub cell dimension and ordinals are inserted into <code>closure</code>.
* Previous information will not be removed.
*/
static void buildSubcellClosure(const shards::CellTopology & cellTopo,unsigned dim,unsigned subCell,
std::set<std::pair<unsigned,unsigned> > & closure);
/** Search a cell topology for sub cells containing a specfic set of nodes.
* This is a downward search (inclusive) from a user specified dimension.
*
* \param[in] cellTopo Parent cell topology being used.
* \param[in] dim Dimension of sub cell
* \param[in] nodes Nodes forming the super set
* \param[in,out] subCells Specific sub cells containing the nodes.
*
* \note Sub cell dimension and ordinals are inserted into <code>subCells</code>.
* Previous information will not be removed.
*/
static void findContainedSubcells(const shards::CellTopology & cellTopo,unsigned dim,
const std::vector<unsigned> & nodes,
std::set<std::pair<unsigned,unsigned> > & subCells);
/** Get the set of nodes making up the user specified sub cells.
*
* \param[in] cellTopo Parent cell topology being used.
* \param[in] dim Dimension of sub cell
* \param[in] subCell Ordinal of sub cell at specified dimension
* \param[in,out] nodes Nodes associated with sub cell.
*/
static void getSubcellNodes(const shards::CellTopology & cellTopo,unsigned dim,unsigned subCell,
std::vector<unsigned> & nodes);
/** \brief Does this field pattern support interpolatory coordinates?
*
* If this method returns true then <code>getInterpolatoryCoordinates</code> will
* succeed, otherwise it will throw.
*
* \returns True if this pattern supports interpolatory coordinates.
*/
bool supportsInterpolatoryCoordinates() const;
/** Get the local coordinates for this field. This is independent of element
* locations.
*
* \param[in,out] coords Coordinates associated with this field type.
*/
void getInterpolatoryCoordinates(Kokkos::DynRankView<double,PHX::Device> & coords) const;
/** Get the local coordinates for this field.
*
* \param[in] cellVertices Coordinates associated with this field type.
* \param[in,out] coords Coordinates associated with this field type.
*/
void getInterpolatoryCoordinates(const Kokkos::DynRankView<double,PHX::Device> & cellVertices,
Kokkos::DynRankView<double,PHX::Device> & coords) const;
/// Returns the underlying Intrepid2::Basis object
Teuchos::RCP< Intrepid2::Basis<PHX::Device,double,double> > getIntrepidBasis() const;
protected:
Teuchos::RCP< Intrepid2::Basis<PHX::Device,double,double> > intrepidBasis_;
//mutable std::vector<int> subcellIndices_;
mutable std::vector<std::vector<std::vector<int> > > subcellIndicies_;
std::vector<int> empty_;
};
}
#endif
| 43.598684 | 108 | 0.689 |
270aff09f7b49dba066873ece2b73065be1fbf58 | 13,021 | hpp | C++ | include/boost/gil/io/device.hpp | sdebionne/gil-reformated | 7065d600d7f84d9ef2ed4df9862c596ff7e8a8c2 | [
"BSL-1.0"
] | null | null | null | include/boost/gil/io/device.hpp | sdebionne/gil-reformated | 7065d600d7f84d9ef2ed4df9862c596ff7e8a8c2 | [
"BSL-1.0"
] | null | null | null | include/boost/gil/io/device.hpp | sdebionne/gil-reformated | 7065d600d7f84d9ef2ed4df9862c596ff7e8a8c2 | [
"BSL-1.0"
] | null | null | null | //
// Copyright 2007-2012 Christian Henning, Andreas Pokorny
//
// Distributed under the Boost Software License, Version 1.0
// See accompanying file LICENSE_1_0.txt or copy at
// http://www.boost.org/LICENSE_1_0.txt
//
#ifndef BOOST_GIL_IO_DEVICE_HPP
#define BOOST_GIL_IO_DEVICE_HPP
#include <boost/gil/detail/mp11.hpp>
#include <boost/gil/io/base.hpp>
#include <cstdio>
#include <memory>
#include <type_traits>
namespace boost {
namespace gil {
#if BOOST_WORKAROUND(BOOST_MSVC, >= 1400)
#pragma warning(push)
#pragma warning(disable : 4512) // assignment operator could not be generated
#endif
namespace detail {
template <typename T> struct buff_item {
static const unsigned int size = sizeof(T);
};
template <> struct buff_item<void> { static const unsigned int size = 1; };
/*!
* Implements the IODevice concept c.f. to \ref IODevice required by Image
* libraries like libjpeg and libpng.
*
* \todo switch to a sane interface as soon as there is
* something good in boost. I.E. the IOChains library
* would fit very well here.
*
* This implementation is based on FILE*.
*/
template <typename FormatTag> class file_stream_device {
public:
using format_tag_t = FormatTag;
public:
/// Used to overload the constructor.
struct read_tag {};
struct write_tag {};
///
/// Constructor
///
file_stream_device(const std::string &file_name, read_tag tag = read_tag())
: file_stream_device(file_name.c_str(), tag) {}
///
/// Constructor
///
file_stream_device(const char *file_name, read_tag = read_tag()) {
FILE *file = nullptr;
io_error_if((file = fopen(file_name, "rb")) == nullptr,
"file_stream_device: failed to open file for reading");
_file = file_ptr_t(file, file_deleter);
}
///
/// Constructor
///
file_stream_device(const std::string &file_name, write_tag tag)
: file_stream_device(file_name.c_str(), tag) {}
///
/// Constructor
///
file_stream_device(const char *file_name, write_tag) {
FILE *file = nullptr;
io_error_if((file = fopen(file_name, "wb")) == nullptr,
"file_stream_device: failed to open file for writing");
_file = file_ptr_t(file, file_deleter);
}
///
/// Constructor
///
file_stream_device(FILE *file) : _file(file, file_deleter) {}
FILE *get() { return _file.get(); }
const FILE *get() const { return _file.get(); }
int getc_unchecked() { return std::getc(get()); }
char getc() {
int ch;
io_error_if((ch = std::getc(get())) == EOF,
"file_stream_device: unexpected EOF");
return (char)ch;
}
///@todo: change byte_t* to void*
std::size_t read(byte_t *data, std::size_t count) {
std::size_t num_elements = fread(data, 1, static_cast<int>(count), get());
///@todo: add compiler symbol to turn error checking on and off.
io_error_if(ferror(get()), "file_stream_device: file read error");
// libjpeg sometimes reads blocks in 4096 bytes even when the file is
// smaller than that. return value indicates how much was actually read
// returning less than "count" is not an error
return num_elements;
}
/// Reads array
template <typename T, int N> void read(T (&buf)[N]) {
io_error_if(read(buf, N) < N, "file_stream_device: file read error");
}
/// Reads byte
uint8_t read_uint8() {
byte_t m[1];
read(m);
return m[0];
}
/// Reads 16 bit little endian integer
uint16_t read_uint16() {
byte_t m[2];
read(m);
return (m[1] << 8) | m[0];
}
/// Reads 32 bit little endian integer
uint32_t read_uint32() {
byte_t m[4];
read(m);
return (m[3] << 24) | (m[2] << 16) | (m[1] << 8) | m[0];
}
/// Writes number of elements from a buffer
template <typename T> std::size_t write(const T *buf, std::size_t count) {
std::size_t num_elements = fwrite(buf, buff_item<T>::size, count, get());
// return value indicates how much was actually written
// returning less than "count" is not an error
return num_elements;
}
/// Writes array
template <typename T, std::size_t N> void write(const T (&buf)[N]) {
io_error_if(write(buf, N) < N, "file_stream_device: file write error");
return;
}
/// Writes byte
void write_uint8(uint8_t x) {
byte_t m[1] = {x};
write(m);
}
/// Writes 16 bit little endian integer
void write_uint16(uint16_t x) {
byte_t m[2];
m[0] = byte_t(x >> 0);
m[1] = byte_t(x >> 8);
write(m);
}
/// Writes 32 bit little endian integer
void write_uint32(uint32_t x) {
byte_t m[4];
m[0] = byte_t(x >> 0);
m[1] = byte_t(x >> 8);
m[2] = byte_t(x >> 16);
m[3] = byte_t(x >> 24);
write(m);
}
void seek(long count, int whence = SEEK_SET) {
io_error_if(fseek(get(), count, whence) != 0,
"file_stream_device: file seek error");
}
long int tell() {
long int pos = ftell(get());
io_error_if(pos == -1L, "file_stream_device: file position error");
return pos;
}
void flush() { fflush(get()); }
/// Prints formatted ASCII text
void print_line(const std::string &line) {
std::size_t num_elements =
fwrite(line.c_str(), sizeof(char), line.size(), get());
io_error_if(num_elements < line.size(),
"file_stream_device: line print error");
}
int error() { return ferror(get()); }
private:
static void file_deleter(FILE *file) {
if (file) {
fclose(file);
}
}
private:
using file_ptr_t = std::shared_ptr<FILE>;
file_ptr_t _file;
};
/**
* Input stream device
*/
template <typename FormatTag> class istream_device {
public:
istream_device(std::istream &in) : _in(in) {
// does the file exists?
io_error_if(!in, "istream_device: Stream is not valid.");
}
int getc_unchecked() { return _in.get(); }
char getc() {
int ch;
io_error_if((ch = _in.get()) == EOF, "istream_device: unexpected EOF");
return (char)ch;
}
std::size_t read(byte_t *data, std::size_t count) {
std::streamsize cr = 0;
do {
_in.peek();
std::streamsize c = _in.readsome(reinterpret_cast<char *>(data),
static_cast<std::streamsize>(count));
count -= static_cast<std::size_t>(c);
data += c;
cr += c;
} while (count && _in);
return static_cast<std::size_t>(cr);
}
/// Reads array
template <typename T, int N> void read(T (&buf)[N]) { read(buf, N); }
/// Reads byte
uint8_t read_uint8() {
byte_t m[1];
read(m);
return m[0];
}
/// Reads 16 bit little endian integer
uint16_t read_uint16() {
byte_t m[2];
read(m);
return (m[1] << 8) | m[0];
}
/// Reads 32 bit little endian integer
uint32_t read_uint32() {
byte_t m[4];
read(m);
return (m[3] << 24) | (m[2] << 16) | (m[1] << 8) | m[0];
}
void seek(long count, int whence = SEEK_SET) {
_in.seekg(count, whence == SEEK_SET ? std::ios::beg
: (whence == SEEK_CUR ? std::ios::cur
: std::ios::end));
}
void write(const byte_t *, std::size_t) {
io_error("istream_device: Bad io error.");
}
void flush() {}
private:
std::istream &_in;
};
/**
* Output stream device
*/
template <typename FormatTag> class ostream_device {
public:
ostream_device(std::ostream &out) : _out(out) {}
std::size_t read(byte_t *, std::size_t) {
io_error("ostream_device: Bad io error.");
return 0;
}
void seek(long count, int whence) {
_out.seekp(count,
whence == SEEK_SET
? std::ios::beg
: (whence == SEEK_CUR ? std::ios::cur : std::ios::end));
}
void write(const byte_t *data, std::size_t count) {
_out.write(reinterpret_cast<char const *>(data),
static_cast<std::streamsize>(count));
}
/// Writes array
template <typename T, std::size_t N> void write(const T (&buf)[N]) {
write(buf, N);
}
/// Writes byte
void write_uint8(uint8_t x) {
byte_t m[1] = {x};
write(m);
}
/// Writes 16 bit little endian integer
void write_uint16(uint16_t x) {
byte_t m[2];
m[0] = byte_t(x >> 0);
m[1] = byte_t(x >> 8);
write(m);
}
/// Writes 32 bit little endian integer
void write_uint32(uint32_t x) {
byte_t m[4];
m[0] = byte_t(x >> 0);
m[1] = byte_t(x >> 8);
m[2] = byte_t(x >> 16);
m[3] = byte_t(x >> 24);
write(m);
}
void flush() { _out << std::flush; }
/// Prints formatted ASCII text
void print_line(const std::string &line) { _out << line; }
private:
std::ostream &_out;
};
/**
* Metafunction to detect input devices.
* Should be replaced by an external facility in the future.
*/
template <typename IODevice> struct is_input_device : std::false_type {};
template <typename FormatTag>
struct is_input_device<file_stream_device<FormatTag>> : std::true_type {};
template <typename FormatTag>
struct is_input_device<istream_device<FormatTag>> : std::true_type {};
template <typename FormatTag, typename T, typename D = void>
struct is_adaptable_input_device : std::false_type {};
template <typename FormatTag, typename T>
struct is_adaptable_input_device<
FormatTag, T,
typename std::enable_if<
mp11::mp_or<std::is_base_of<std::istream, T>,
std::is_same<std::istream, T>>::value>::type>
: std::true_type {
using device_type = istream_device<FormatTag>;
};
template <typename FormatTag>
struct is_adaptable_input_device<FormatTag, FILE *, void> : std::true_type {
using device_type = file_stream_device<FormatTag>;
};
///
/// Metafunction to decide if a given type is an acceptable read device type.
///
template <typename FormatTag, typename T, typename D = void>
struct is_read_device : std::false_type {};
template <typename FormatTag, typename T>
struct is_read_device<
FormatTag, T,
typename std::enable_if<
mp11::mp_or<is_input_device<FormatTag>,
is_adaptable_input_device<FormatTag, T>>::value>::type>
: std::true_type {};
/**
* Metafunction to detect output devices.
* Should be replaced by an external facility in the future.
*/
template <typename IODevice> struct is_output_device : std::false_type {};
template <typename FormatTag>
struct is_output_device<file_stream_device<FormatTag>> : std::true_type {};
template <typename FormatTag>
struct is_output_device<ostream_device<FormatTag>> : std::true_type {};
template <typename FormatTag, typename IODevice, typename D = void>
struct is_adaptable_output_device : std::false_type {};
template <typename FormatTag, typename T>
struct is_adaptable_output_device<
FormatTag, T,
typename std::enable_if<
mp11::mp_or<std::is_base_of<std::ostream, T>,
std::is_same<std::ostream, T>>::value>::type>
: std::true_type {
using device_type = ostream_device<FormatTag>;
};
template <typename FormatTag>
struct is_adaptable_output_device<FormatTag, FILE *, void> : std::true_type {
using device_type = file_stream_device<FormatTag>;
};
///
/// Metafunction to decide if a given type is an acceptable read device type.
///
template <typename FormatTag, typename T, typename D = void>
struct is_write_device : std::false_type {};
template <typename FormatTag, typename T>
struct is_write_device<
FormatTag, T,
typename std::enable_if<
mp11::mp_or<is_output_device<FormatTag>,
is_adaptable_output_device<FormatTag, T>>::value>::type>
: std::true_type {};
} // namespace detail
template <typename Device, typename FormatTag> class scanline_reader;
template <typename Device, typename FormatTag, typename ConversionPolicy>
class reader;
template <typename Device, typename FormatTag, typename Log = no_log>
class writer;
template <typename Device, typename FormatTag> class dynamic_image_reader;
template <typename Device, typename FormatTag, typename Log = no_log>
class dynamic_image_writer;
namespace detail {
template <typename T> struct is_reader : std::false_type {};
template <typename Device, typename FormatTag, typename ConversionPolicy>
struct is_reader<reader<Device, FormatTag, ConversionPolicy>> : std::true_type {
};
template <typename T> struct is_dynamic_image_reader : std::false_type {};
template <typename Device, typename FormatTag>
struct is_dynamic_image_reader<dynamic_image_reader<Device, FormatTag>>
: std::true_type {};
template <typename T> struct is_writer : std::false_type {};
template <typename Device, typename FormatTag>
struct is_writer<writer<Device, FormatTag>> : std::true_type {};
template <typename T> struct is_dynamic_image_writer : std::false_type {};
template <typename Device, typename FormatTag>
struct is_dynamic_image_writer<dynamic_image_writer<Device, FormatTag>>
: std::true_type {};
} // namespace detail
#if BOOST_WORKAROUND(BOOST_MSVC, >= 1400)
#pragma warning(pop)
#endif
} // namespace gil
} // namespace boost
#endif
| 25.531373 | 80 | 0.651179 |
270e8b3df3b7bd8b52e67cb3eea40f08be838f4c | 1,135 | hpp | C++ | e-Paper/src/WiFiHandler.hpp | PDA-UR/Dumb-e-Paper | 99aecce5fbcb64d32b7e47809df393e0e2e7fab4 | [
"MIT"
] | 2 | 2019-01-30T13:48:14.000Z | 2021-10-30T16:11:03.000Z | e-Paper/src/WiFiHandler.hpp | PDA-UR/Dumb-e-Paper | 99aecce5fbcb64d32b7e47809df393e0e2e7fab4 | [
"MIT"
] | null | null | null | e-Paper/src/WiFiHandler.hpp | PDA-UR/Dumb-e-Paper | 99aecce5fbcb64d32b7e47809df393e0e2e7fab4 | [
"MIT"
] | 2 | 2018-02-14T12:45:59.000Z | 2021-12-17T20:57:02.000Z | #ifndef __WIFIHANDLER_H_INCLUDED__
#define __WIFIHANDLER_H_INCLUDED__
/**
* @defgroup WiFi Handler
*/
/** @addtogroup WiFi Handler */
/*@{*/
#include "main.hpp"
#include <WiFi.h>
#include <WiFiMulti.h>
/**
* @brief Could be anything but must also be changed in python script
*/
const int PORT = 1516;
enum class WiFiStatus
{
WIFI_SUCCESS,
WIFI_ERROR,
WIFI_WAIT,
SHOW_PICTURE_01,
SHOW_PICTURE_02,
CLEAR_SCREEN
};
class WiFiHandler
{
public:
/**
* @brief Start WiFi connection
*
* @param id ssid to connect
* @param password for network
* @return true if WiFi could connect
*/
static bool init(String id, String password);
/**
* @brief Receive data from WiFi and write to buffer
*
* @param buffer gets WiFi data
* @param le buffer length
* @return WiFiStatus
*/
static WiFiStatus handle(byte *buffer, int le);
/**
* @brief Sends "OK" to server, to receive new data
*/
static void requestDataChunk();
private:
static const byte O;
static const byte K;
static char *ip;
};
/*@}*/
#endif
| 17.461538 | 69 | 0.629956 |
2716f46542abf6879e15307467bf50c0275d7865 | 1,125 | cpp | C++ | t_rex.cpp | alexycruz1/proyecto2 | e4817969d610473d02f2b4c68c69d629ef93bef4 | [
"MIT"
] | null | null | null | t_rex.cpp | alexycruz1/proyecto2 | e4817969d610473d02f2b4c68c69d629ef93bef4 | [
"MIT"
] | null | null | null | t_rex.cpp | alexycruz1/proyecto2 | e4817969d610473d02f2b4c68c69d629ef93bef4 | [
"MIT"
] | null | null | null | #include "dinosaurio.h"
#include "t_rex.h"
#include <string>
#include <sstream>
using std::string;
using std::stringstream;
t_rex::t_rex(string nombre, char genero, int peso, int altura, int esperanza_vida, string era, string territorio, int hambre, int edad):dinosaurio(nombre,genero,peso,altura,esperanza_vida,era,territorio, hambre, edad){}
string t_rex::toString()const{
stringstream temp;
temp<<genero;
temp<<" ";
temp<<peso;
temp<<" ";
temp<<altura;
temp<<" ";
temp<<esperanza_vida;
temp<<" ";
temp<<era;
temp<<" ";
temp<<territorio;
temp<<" ";
temp<<hambre;
temp<<" ";
temp<<edad;
temp<<" ";
temp<<nombre;
temp;
return temp.str();
}
void t_rex::comer(int& comidon){
if(hambre<20){
comidon-=3;
hambre+=3;
}
}
void t_rex::hambrita(){
hambre-=7;
}
bool t_rex::morir(){
if(esperanza_vida==edad || hambre<=0){
return true;
}else{
return false;
}
}
void t_rex::cumple(){
edad+=1;
}
void t_rex::paga(int& dinero,int& semana){
if(semana % 4 == 0){
dinero += 3000;
}
} | 18.75 | 219 | 0.587556 |
271977f61e3e2b952a3d340389cb5a28802382f2 | 2,378 | cpp | C++ | src/graphics/backend/depth_pass.cpp | NotAPenguin0/Andromeda | 69ac0e448dbc7d5ba8f5915177f333bd8cd1a1b4 | [
"MIT"
] | 7 | 2020-04-28T11:01:55.000Z | 2022-02-22T09:59:33.000Z | src/graphics/backend/depth_pass.cpp | NotAPenguin0/Andromeda | 69ac0e448dbc7d5ba8f5915177f333bd8cd1a1b4 | [
"MIT"
] | 2 | 2021-09-03T12:58:06.000Z | 2021-09-20T20:07:33.000Z | src/graphics/backend/depth_pass.cpp | NotAPenguin0/Andromeda | 69ac0e448dbc7d5ba8f5915177f333bd8cd1a1b4 | [
"MIT"
] | 1 | 2021-09-03T12:56:25.000Z | 2021-09-03T12:56:25.000Z | #include <andromeda/graphics/backend/depth_pass.hpp>
#include <andromeda/graphics/backend/mesh_draw.hpp>
namespace andromeda::gfx::backend {
void create_depth_only_pipeline(gfx::Context& ctx, VkSampleCountFlagBits samples, float sample_ratio) {
ph::PipelineCreateInfo pci = ph::PipelineBuilder::create(ctx, "depth_only")
.add_shader("data/shaders/depth.vert.spv", "main", ph::ShaderStage::Vertex)
.add_vertex_input(0)
// Note that not all these attributes will be used, but they are specified because the vertex size is deduced from them
.add_vertex_attribute(0, 0, VK_FORMAT_R32G32B32_SFLOAT) // iPos
.add_vertex_attribute(0, 1, VK_FORMAT_R32G32B32_SFLOAT) // iNormal
.add_vertex_attribute(0, 2, VK_FORMAT_R32G32B32_SFLOAT) // iTangent
.add_vertex_attribute(0, 3, VK_FORMAT_R32G32_SFLOAT) // iUV
.add_dynamic_state(VK_DYNAMIC_STATE_SCISSOR)
.add_dynamic_state(VK_DYNAMIC_STATE_VIEWPORT)
.set_depth_test(true)
.set_depth_write(true)
.set_cull_mode(VK_CULL_MODE_BACK_BIT)
.set_samples(samples)
.set_sample_shading(sample_ratio)
.reflect()
.get();
ctx.create_named_pipeline(std::move(pci));
}
ph::Pass build_depth_pass(gfx::Context& ctx, ph::InFlightContext& ifc, std::string_view target, gfx::SceneDescription const& scene, ph::BufferSlice camera, ph::BufferSlice transforms) {
ph::Pass pass = ph::PassBuilder::create("fwd_plus_depth")
.add_depth_attachment(target, ph::LoadOp::Clear, {.depth_stencil = {.depth = 1.0f, .stencil = 0}})
.execute([&ctx, &ifc, &scene, camera, transforms](ph::CommandBuffer& cmd) {
cmd.bind_pipeline("depth_only");
cmd.auto_viewport_scissor();
VkDescriptorSet set = ph::DescriptorBuilder::create(ctx, cmd.get_bound_pipeline())
.add_uniform_buffer("camera", camera)
.add_storage_buffer("transforms", transforms)
.get();
cmd.bind_descriptor_set(set);
for_each_ready_mesh(scene, [&cmd](auto const& _, gfx::Mesh const& mesh, uint32_t index) {
cmd.push_constants(ph::ShaderStage::Vertex, 0, sizeof(uint32_t), &index); // mesh index is also the transform index
bind_and_draw(cmd, mesh);
});
})
.get();
return pass;
}
} | 48.530612 | 185 | 0.671152 |
271a387131255dd1d036ea05cd4a62a2a4d84380 | 11,061 | cpp | C++ | src/hostif/snmpAdapter/snmpAdapter.cpp | rdkcmf/rdk-tr69hostif | 5d9042b968eca933481e111e352828402732ec26 | [
"Apache-2.0"
] | 3 | 2018-11-23T05:08:54.000Z | 2019-10-18T12:52:38.000Z | src/hostif/snmpAdapter/snmpAdapter.cpp | rdkcmf/rdk-tr69hostif | 5d9042b968eca933481e111e352828402732ec26 | [
"Apache-2.0"
] | null | null | null | src/hostif/snmpAdapter/snmpAdapter.cpp | rdkcmf/rdk-tr69hostif | 5d9042b968eca933481e111e352828402732ec26 | [
"Apache-2.0"
] | 1 | 2018-08-16T19:15:22.000Z | 2018-08-16T19:15:22.000Z | /*
* If not stated otherwise in this file or this component's Licenses.txt file the
* following copyright and licenses apply:
*
* Copyright 2017 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.
*/
/**
* @file snmpAdapter.cpp
* @brief This source file contains the APIs for getting device information.
*/
/**
* @file snmpAdapter.cpp
*
* @brief SNMP RDKCENTRAL API Implementation.
*
* This is the implementation of the DeviceInfo API.
*
* @par Document
* TBD Relevant design or API documentation.
*
*/
/*****************************************************************************
* STANDARD INCLUDE FILES
*****************************************************************************/
/**
* @defgroup tr69hostif
* @{
* @defgroup hostif
* @{
**/
#include "snmpAdapter.h"
#include <fstream>
#include "safec_lib.h"
#ifdef YOCTO_BUILD
#include "secure_wrapper.h"
#endif
#define TR181_SNMPOID_FILE "/etc/tr181_snmpOID.conf"
#define SNMP_AGENT_IP_ADDRESS "192.168.100.1" //"127.0.0.1"
#define SNMP_COMMUNITY "hDaFHJG7"
GHashTable* hostIf_snmpAdapter::ifHash = NULL;
GHashTable* hostIf_snmpAdapter::m_notifyHash = NULL;
GMutex* hostIf_snmpAdapter::m_mutex = NULL;
map<string, string> hostIf_snmpAdapter::tr181SNMPMap;
/****************************************************************************************************************************************************/
// Device.X_RDKCENTRAL Profile. Getters:
/****************************************************************************************************************************************************/
/**
* @brief Class Constructor of the class hostIf_snmpAdapter.
*
*/
hostIf_snmpAdapter::hostIf_snmpAdapter(int dev_id):
dev_id(dev_id)
{
}
/**
* @brief Class Destructor of the class hostIf_snmpAdapter.
*
*/
hostIf_snmpAdapter::~hostIf_snmpAdapter()
{
if(m_notifyHash)
{
g_hash_table_destroy(m_notifyHash);
}
}
/**
* @brief This function opens the RF_DocsIf_tr181_snmp map file,
* parse the TR181 parameter and its correspoinding OID, fill it in map container.
*
*/
void hostIf_snmpAdapter::init(void)
{
string line;
ifstream fileStream (TR181_SNMPOID_FILE);
char delimeter[] = " \t\n\r\f\v";
tr181SNMPMap.clear();
if (fileStream.is_open())
{
while(getline(fileStream, line))
{
int pos = line.find('=');
if(pos != string::npos)
{
string key = line.substr(0, pos);
string value = line.substr(pos + 1);
key.erase(0, key.find_first_not_of(delimeter));
key.erase(key.find_last_not_of(delimeter) + 1);
value.erase(0, value.find_first_not_of(delimeter));
value.erase(value.find_last_not_of(delimeter) + 1);
tr181SNMPMap[key] = value;
}
}
}
else
RDK_LOG(RDK_LOG_ERROR,LOG_TR69HOSTIF,"[%s:%d] Error opening %s fileStream.", __FUNCTION__, __LINE__, TR181_SNMPOID_FILE );
if (!tr181SNMPMap.empty())
{
RDK_LOG(RDK_LOG_DEBUG,LOG_TR69HOSTIF,"[%s] %s count %d\n", __FUNCTION__, TR181_SNMPOID_FILE, tr181SNMPMap.size());
for(map<string, string>::iterator it = tr181SNMPMap.begin(); it != tr181SNMPMap.end(); it++)
RDK_LOG(RDK_LOG_DEBUG,LOG_TR69HOSTIF,"[%s] %s : %s\n", __FUNCTION__, it->first.c_str(), it->second.c_str());
}
}
/**
* @brief This function clear the TR181 OID map container.
*
*/
void hostIf_snmpAdapter::unInit(void)
{
tr181SNMPMap.clear();
}
hostIf_snmpAdapter* hostIf_snmpAdapter::getInstance(int dev_id)
{
hostIf_snmpAdapter* pRet = NULL;
if(ifHash)
pRet = (hostIf_snmpAdapter *)g_hash_table_lookup(ifHash,(gpointer) dev_id);
else
ifHash = g_hash_table_new(NULL,NULL);
if(!pRet)
{
try {
pRet = new hostIf_snmpAdapter(dev_id);
} catch(int e)
{
RDK_LOG(RDK_LOG_WARN,LOG_TR69HOSTIF,"Caught exception, not able create SNMP Device RDK Central instance..\n");
}
g_hash_table_insert(ifHash, (gpointer)dev_id, pRet);
}
return pRet;
}
GList* hostIf_snmpAdapter::getAllInstances()
{
if(ifHash)
return g_hash_table_get_keys(ifHash);
return NULL;
}
void hostIf_snmpAdapter::closeInstance(hostIf_snmpAdapter *pDev)
{
if(pDev)
{
g_hash_table_remove(ifHash, (gconstpointer)pDev->dev_id);
delete pDev;
}
}
void hostIf_snmpAdapter::closeAllInstances()
{
if(ifHash)
{
GList* tmp_list = g_hash_table_get_values (ifHash);
while(tmp_list)
{
hostIf_snmpAdapter* pDev = (hostIf_snmpAdapter *)tmp_list->data;
tmp_list = tmp_list->next;
closeInstance(pDev);
}
}
}
void hostIf_snmpAdapter::getLock()
{
if(!m_mutex)
{
m_mutex = g_mutex_new();
}
g_mutex_lock(m_mutex);
}
void hostIf_snmpAdapter::releaseLock()
{
g_mutex_unlock(m_mutex);
}
GHashTable* hostIf_snmpAdapter::getNotifyHash()
{
if(m_notifyHash)
return m_notifyHash;
else
return m_notifyHash = g_hash_table_new(g_str_hash, g_str_equal);
}
/**
* @brief This function fetch the SNMP OID for the corresponding TR181 param,
* and run the snmpget command with the OID. The result will be return back as string.
*
*/
int hostIf_snmpAdapter::get_ValueFromSNMPAdapter(HOSTIF_MsgData_t *stMsgData)
{
int ret = NOT_HANDLED;
char cmd[BUFF_LENGTH_256] = { 0 };
char resultBuff[BUFF_LENGTH_256] = { 0 };
char delimeter[] = " \t\n\r\f\v";
map<string,string>::iterator it;
string consoleString("");
errno_t rc = -1;
if(stMsgData)
{
it = tr181SNMPMap.find(stMsgData->paramName);
if (it != tr181SNMPMap.end())
{
snprintf (cmd, BUFF_LENGTH_256, "snmpget -OQ -Ir -v 2c -c %s %s %s",
SNMP_COMMUNITY,
SNMP_AGENT_IP_ADDRESS,
it->second.c_str());
RDK_LOG(RDK_LOG_TRACE1,LOG_TR69HOSTIF,"[%s] %s\n", __FUNCTION__, cmd);
ret = GetStdoutFromCommand( cmd, consoleString);
if (ret == OK)
{
int pos = consoleString.find('=');
if(pos != string::npos)
{
string subStr = consoleString.substr(pos + 1);
subStr.erase(0, subStr.find_first_not_of(delimeter));
subStr.erase(subStr.find_last_not_of(delimeter) + 1);
rc=strcpy_s(stMsgData->paramValue,sizeof(stMsgData->paramValue), subStr.c_str());
if(rc!=EOK)
{
ERR_CHK(rc);
}
}
else
{
rc=strcpy_s(stMsgData->paramValue,sizeof(stMsgData->paramValue), resultBuff);
if(rc!=EOK)
{
ERR_CHK(rc);
}
}
stMsgData->paramtype = hostIf_StringType;
RDK_LOG(RDK_LOG_TRACE1,LOG_TR69HOSTIF,"[%s] %s %s\n", __FUNCTION__, stMsgData->paramName, stMsgData->paramValue);
ret = OK;
}
}
else
{
ret = NOK;
RDK_LOG(RDK_LOG_ERROR,LOG_TR69HOSTIF,"[%s:%d] %s NOT found in the map.\n", __FUNCTION__, __LINE__, stMsgData->paramName );
}
}
return ret;
}
/**
* @brief This function fetch the SNMP OID for the corresponding TR181 param,
* and run the snmpset command with the OID.
*
*/
int hostIf_snmpAdapter::set_ValueToSNMPAdapter(HOSTIF_MsgData_t *stMsgData)
{
int ret = NOT_HANDLED;
char cmd[BUFF_LENGTH_256] = { 0 };
char resultBuff[BUFF_LENGTH_256] = { 0 };
map<string,string>::iterator it;
#ifdef YOCTO_BUILD
FILE *fp;
#define CMD(cmd, length, args...) ({ snprintf(cmd, length, args); fp = (v_secure_popen("r", args); )})
#else
#define CMD(cmd, length, args...) ({ snprintf(cmd, length, args); })
#endif
if(stMsgData)
{
it = tr181SNMPMap.find(stMsgData->paramName);
if (it != tr181SNMPMap.end())
{
switch(stMsgData->paramtype)
{
case hostIf_StringType:
CMD(cmd, BUFF_LENGTH_256, "snmpset -v 2c -c %s %s %s s %s",
SNMP_COMMUNITY, SNMP_AGENT_IP_ADDRESS,
it->second.c_str(),
stMsgData->paramValue);
break;
case hostIf_IntegerType:
CMD(cmd, BUFF_LENGTH_256, "snmpset -v 2c -c %s %s %s i %d",
SNMP_COMMUNITY, SNMP_AGENT_IP_ADDRESS,
it->second.c_str(),
stMsgData->paramValue);
break;
case hostIf_UnsignedIntType:
CMD(cmd, BUFF_LENGTH_256, "snmpset -v 2c -c %s %s %s u %d",
SNMP_COMMUNITY,
SNMP_AGENT_IP_ADDRESS,
it->second.c_str(),
stMsgData->paramValue);
break;
case hostIf_BooleanType:
case hostIf_DateTimeType:
case hostIf_UnsignedLongType:
default:
RDK_LOG(RDK_LOG_ERROR,LOG_TR69HOSTIF,"[%s:%d] %s not supported type %d\n", __FUNCTION__, __LINE__, stMsgData->paramName, stMsgData->paramtype);
return NOK;
}
RDK_LOG(RDK_LOG_TRACE1,LOG_TR69HOSTIF,"[%s] %s\n", __FUNCTION__, cmd);
#ifdef YOCTO_BUILD
if (fp == NULL) {
RDK_LOG (RDK_LOG_ERROR, LOG_TR69HOSTIF, "[%s]: cannot run command [%s]\n", __FUNCTION__, cmd);
ret = NOK;
} else if (fgets (resultBuff, BUFF_LENGTH_256, fp) == NULL) {
RDK_LOG (RDK_LOG_ERROR, LOG_TR69HOSTIF, "[%s]: cannot read output from command [%s]\n", __FUNCTION__, cmd);
v_secure_pclose (fp);
ret = NOK;
} else {
ret = v_secure_pclose(fp);
}
RDK_LOG (RDK_LOG_DEBUG, LOG_TR69HOSTIF, "[%s]: command [%s] returned [%s]\n", __FUNCTION__, cmd, resultBuff);
#else
ret = read_command_output (cmd, resultBuff, BUFF_LENGTH_256);
#endif
stMsgData->faultCode = (OK == ret)?fcNoFault:fcRequestDenied;
}
else
{
ret = NOK;
RDK_LOG(RDK_LOG_ERROR,LOG_TR69HOSTIF,"[%s:%d] %s NOT found in the map.\n", __FUNCTION__,__LINE__, stMsgData->paramName );
}
}
#undef CMD
return ret;
}
/* End of doxygen group */
/**
* @}
*/
/* End of file xxx_api.c. */
/** @} */
/** @} */
| 29.339523 | 163 | 0.574541 |
271a6bb390cdea7444ec97670599d0ec5b539f6f | 344 | cpp | C++ | hilbert_mapper/src/hilbert_mapper_node.cpp | Jaeyoung-Lim/mav_hilbertmap_planning | 96df718a04953df3b39f080a7e33565407ad6be1 | [
"BSD-3-Clause"
] | 4 | 2019-01-16T16:18:16.000Z | 2019-06-06T14:30:56.000Z | hilbert_mapper/src/hilbert_mapper_node.cpp | Wayne-xixi/mav_hilbertmap_planning | 96df718a04953df3b39f080a7e33565407ad6be1 | [
"BSD-3-Clause"
] | 16 | 2019-01-24T12:44:28.000Z | 2021-01-08T01:44:41.000Z | hilbert_mapper/src/hilbert_mapper_node.cpp | Wayne-xixi/mav_hilbertmap_planning | 96df718a04953df3b39f080a7e33565407ad6be1 | [
"BSD-3-Clause"
] | 2 | 2020-01-10T09:31:49.000Z | 2021-01-02T23:25:53.000Z | // July/2018, ETHZ, Jaeyoung Lim, jalim@student.ethz.ch
#include "hilbert_mapper/hilbert_mapper.h"
//using namespace RAI;
int main(int argc, char** argv) {
ros::init(argc,argv,"geometric_controller");
ros::NodeHandle nh("");
ros::NodeHandle nh_private("~");
HilbertMapper Hilbertmapper(nh, nh_private);
ros::spin();
return 0;
}
| 22.933333 | 56 | 0.700581 |
271cba3e5d38e9e79acafa3f44fabf815445a617 | 422 | hpp | C++ | src/as3/as3_function_call.hpp | sweetkristas/swiftly | 0b5c2badc88637b8bdaa841a45d1babd8f12a703 | [
"BSL-1.0",
"Zlib",
"BSD-3-Clause"
] | null | null | null | src/as3/as3_function_call.hpp | sweetkristas/swiftly | 0b5c2badc88637b8bdaa841a45d1babd8f12a703 | [
"BSL-1.0",
"Zlib",
"BSD-3-Clause"
] | null | null | null | src/as3/as3_function_call.hpp | sweetkristas/swiftly | 0b5c2badc88637b8bdaa841a45d1babd8f12a703 | [
"BSL-1.0",
"Zlib",
"BSD-3-Clause"
] | null | null | null | #pragma once
#include "as3_object.hpp"
#include "as3_value.hpp"
#include "../swf_environment.hpp"
namespace avm2
{
class function_call
{
public:
function_call();
~function_call();
size_t arg_count() const { return arg_count_; }
as3_value_ptr arg(size_t n) const;
private:
as3_object_ptr this_;
as3_value_ptr result_;
//swf::environment env_;
size_t arg_count_;
swf::stack_iterator arg_iter_;
};
}
| 17.583333 | 49 | 0.727488 |
271f8d927109f5c645a03e80ac2afa4111899984 | 4,779 | cpp | C++ | test/tbmv.cpp | Idein/qmkl6 | ac3e631ca89293c562db24b78576eef66426ab65 | [
"BSD-3-Clause"
] | 38 | 2020-09-24T08:46:33.000Z | 2022-03-23T01:40:03.000Z | test/tbmv.cpp | Idein/qmkl6 | ac3e631ca89293c562db24b78576eef66426ab65 | [
"BSD-3-Clause"
] | 3 | 2021-02-03T08:33:55.000Z | 2021-08-24T00:04:05.000Z | test/tbmv.cpp | Idein/qmkl6 | ac3e631ca89293c562db24b78576eef66426ab65 | [
"BSD-3-Clause"
] | 6 | 2020-09-24T13:40:19.000Z | 2021-06-08T19:35:43.000Z | #include <algorithm>
#include <cmath>
#include <complex>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <functional>
#include <iostream>
#include <random>
#include <type_traits>
#include "cblasdefs.h"
#include "cxxutils.hpp"
template <typename T>
static void naive_tbmv([[maybe_unused]] const CBLAS_LAYOUT layout,
[[maybe_unused]] const CBLAS_UPLO uplo,
[[maybe_unused]] const CBLAS_TRANSPOSE trans,
[[maybe_unused]] const CBLAS_DIAG diag, const int n,
const int k, const T *const a, const int lda, T *const x,
const int incx) {
if (k != 0) {
std::cerr << "error: We only support diagonal matrices for now"
<< std::endl;
std::exit(EXIT_FAILURE);
}
#pragma omp parallel for default(none) firstprivate(n, a, lda, x, incx) \
schedule(guided)
for (int i = 0; i < n; ++i) x[incx * i] *= a[lda * i];
}
template <typename T,
typename std::enable_if_t<std::is_same<T, float>{}, bool> = true>
static void cblas_tbmv(const CBLAS_LAYOUT layout, const CBLAS_UPLO uplo,
const CBLAS_TRANSPOSE trans, const CBLAS_DIAG diag,
const int n, const int k, const T *const a,
const int lda, T *const x, const int incx) {
cblas_stbmv(layout, uplo, trans, diag, n, k, a, lda, x, incx);
}
template <typename T, typename std::enable_if_t<
std::is_same<T, std::complex<float>>{}, bool> = true>
static void cblas_tbmv(const CBLAS_LAYOUT layout, const CBLAS_UPLO uplo,
const CBLAS_TRANSPOSE trans, const CBLAS_DIAG diag,
const int n, const int k, const T *const a,
const int lda, T *const x, const int incx) {
cblas_ctbmv(layout, uplo, trans, diag, n, k, a, lda, x, incx);
}
template <typename T, class Generator>
static int test_tbmv_diag_single(const int n, const int lda, const int incx,
Generator &gen) {
T *a, *x0, *x1;
uniform_distribution<T> dist;
printf("%stbmv: n = %5d, lda = %5d, incx = %d: ", blas_prefix<T>(), n, lda,
incx);
a = (T *)mkl_malloc(n * lda * sizeof(T), 64);
std::generate(a, a + n * lda, std::bind(dist, gen));
x0 = (T *)malloc((1 + (n - 1) * incx) * sizeof(T));
x1 = (T *)mkl_malloc((1 + (n - 1) * incx) * sizeof(T), 64);
std::generate(x0, x0 + (1 + (n - 1) * incx), std::bind(dist, gen));
memcpy(x1, x0, (1 + (n - 1) * incx) * sizeof(T));
const double start0 = dsecnd();
naive_tbmv(CblasRowMajor, CblasUpper, CblasNoTrans, CblasNonUnit, n, 0, a,
lda, x0, incx);
const double t0 = dsecnd() - start0;
const double start1 = dsecnd();
cblas_tbmv(CblasRowMajor, CblasUpper, CblasNoTrans, CblasNonUnit, n, 0, a,
lda, x1, incx);
const double t1 = dsecnd() - start1;
using error_type = decltype(std::abs(T()));
error_type err_abs_min = std::numeric_limits<error_type>::infinity(),
err_abs_max = -std::numeric_limits<error_type>::infinity(),
err_rel_min = std::numeric_limits<error_type>::infinity(),
err_rel_max = -std::numeric_limits<error_type>::infinity();
for (int i = 0; i < n; ++i) {
const T err = x0[incx * i] - x1[incx * i];
const error_type err_abs = std::abs(err),
err_rel = std::abs(err / x0[incx * i]);
err_abs_min = std::min(err_abs_min, err_abs);
err_abs_max = std::max(err_abs_max, err_abs);
err_rel_min = std::min(err_rel_min, err_rel);
err_rel_max = std::max(err_rel_max, err_rel);
}
printf(
"err_abs = [%f, %f], "
"err_rel = [%f, %f], "
"%f sec -> %f sec, "
"%f Mflop/s -> %f Mflop/s\n",
err_abs_min, err_abs_max, err_rel_min, err_rel_max, t0, t1, n / t0 * 1e-6,
n / t1 * 1e-6);
if (err_rel_max > 1e-3) {
std::cerr << "error: Absolute error is too large" << std::endl;
return 1;
}
mkl_free(a);
free(x0);
mkl_free(x1);
return 0;
}
template <typename T, class Generator>
static int test_tbmv_diag_random(Generator &gen) {
std::uniform_int_distribution<int> dist_int;
dist_int.param(decltype(dist_int)::param_type(1, 1 << 16));
const int n = dist_int(gen);
dist_int.param(decltype(dist_int)::param_type(1, 8));
const int incx = dist_int(gen), lda = dist_int(gen);
return test_tbmv_diag_single<T>(n, lda, incx, gen);
}
int main(void) {
setbuf(stdout, NULL);
std::default_random_engine gen;
int ret;
for (int i = 0; i < 10; ++i) {
ret = test_tbmv_diag_random<float>(gen);
if (ret) return ret;
}
for (int i = 0; i < 10; ++i) {
ret = test_tbmv_diag_random<std::complex<float>>(gen);
if (ret) return ret;
}
return 0;
}
| 33.1875 | 80 | 0.596359 |
2721f2a2a3764ae828f43dbe3adff321a7e0c752 | 1,244 | cc | C++ | csrc/inline_histogram_weighted.cc | dwferrer/loom | 8d0261028a4ccc1d1250ceff5f20a435fca0bd60 | [
"MIT"
] | null | null | null | csrc/inline_histogram_weighted.cc | dwferrer/loom | 8d0261028a4ccc1d1250ceff5f20a435fca0bd60 | [
"MIT"
] | null | null | null | csrc/inline_histogram_weighted.cc | dwferrer/loom | 8d0261028a4ccc1d1250ceff5f20a435fca0bd60 | [
"MIT"
] | null | null | null | //fast c based histogram code for generating the 1-d histogram of an array destructively. Requires Intel's tbb to be included and linked seperately, along with std::algorithm
//we assume that data, data_x_weights are already sorted
//{FLOAT} * c_data = data;//({FLOAT} *) PyArray_DATA(PyArray_GETCONTIGUOUS(data));
unsigned long long int count = 1;
for(int d = 0; d < Ddata; d++) count*=Ndata[d];
double * counts = bincounts;
int nbins = Nbins [0] -1;
unsigned long long int b_low [omp_get_max_threads()];
unsigned long long int b_high[omp_get_max_threads()];
for(int i = 0; i < omp_get_max_threads();i++){{
b_low[i] = 0;
b_high[i] = count;
}}
#pragma omp parallel for schedule( dynamic,1)
for( int b = 0; b < nbins; b++){{
int t = omp_get_thread_num();
{FLOAT} * p_low = std::lower_bound(data,data+count,bins[b]);
{FLOAT} * p_high;
if(b <nbins-1)
p_high = std::lower_bound(data,data+count,bins[b+1]);
else
p_high = std::upper_bound(data,data+count,bins[b+1]);
b_low[t] = p_low - data;
b_high[t] = p_high -data;
double bincount = 0;
#pragma simd
for (size_t i = b_low[t]; i < b_high[t]; i++) bincount += weights[i];
counts[b] += bincount;
}}
| 24.392157 | 174 | 0.639871 |
2726f408337596cb11dd98ed1f186d3fb3fbc84c | 659 | cpp | C++ | pointers_class_memory/class7.cpp | Sinchiguano/Algorithmic-Toolbox | 7e9dda588a72356fc43fa276016fc3486be47556 | [
"BSD-2-Clause"
] | null | null | null | pointers_class_memory/class7.cpp | Sinchiguano/Algorithmic-Toolbox | 7e9dda588a72356fc43fa276016fc3486be47556 | [
"BSD-2-Clause"
] | null | null | null | pointers_class_memory/class7.cpp | Sinchiguano/Algorithmic-Toolbox | 7e9dda588a72356fc43fa276016fc3486be47556 | [
"BSD-2-Clause"
] | null | null | null | /*
* class7.cpp
* Copyright (C) 2018 CESAR SINCHIGUANO <cesarsinchiguano@hotmail.es>
*
* Distributed under terms of the BSD license.
*/
#include <iostream>
#include <string>
//g++ -std=c++14 -o temp sort.cpp
using namespace std;
class Example4
{
string* ptr;
public:
// constructors:
Example4() : ptr(new string) {}
Example4 (const string& str) : ptr(new string(str)) {}
// destructor:
~Example4 () {delete ptr;}
// access content:
const string& content() const {return *ptr;}
};
int main ()
{
//Example4 myObject1;
Example4 myObject2("CESAR");
std::cout << myObject2.content() << '\n';
return 0;
}
| 15.325581 | 69 | 0.622155 |
272c01ee9f86a8fc7dad48ccdd942e8495d58c09 | 3,773 | cpp | C++ | sim/src/main.cpp | bentobox-dev/bento-box | 3e10c62f586c1251529e059b6af515d4d03c60e9 | [
"MIT"
] | 1 | 2021-01-02T02:50:15.000Z | 2021-01-02T02:50:15.000Z | sim/src/main.cpp | joeltio/bento-box | 3e10c62f586c1251529e059b6af515d4d03c60e9 | [
"MIT"
] | 48 | 2020-10-21T07:42:30.000Z | 2021-02-15T19:34:55.000Z | sim/src/main.cpp | joeltio/bento-box | 3e10c62f586c1251529e059b6af515d4d03c60e9 | [
"MIT"
] | null | null | null | /*
* bentobox-sim
* Main Entrypoint
*/
#include <component/textureComponent.h>
#include <core/graphicsContext.h>
#include <core/systemContext.h>
#include <core/windowContext.h>
#include <ics.h>
#include <system/render.h>
#include <network/grpcServer.h>
#include <service/engineService.h>
using grpc::Service;
using network::GRPCServer;
using service::EngineServiceImpl;
using std::invalid_argument;
using std::list;
using std::stoi;
using std::string;
using std::to_string;
/**
* Get the value of the environment variable with the given name.
*
* @param name The name of environment variable to get.
* @param defaultValue The value to return if no such environment variable is
* found.
*
* @returns The value of the environment variable or defaultValue
* if the variable cannot be found.
*/
string getEnv(const string name, const string defaultValue) {
auto envValue = std::getenv(name.c_str());
if (!envValue) {
return defaultValue;
}
return envValue;
}
/**
* Bentobox-sim engine main entrypoint
*
* Environment Variable parameters:
* - BENTOBOX_SIM_HOST - the host/ip that bentobox-sim listens on.
* - BENTOBOX_SIM_PORT - the port that bentobox-sim listens on.
*/
int main(int argc, char *argv[]) {
// setup graphics
WindowContext windowContext = WindowContext(800, 600, "Bento Box");
GraphicsContext graphics = GraphicsContext(windowContext);
// setup ICS
ics::ComponentStore componentStore = ics::ComponentStore();
ics::index::IndexStore indexStore = ics::index::IndexStore();
SystemContext systemContext = SystemContext<ics::index::IndexStore>();
auto tex1 = ics::component::Texture2DComponent();
auto value = bento::protos::Value();
value.mutable_primitive()->set_int_64(1);
value.mutable_data_type()->set_primitive(
bento::protos::Type_Primitive_INT64);
tex1.setValue("texture", value);
auto tex2 = ics::component::Texture2DComponent();
value = bento::protos::Value();
value.mutable_primitive()->set_int_64(2);
value.mutable_data_type()->set_primitive(
bento::protos::Type_Primitive_INT64);
tex2.setValue("texture", value);
auto tex3 = ics::component::Texture2DComponent();
value = bento::protos::Value();
value.mutable_primitive()->set_int_64(3);
value.mutable_data_type()->set_primitive(
bento::protos::Type_Primitive_INT64);
tex3.setValue("texture", value);
auto tex4 = ics::component::Texture2DComponent();
value = bento::protos::Value();
value.mutable_primitive()->set_int_64(4);
value.mutable_data_type()->set_primitive(
bento::protos::Type_Primitive_INT64);
tex4.setValue("texture", value);
ics::addComponent(indexStore, componentStore, tex1);
ics::addComponent(indexStore, componentStore, tex2);
ics::addComponent(indexStore, componentStore, tex3);
ics::addComponent(indexStore, componentStore, tex4);
// register ICS systems
const SystemFn<ics::index::IndexStore> a(&ics::system::render);
systemContext.systems.push_front(a);
// start gRPC server using host and port obtained via env vars
string host = getEnv("BENTOBOX_SIM_HOST", "localhost");
int port = std::stoi(getEnv("BENTOBOX_SIM_PORT", "54242"));
EngineServiceImpl engineService;
list<Service *> services = {&engineService};
GRPCServer server(host, port, services);
std::cout << "bentobox-sim listening on " << server.address() << std::endl;
// run engine main loop
while (!windowContext.shouldClose()) {
glClearColor(0.2f, 0.3f, 0.3f, 1.0f);
glClear(GL_COLOR_BUFFER_BIT);
systemContext.run(graphics, componentStore, indexStore);
windowContext.swapBuffers();
windowContext.updateEvents();
}
}
| 32.808696 | 79 | 0.702624 |
272cc7f0fb1519b31760bc68b706d7eab0933a6a | 1,128 | cpp | C++ | tag_hierarchy/utils/filters.cpp | equinor/ioc-hierarchy-service | e60ad3eaae3c4b71ec5d8d6d64913c8463b749e9 | [
"MIT"
] | 3 | 2021-12-22T07:36:26.000Z | 2022-03-29T07:24:28.000Z | tag_hierarchy/utils/filters.cpp | equinor/ioc-hierarchy-service | e60ad3eaae3c4b71ec5d8d6d64913c8463b749e9 | [
"MIT"
] | 10 | 2020-08-03T13:00:30.000Z | 2021-12-27T10:08:54.000Z | tag_hierarchy/utils/filters.cpp | equinor/ioc-hierarchy-service | e60ad3eaae3c4b71ec5d8d6d64913c8463b749e9 | [
"MIT"
] | null | null | null | #include "tag_hierarchy/utils/filters.h"
std::tuple<std::vector<std::string>, std::vector<std::string>, std::vector<std::string>>
TagHierarchyUtils::Filters::GetFilterSettings(NodeType& command_map) {
auto l1filter = std::vector<std::string>();
if (command_map.count("l1filter") &&
command_map["l1filter"].type() == typeid(std::vector<std::string>))
{
l1filter = boost::get<std::vector<std::string>>(command_map.at("l1filter"));
}
auto modelownerfilter = std::vector<std::string>();
if (command_map.count("modelownerfilter") &&
command_map["modelownerfilter"].type() == typeid(std::vector<std::string>))
{
modelownerfilter = boost::get<std::vector<std::string>>(command_map.at("modelownerfilter"));
}
auto modelclassfilter = std::vector<std::string>();
if (command_map.count("modelclassfilter") &&
command_map["modelclassfilter"].type() == typeid(std::vector<std::string>))
{
modelclassfilter = boost::get<std::vector<std::string>>(command_map.at("modelclassfilter"));
}
return {l1filter, modelownerfilter, modelclassfilter};
} | 47 | 100 | 0.669326 |
272df97d7c2eeeb96e5bdcd9f8ff41d0e7495246 | 2,719 | cc | C++ | mace/ops/reduce_mean_benchmark.cc | nihui/mace | e13c3f66d3543a46248849294f6606eba769964d | [
"Apache-2.0"
] | 5 | 2018-06-28T02:39:33.000Z | 2021-05-14T08:12:12.000Z | mace/ops/reduce_mean_benchmark.cc | fly-jelly/mace | e13c3f66d3543a46248849294f6606eba769964d | [
"Apache-2.0"
] | null | null | null | mace/ops/reduce_mean_benchmark.cc | fly-jelly/mace | e13c3f66d3543a46248849294f6606eba769964d | [
"Apache-2.0"
] | null | null | null | //
// Copyright (c) 2017 XiaoMi All rights reserved.
//
#include "mace/core/operator.h"
#include "mace/core/runtime/opencl/opencl_runtime.h"
#include "mace/core/testing/test_benchmark.h"
#include "mace/ops/ops_test_util.h"
namespace mace {
namespace ops {
namespace test {
namespace {
template <DeviceType D, typename T>
void ReduceMean(int iters, int batch, int channels,
int height, int width) {
mace::testing::StopTiming();
OpsTestNet net;
// Add input data
net.AddRandomInput<D, T>("Input", {batch, height, width, channels});
if (D == DeviceType::GPU) {
BufferToImage<D, T>(&net, "Input", "InputImage",
kernels::BufferType::IN_OUT_CHANNEL);
OpDefBuilder("ReduceMean", "ReduceMeanBM")
.Input("InputImage")
.AddIntsArg("axis", {1, 2})
.Output("OutputImage")
.Finalize(net.NewOperatorDef());
} else {
net.TransformDataFormat<DeviceType::CPU, float>("Input", NHWC, "InputNCHW",
NCHW);
OpDefBuilder("ReduceMean", "ReduceMeanBM")
.Input("InputNCHW")
.AddIntsArg("axis", {2, 3})
.Output("Output")
.Finalize(net.NewOperatorDef());
}
// Warm-up
for (int i = 0; i < 5; ++i) {
net.RunOp(D);
}
net.Sync();
mace::testing::StartTiming();
while (iters--) {
net.RunOp(D);
}
net.Sync();
}
} // namespace
#define MACE_BM_REDUCE_MEAN_MACRO(N, C, H, W, TYPE, DEVICE) \
static void \
MACE_BM_REDUCE_MEAN_##N##_##C##_##H##_##W##_##TYPE##_##DEVICE(\
int iters) { \
const int64_t tot = static_cast<int64_t>(iters) * N * C * H * W; \
mace::testing::MaccProcessed(tot); \
mace::testing::BytesProcessed(tot *(sizeof(TYPE))); \
ReduceMean<DEVICE, TYPE>(iters, N, C, H, W); \
} \
MACE_BENCHMARK( \
MACE_BM_REDUCE_MEAN_##N##_##C##_##H##_##W##_##TYPE##_##DEVICE)
#define MACE_BM_REDUCE_MEAN(N, C, H, W) \
MACE_BM_REDUCE_MEAN_MACRO(N, C, H, W, float, GPU); \
MACE_BM_REDUCE_MEAN_MACRO(N, C, H, W, half, GPU); \
MACE_BM_REDUCE_MEAN_MACRO(N, C, H, W, float, CPU);
MACE_BM_REDUCE_MEAN(1, 1, 512, 512);
MACE_BM_REDUCE_MEAN(4, 3, 128, 128);
MACE_BM_REDUCE_MEAN(4, 3, 512, 512);
MACE_BM_REDUCE_MEAN(16, 32, 112, 112);
MACE_BM_REDUCE_MEAN(8, 32, 112, 112);
MACE_BM_REDUCE_MEAN(8, 64, 256, 256);
MACE_BM_REDUCE_MEAN(1, 32, 480, 640);
} // namespace test
} // namespace ops
} // namespace mace
| 31.616279 | 79 | 0.552409 |
272ef38e2bdd26b398d8e764eadb4f729ee15768 | 3,715 | cpp | C++ | Src/Vessel/Atlantis/Common.cpp | Ybalrid/orbiter | 7bed82f845ea8347f238011367e07007b0a24099 | [
"MIT"
] | 1,040 | 2021-07-27T12:12:06.000Z | 2021-08-02T14:24:49.000Z | Src/Vessel/Atlantis/Common.cpp | Ybalrid/orbiter | 7bed82f845ea8347f238011367e07007b0a24099 | [
"MIT"
] | 20 | 2021-07-27T12:25:22.000Z | 2021-08-02T12:22:19.000Z | Src/Vessel/Atlantis/Common.cpp | Ybalrid/orbiter | 7bed82f845ea8347f238011367e07007b0a24099 | [
"MIT"
] | 71 | 2021-07-27T14:19:49.000Z | 2021-08-02T05:51:52.000Z | // ==============================================================
// ORBITER MODULE: Atlantis
// Part of the ORBITER SDK
// Copyright (C) 2001-2003 Martin Schweiger
// All rights reserved
//
// Common.cpp
// Utility functions common to multiple Atlantis-related modules
// ==============================================================
#include "Atlantis.h"
#ifdef _DEBUG
// D. Beachy: GROW THE STACK HERE SO WE CAN USE BOUNDSCHECKER FOR DEBUGGING
// We need this is because BoundsChecker (for this object) grows the stack more than 1 full page (4K) at once
// and then touches data beyond the initial 4K, skipping over the guard page that Windows places below the stack to grow it automatically.
// Therefore we will grow the stack manually in one-page increments here.
// This is only necessary for BoundsChecker debugging.
int GrowStack()
{
#ifdef UNDEF // This function causes a crash (LoadLibrary fails with code 1001 (stack overflow) on compiling with VS2019, so I am disabling it for now
// NOTE: this requires that orbiter.exe has its 'Size of Stack Reserve' PE header parameter set to 4 MB
int pageCount = 256; // 256 4K pages = reserve 1 MB of stack
DWORD dwStackDelta = 0; // total # of stack bytes used
for (int i=0; i < pageCount; i++)
{
dwStackDelta += 4096;
__asm
{
sub esp, 4092; // 1 page - 4 bytes
push 0xFEEDFEED // touch the page
}
}
// now pop the stack we touched
__asm
{
mov eax, [dwStackDelta] // size in bytes
add esp, eax
}
#endif
return 0;
}
// invoke GrowStack early before the next lines are called (otherwise BoundsChecker will crash)
int growStack=GrowStack();
#endif
int SRB_nt = 6;
double SRB_Seq[6] = {-SRB_STABILISATION_TIME, -1, 103, 115, SRB_SEPARATION_TIME, SRB_CUTOUT_TIME};
double SRB_Thrust[6] = { 0, 1, 1, 0.85, 0.05, 0 };
double SRB_Prop[6] = { 1, 0.98768, 0.13365, 0.04250, 0.001848, 0 };
double SRB_ThrSCL[5] = {(SRB_Thrust[1]-SRB_Thrust[0])/(SRB_Seq[1]-SRB_Seq[0]),
(SRB_Thrust[2]-SRB_Thrust[1])/(SRB_Seq[2]-SRB_Seq[1]),
(SRB_Thrust[3]-SRB_Thrust[2])/(SRB_Seq[3]-SRB_Seq[2]),
(SRB_Thrust[4]-SRB_Thrust[3])/(SRB_Seq[4]-SRB_Seq[3]),
(SRB_Thrust[5]-SRB_Thrust[4])/(SRB_Seq[5]-SRB_Seq[4])};
double SRB_PrpSCL[5] = {(SRB_Prop[1]-SRB_Prop[0])/(SRB_Seq[1]-SRB_Seq[0]),
(SRB_Prop[2]-SRB_Prop[1])/(SRB_Seq[2]-SRB_Seq[1]),
(SRB_Prop[3]-SRB_Prop[2])/(SRB_Seq[3]-SRB_Seq[2]),
(SRB_Prop[4]-SRB_Prop[3])/(SRB_Seq[4]-SRB_Seq[3]),
(SRB_Prop[5]-SRB_Prop[4])/(SRB_Seq[5]-SRB_Seq[4])};
//PARTICLESTREAMSPEC srb_contrail = {
// 0, 12.0, 3, 150.0, 0.4, 8.0, 4, 3.0, PARTICLESTREAMSPEC::DIFFUSE,
// PARTICLESTREAMSPEC::LVL_PSQRT, 0, 0.5,
// PARTICLESTREAMSPEC::ATM_PLOG, 1e-6, 0.1
//};
PARTICLESTREAMSPEC srb_contrail = {
0, 12.0, 3, 200.0, 0.25, 12.0, 11, 10.0, PARTICLESTREAMSPEC::DIFFUSE,
PARTICLESTREAMSPEC::LVL_PSQRT, 0, 0.7,
PARTICLESTREAMSPEC::ATM_PLOG, 1e-6, 0.1
};
PARTICLESTREAMSPEC srb_exhaust = {
0, 6.0, 40, 250.0, 0.04, 0.4, 20, 6.0, PARTICLESTREAMSPEC::EMISSIVE,
PARTICLESTREAMSPEC::LVL_SQRT, 1, 1,
PARTICLESTREAMSPEC::ATM_FLAT, 1, 1
};
// time-dependent calculation of SRB thrust and remaining propellant
void GetSRB_State (double met, double &thrust_level, double &prop_level)
{
int i;
for (i = SRB_nt-2; i >= 0; i--)
if (met > SRB_Seq[i]) break;
thrust_level = SRB_ThrSCL[i] * (met-SRB_Seq[i]) + SRB_Thrust[i];
prop_level = SRB_PrpSCL[i] * (met-SRB_Seq[i]) + SRB_Prop[i];
}
| 40.380435 | 150 | 0.61319 |
27305309e16b21f4b91241bdb63de3e3ea06e5ee | 6,215 | cxx | C++ | EVE/EveDet/AliEveEMCALSModuleData.cxx | AllaMaevskaya/AliRoot | c53712645bf1c7d5f565b0d3228e3a6b9b09011a | [
"BSD-3-Clause"
] | 52 | 2016-12-11T13:04:01.000Z | 2022-03-11T11:49:35.000Z | EVE/EveDet/AliEveEMCALSModuleData.cxx | AllaMaevskaya/AliRoot | c53712645bf1c7d5f565b0d3228e3a6b9b09011a | [
"BSD-3-Clause"
] | 1,388 | 2016-11-01T10:27:36.000Z | 2022-03-30T15:26:09.000Z | EVE/EveDet/AliEveEMCALSModuleData.cxx | AllaMaevskaya/AliRoot | c53712645bf1c7d5f565b0d3228e3a6b9b09011a | [
"BSD-3-Clause"
] | 275 | 2016-06-21T20:24:05.000Z | 2022-03-31T13:06:19.000Z | /**************************************************************************
* Copyright(c) 1998-1999, ALICE Experiment at CERN, All rights reserved. *
* *
* Author: The ALICE Off-line Project. *
* Contributors are mentioned in the code where appropriate. *
* *
* Permission to use, copy, modify and distribute this software and its *
* documentation strictly for non-commercial purposes is hereby granted *
* without fee, provided that the above copyright notice appears in all *
* copies and that both the copyright notice and this permission notice *
* appear in the supporting documentation. The authors make no claims *
* about the suitability of this software for any purpose. It is *
* provided "as is" without express or implied warranty. *
**************************************************************************/
#include <TGeoBBox.h>
#include "AliEMCALGeometry.h"
#include "AliEveEMCALSModuleData.h"
class TClonesArray;
class TGeoNode;
//class TGeoMatrix;
class TVector2;
class AliEveEventManager;
/// \cond CLASSIMP
ClassImp(AliEveEMCALSModuleData) ;
/// \endcond
Float_t AliEveEMCALSModuleData::fgSModuleBigBox0 = 0.;
Float_t AliEveEMCALSModuleData::fgSModuleBigBox1 = 0.;
Float_t AliEveEMCALSModuleData::fgSModuleBigBox2 = 0.;
Float_t AliEveEMCALSModuleData::fgSModuleSmallBox0 = 0.;
Float_t AliEveEMCALSModuleData::fgSModuleSmallBox1 = 0.;
Float_t AliEveEMCALSModuleData::fgSModuleSmallBox2 = 0.;
Float_t AliEveEMCALSModuleData::fgSModuleDCalBox0 = 0.;
Float_t AliEveEMCALSModuleData::fgSModuleDCalBox1 = 0.;
Float_t AliEveEMCALSModuleData::fgSModuleDCalBox2 = 0.;
Float_t AliEveEMCALSModuleData::fgSModuleSmallDBox0 = 0.;
Float_t AliEveEMCALSModuleData::fgSModuleSmallDBox1 = 0.;
Float_t AliEveEMCALSModuleData::fgSModuleSmallDBox2 = 0.;
//
// Constructor
//
//______________________________________________________________________________
AliEveEMCALSModuleData::AliEveEMCALSModuleData(Int_t sm,AliEMCALGeometry* geom, TGeoNode* node): //, TGeoHMatrix* m) :
TObject(),
fGeom(geom),
fNode(node),
fSmId(sm),
fNsm(0),
fNDigits(0),
fNClusters(0),
fNHits(0),
fPhiTileSize(0), fEtaTileSize(0),
fHitArray(0),
fDigitArray(0),
fClusterArray(0)
// fMatrix(0),
// fHMatrix(m)
{
Init(sm);
}
///
/// Copy constructor
///
//______________________________________________________________________________
AliEveEMCALSModuleData::AliEveEMCALSModuleData(const AliEveEMCALSModuleData &esmdata) :
TObject(),
fGeom(esmdata.fGeom),
fNode(esmdata.fNode),
fSmId(esmdata.fSmId),
fNsm(esmdata.fNsm),
fNDigits(esmdata.fNDigits),
fNClusters(esmdata.fNClusters),
fNHits(esmdata.fNHits),
fPhiTileSize(esmdata.fPhiTileSize), fEtaTileSize(esmdata.fEtaTileSize),
fHitArray(esmdata.fHitArray),
fDigitArray(esmdata.fDigitArray),
fClusterArray(esmdata.fClusterArray)
// fMatrix(esmdata.fMatrix),
// fHMatrix(esmdata.fHMatrix)
{
Init(esmdata.fNsm);
}
///
/// Destructor
///
//______________________________________________________________________________
AliEveEMCALSModuleData::~AliEveEMCALSModuleData()
{
if(!fHitArray.empty())
fHitArray.clear();
if(!fDigitArray.empty())
fDigitArray.clear();
if(!fClusterArray.empty())
fClusterArray.clear();
}
///
/// Release the SM data.
///
//______________________________________________________________________________
void AliEveEMCALSModuleData::DropData()
{
fNDigits = 0;
fNClusters = 0;
fNHits = 0;
if(!fHitArray.empty())
fHitArray.clear();
if(!fDigitArray.empty())
fDigitArray.clear();
if(!fClusterArray.empty())
fClusterArray.clear();
return;
}
///
/// Initialize parameters
///
// ______________________________________________________________________________
void AliEveEMCALSModuleData::Init(Int_t sm)
{
fNsm = fGeom->GetNumberOfSuperModules();
fPhiTileSize = fGeom->GetPhiTileSize();
fEtaTileSize = fGeom->GetPhiTileSize();
//fMatrix = (TGeoMatrix*) fNode->GetDaughter(sm)->GetMatrix();
TGeoBBox * bbox = (TGeoBBox*) fNode->GetDaughter(sm)->GetVolume()->GetShape();
if(sm < 10)
{
fgSModuleBigBox0 = bbox->GetDX();
fgSModuleBigBox1 = bbox->GetDY();
fgSModuleBigBox2 = bbox->GetDZ();
}
else if(sm < 12)
{
fgSModuleSmallBox0 = bbox->GetDX();
fgSModuleSmallBox1 = bbox->GetDY();
fgSModuleSmallBox2 = bbox->GetDZ();
}
else if(sm < 18)
{
fgSModuleDCalBox0 = bbox->GetDX();
fgSModuleDCalBox1 = bbox->GetDY();
fgSModuleDCalBox2 = bbox->GetDZ();
}
else if(sm < 20)
{
fgSModuleSmallDBox0 = bbox->GetDX();
fgSModuleSmallDBox1 = bbox->GetDY();
fgSModuleSmallDBox2 = bbox->GetDZ();
}
}
///
/// Add a digit to this SM
///
// ______________________________________________________________________________
void AliEveEMCALSModuleData::RegisterDigit(Int_t AbsId, Int_t isupMod, Double_t iamp, Double_t ix, Double_t iy, Double_t iz)
{
std::vector<Double_t> bufDig(6);
bufDig[0] = AbsId;
bufDig[1] = isupMod;
bufDig[2] = iamp;
bufDig[3] = ix;
bufDig[4] = iy;
bufDig[5] = iz;
fDigitArray.push_back(bufDig);
fNDigits++;
}
///
/// Add a hit to this SM
///
// ______________________________________________________________________________
void AliEveEMCALSModuleData::RegisterHit(Int_t AbsId, Int_t isupMod, Double_t iamp, Double_t ix, Double_t iy, Double_t iz)
{
std::vector<Float_t> bufHit(6);
bufHit[0] = AbsId;
bufHit[1] = isupMod;
bufHit[2] = iamp;
bufHit[3] = ix;
bufHit[4] = iy;
bufHit[5] = iz;
fHitArray.push_back(bufHit);
fNHits++;
}
///
/// Add a cluster to this SM
///
// ______________________________________________________________________________
void AliEveEMCALSModuleData::RegisterCluster(Int_t isupMod, Double_t iamp, Double_t ix, Double_t iy, Double_t iz)
{
std::vector<Double_t> bufClu(5);
bufClu[0] = isupMod;
bufClu[1] = iamp;
bufClu[2] = ix;
bufClu[3] = iy;
bufClu[4] = iz;
fClusterArray.push_back(bufClu);
fNClusters++;
}
| 27.258772 | 124 | 0.684312 |
27307444b2da9e8959408ee53db2556cc14f1982 | 578 | cpp | C++ | codes/HDU/hdu5510.cpp | JeraKrs/ACM | edcd61ec6764b8cd804bf1538dfde53d0ff572b5 | [
"Apache-2.0"
] | null | null | null | codes/HDU/hdu5510.cpp | JeraKrs/ACM | edcd61ec6764b8cd804bf1538dfde53d0ff572b5 | [
"Apache-2.0"
] | null | null | null | codes/HDU/hdu5510.cpp | JeraKrs/ACM | edcd61ec6764b8cd804bf1538dfde53d0ff572b5 | [
"Apache-2.0"
] | null | null | null | #include <cstdio>
#include <cstring>
#include <algorithm>
using namespace std;
const int maxn = 505;
const int maxm = 2005;
int N, F[maxn];
char str[maxn][maxm];
int main () {
int cas;
scanf("%d", &cas);
for (int kcas = 1; kcas <= cas; kcas++) {
scanf("%d", &N);
for (int i = 0; i < N; i++) scanf("%s", str[i]);
int p = N-1;
while (p && strstr(str[p], str[p-1]) != NULL) p--;
p++;
for (int i = p-2; i >= 0 && p < N; i--) {
while (p < N && strstr(str[p], str[i]) == NULL) p++;
}
if (p == 1) p = -1;
printf("Case #%d: %d\n", kcas, p);
}
return 0;
}
| 18.645161 | 55 | 0.50346 |
27326fc91fe01e24ab157440f0a5b456c35c17f4 | 5,121 | cpp | C++ | EsteganografiaC++/src/codificar.cpp | nen155/Metodolog-a-de-Programaci-n | 587d9a231d1c6ef1fa59f895fdf69d30eb4c598a | [
"MIT"
] | null | null | null | EsteganografiaC++/src/codificar.cpp | nen155/Metodolog-a-de-Programaci-n | 587d9a231d1c6ef1fa59f895fdf69d30eb4c598a | [
"MIT"
] | null | null | null | EsteganografiaC++/src/codificar.cpp | nen155/Metodolog-a-de-Programaci-n | 587d9a231d1c6ef1fa59f895fdf69d30eb4c598a | [
"MIT"
] | null | null | null | /**
* @file codificar.cpp
* @brief Fichero que contiene las funciones para codificar un mensaje en una imagen, tanto para introducirlo como para leerlo.
*
* Permite la E/S de archivos de tipo PGM,PPM
*
*/
#include "imagenES.h"
#include "codificar.h"
#include <iostream>
#include <cstring>
using namespace std;
//Para mostrarle mensajes al usuario por teclado
void lecturaTeclado(char nombre[],const int max,char mensaje[]){
cout<<mensaje;
cin.getline(nombre,max,'\n');
}
// _____________________________________________________________________________
bool compruebaLectura(char nombre[]){
if(strlen(nombre)>100){
cout<<"El mensaje tiene que ser de menos de 100 caracteres";
return true;
}
else return false;
}
//Introduce en la variable bncolor el tipo de imagen leido.
// _____________________________________________________________________________
void lecturaTipoIMG(const char nombre[],TipoImagen &bncolor,int &filas,int &columnas){
bncolor= LeerTipoImagen(nombre,filas,columnas);
}
//Dependiendo del tipo de imagen leido hace una lectura u otra y devuelve si la lectura ha tenido exito.
// _____________________________________________________________________________
bool lecturaIMG(const char nombre[],const TipoImagen bncolor,int &filas,int &columnas,unsigned char buffer[]){
bool flag=false;
switch(bncolor){
case IMG_PGM:
if(LeerImagenPGM(nombre,filas,columnas,buffer))
flag=true;
else
flag=false;
break;
case IMG_PPM:
if(LeerImagenPPM(nombre,filas,columnas,buffer))
flag=true;
else
flag=false;
break;
case IMG_DESCONOCIDO:
flag=false;
break;
return flag;
}
}
// _____________________________________________________________________________
void ocultar(unsigned char imagen[],char mensaje[]){
for(int i=0;i<strlen(mensaje);i++){
for(int k=0;k<8;k++){
//DESPLAZA A LA DERECHA EL ÚLTIMO BIT DE IMAGEN
if(((imagen[k]<<7)&(mensaje[i]<<k))!=0){
imagen[k]=imagen[k]|1; //HACE UN OR CON EL NUMERO 00000001 CON EL MENSAJE
}else{
imagen[k]=imagen[k]&~1; //HACE UN AND EL NUMERO 11111110
}
}
}
}
// _____________________________________________________________________________
void revelar(unsigned char imagen[],char mensajeRevelado[]){
int i=0;
do{
mensajeRevelado[i]=0;//Pongo a 0 el caracter con el que voy a operar para que no haya basura
//Recorro los 8 bytes primeros de la imagen
for(int k=0;k<8;k++){
mensajeRevelado[i]=((mensajeRevelado[i]>>k)|(imagen[k]<<7));//Desplazo el mensaje tantas posiciones como bytes haya recorrido y el byte de la imagen también lo desplazo para sólo tener algo de la forma 10000000
}
i++;
}while(mensajeRevelado[i]!='\0');//Voy metiendo caracteres hasta llegar al caracter \0
}
// _____________________________________________________________________________
int main(){
//Declaración de variables para utilizar durante la ejecución
const int MAXBUFFER= 1000000;
const int MAXNOMBRE= 100;
char nombre_imagen[MAXNOMBRE];
char nombreIMGSalida[MAXNOMBRE];//Nombre de la imagen de salida
unsigned char buffer[MAXBUFFER];
int filas,columnas;//Las filas y columnas de la imagen
TipoImagen bncolor;//El tipo de imagen que es
char mensaje[MAXNOMBRE];//EL mensaje que se ocultará o revelará de la imagen
bool flag=true;//Para saber si falla la ocultación o revelación
int n=0;
do{
cout<<"Introduce una opción:\n(1) Ocultar\n(2) Revelar\n(0) Exit\n";
cin>>n;
cin.ignore();
switch(n){
case 1:
lecturaTeclado(nombre_imagen,MAXNOMBRE,(char *)"Introduce el nombre de la imagen para codificar el mensaje:");//Pido la imagen a usar
lecturaTipoIMG(nombre_imagen,bncolor,filas,columnas);//Compruebo el tipo de imagen
lecturaIMG(nombre_imagen,bncolor,filas,columnas,buffer);//Pido la imagen a usar
lecturaTeclado(nombreIMGSalida,MAXNOMBRE,(char *)"Introduce el nombre de la imagen de salida:");//Pido el nombre de la imagen a la salida
do{
lecturaTeclado(mensaje,MAXNOMBRE,(char *)"Introduce el mensaje a ocultar:");//Pido el mensaje al usuario
}while(compruebaLectura(mensaje)); //Compruebo que tenga menos de 100 caracteres
cout<<"Ocultando...\n";
ocultar(buffer,mensaje);
if(bncolor==IMG_PGM){
flag=EscribirImagenPGM(strcat(nombreIMGSalida,".pgm"),buffer,filas,columnas);
}
else if(bncolor==IMG_PPM){
flag=EscribirImagenPPM(strcat(nombreIMGSalida,".ppm"),buffer,filas,columnas);
}else flag=false;
if(flag)
cout<<"Ocultación con éxito!\n ¿Que más desea hacer?\n";
else
cout<<"Upps..El mensaje no se ha podido ocultar\n ¿Que más desea hacer?\n";
break;
case 2:
lecturaTeclado(nombre_imagen,MAXNOMBRE,(char *)"Introduce el nombre de la imagen con el mensaje codificado:");//Pido la imagen a usar
lecturaTipoIMG(nombre_imagen,bncolor,filas,columnas);//Compruebo el tipo de Imagen a descodificar
lecturaIMG(nombre_imagen,bncolor,filas,columnas,buffer);//Pido la imagen a usar
cout<<"Revelanado el mensaje...\n";
revelar(buffer,mensaje);
cout<<"El mensaje es: "<<mensaje <<"\n¿Que más desea hacer?\n";
break;
case 0:
break;
}
}while(n!=0);
}
| 34.369128 | 213 | 0.737161 |
27328566237e55700f7895bf93f686526d64ee99 | 3,341 | cpp | C++ | tests/src/QtSettingsUtilsTests.cpp | oclero/qtutils | 477d65211a15bffabe11d9f0b526c917893ae8ee | [
"MIT"
] | null | null | null | tests/src/QtSettingsUtilsTests.cpp | oclero/qtutils | 477d65211a15bffabe11d9f0b526c917893ae8ee | [
"MIT"
] | null | null | null | tests/src/QtSettingsUtilsTests.cpp | oclero/qtutils | 477d65211a15bffabe11d9f0b526c917893ae8ee | [
"MIT"
] | null | null | null | #include "QtSettingsUtilsTests.hpp"
#include <QTest>
#include <oclero/QtSettingsUtils.hpp>
constexpr auto SETTINGS_KEY = "Toto";
using namespace oclero;
void QtSettingsUtilsTests::init() {
{
QSettings qSettings;
qSettings.remove(SETTINGS_KEY);
}
}
void QtSettingsUtilsTests::cleanup() {
{
QSettings qSettings;
qSettings.remove(SETTINGS_KEY);
}
}
void QtSettingsUtilsTests::test_tryLoadInexistentSetting_enum() const {
QSettings settings;
auto const optionalValue = tryLoadSetting<DummyEnum>(settings, SETTINGS_KEY);
QVERIFY(!optionalValue.has_value());
}
void QtSettingsUtilsTests::test_tryLoadInvalidSetting_enum() const {
{ QSettings{}.setValue(SETTINGS_KEY, "1"); }
QSettings settings;
auto const optionalValue = tryLoadSetting<DummyEnum>(settings, SETTINGS_KEY);
QVERIFY(!optionalValue.has_value());
}
void QtSettingsUtilsTests::test_tryLoadValidSetting_enum() const {
{ QSettings{}.setValue(SETTINGS_KEY, "DummyValue2"); }
QSettings settings;
auto const optionalValue = tryLoadSetting<DummyEnum>(settings, SETTINGS_KEY);
QVERIFY(optionalValue.has_value() && optionalValue.value() == DummyEnum::DummyValue2);
}
void QtSettingsUtilsTests::test_tryLoadInexistentSetting_int() const {
QSettings settings;
auto const optionalValue = tryLoadSetting<int>(settings, SETTINGS_KEY);
QVERIFY(!optionalValue.has_value());
}
void QtSettingsUtilsTests::test_tryLoadInvalidSetting_int() const {
{ QSettings{}.setValue(SETTINGS_KEY, "abc"); }
QSettings settings;
auto const optionalValue = tryLoadSetting<int>(settings, SETTINGS_KEY);
QVERIFY(!optionalValue.has_value());
}
void QtSettingsUtilsTests::test_tryLoadValidSetting_int() const {
{ QSettings{}.setValue(SETTINGS_KEY, 42); }
QSettings settings;
auto const optionalValue = tryLoadSetting<int>(settings, SETTINGS_KEY);
QVERIFY(optionalValue.has_value() && optionalValue.value() == 42);
}
void QtSettingsUtilsTests::test_loadValidSetting() const {
{ QSettings{}.setValue(SETTINGS_KEY, 42); }
QSettings settings;
auto const value = loadSetting<int>(settings, SETTINGS_KEY);
QVERIFY(value == 42);
}
void QtSettingsUtilsTests::test_loadInvalidSetting() const {
QSettings settings;
auto const value = loadSetting<int>(settings, SETTINGS_KEY, 12);
QVERIFY(value == 12);
}
void QtSettingsUtilsTests::test_saveSetting_int() const {
{
QSettings settings;
saveSetting<int>(settings, SETTINGS_KEY, 42);
}
auto const value = QSettings{}.value(SETTINGS_KEY).toInt();
QVERIFY(value == 42);
}
void QtSettingsUtilsTests::test_saveSetting_enum() const {
{
QSettings settings;
saveSetting<DummyEnum>(settings, SETTINGS_KEY, DummyEnum::DummyValue2);
}
// Enum are saved as strings and parsed.
auto const value = QSettings{}.value(SETTINGS_KEY).toString();
QVERIFY(value == "DummyValue2");
}
void QtSettingsUtilsTests::test_useQStringAsKey() const {
auto qStringKey = QString{ SETTINGS_KEY };
{
QSettings settings;
saveSetting<int>(settings, qStringKey, 42);
}
auto const value = QSettings{}.value(SETTINGS_KEY).toInt();
QVERIFY(value == 42);
QSettings{}.setValue(qStringKey, "DummyValue");
{
QSettings settings;
auto const valueInSettings = loadSetting<QString>(settings, qStringKey, QString{});
QVERIFY(valueInSettings == "DummyValue");
}
}
| 29.052174 | 88 | 0.747082 |
2734ad912439e8edf65e2870e1d3906a68a2fbd6 | 13,656 | hpp | C++ | src/Memory/AffixAllocator.hpp | epicbrownie/Epic | c54159616b899bb24c6d59325d582e73f2803ab6 | [
"MIT"
] | null | null | null | src/Memory/AffixAllocator.hpp | epicbrownie/Epic | c54159616b899bb24c6d59325d582e73f2803ab6 | [
"MIT"
] | 29 | 2016-08-01T14:50:12.000Z | 2017-12-17T20:28:27.000Z | src/Memory/AffixAllocator.hpp | epicbrownie/Epic | c54159616b899bb24c6d59325d582e73f2803ab6 | [
"MIT"
] | null | null | null | //////////////////////////////////////////////////////////////////////////////
//
// Copyright (c) 2016 Ronnie Brohn (EpicBrownie)
//
// Distributed under The MIT License (MIT).
// (See accompanying file License.txt or copy at
// https://opensource.org/licenses/MIT)
//
// Please report any bugs, typos, or suggestions to
// https://github.com/epicbrownie/Epic/issues
//
//////////////////////////////////////////////////////////////////////////////
#pragma once
#include <Epic/Memory/MemoryBlock.hpp>
#include <Epic/Memory/detail/AllocatorTraits.hpp>
#include <Epic/Memory/detail/AllocatorHelpers.hpp>
#include <Epic/Memory/detail/AffixHelpers.hpp>
#include <cassert>
#include <cstdint>
#include <algorithm>
#include <type_traits>
//////////////////////////////////////////////////////////////////////////////
namespace Epic
{
template<class Allocator, class Prefix, class Suffix = void>
class AffixAllocator;
}
//////////////////////////////////////////////////////////////////////////////
/// AffixAllocator<A, Prefix, Suffix>
template<class A, class Prefix, class Suffix>
class Epic::AffixAllocator
{
static_assert(std::is_default_constructible<A>::value, "The affix allocator must be default-constructible.");
public:
using Type = Epic::AffixAllocator<A, Prefix, Suffix>;
using AllocatorType = A;
using PrefixType = Prefix;
using SuffixType = Suffix;
public:
static constexpr size_t Alignment = A::Alignment;
private:
static constexpr bool HasPrefix = !std::is_same<Prefix, void>::value;
static constexpr bool HasSuffix = !std::is_same<Suffix, void>::value;
static constexpr size_t UnalignedPrefixSize = detail::AffixSize<Prefix>::value;
static constexpr size_t PrefixSize = detail::RoundToAligned(UnalignedPrefixSize, Alignment);
static constexpr size_t SuffixSize = detail::AffixSize<Suffix>::value;
using AlignmentMemento = uint16_t;
private:
static constexpr size_t NonAllocSize = (PrefixSize + SuffixSize + sizeof(AlignmentMemento));
public:
static constexpr size_t MinAllocSize = A::MinAllocSize;
static constexpr size_t MaxAllocSize = A::MaxAllocSize - NonAllocSize;
static constexpr bool IsShareable = A::IsShareable;
static_assert(!HasPrefix || std::is_default_constructible<Prefix>::value, "The Prefix Type must be default-constructible.");
static_assert(!HasSuffix || std::is_default_constructible<Suffix>::value, "The Suffix Type must be default-constructible.");
static_assert(A::MaxAllocSize > NonAllocSize && MaxAllocSize > MinAllocSize,
"The affix sizes are too large for the backing Allocator.");
private:
AllocatorType m_Allocator;
public:
constexpr AffixAllocator()
noexcept(std::is_nothrow_default_constructible<A>::value) = default;
template<typename = std::enable_if_t<std::is_copy_constructible<A>::value>>
constexpr AffixAllocator(const Type& obj)
noexcept(std::is_nothrow_copy_constructible<A>::value)
: m_Allocator{ obj.m_Allocator }
{ }
template<typename = std::enable_if_t<std::is_move_constructible<A>::value>>
constexpr AffixAllocator(Type&& obj)
noexcept(std::is_nothrow_move_constructible<A>::value)
: m_Allocator{ std::move(obj.m_Allocator) }
{ }
template<typename = std::enable_if_t<std::is_copy_assignable<A>::value>>
AffixAllocator& operator = (const Type& obj)
noexcept(std::is_nothrow_copy_assignable<A>::value)
{
m_Allocator = obj.m_Allocator;
return *this;
}
template<typename = std::enable_if_t<std::is_move_assignable<A>::value>>
AffixAllocator& operator = (Type&& obj)
noexcept(std::is_nothrow_move_assignable<A>::value)
{
m_Allocator = std::move(obj.m_Allocator);
return *this;
}
private:
static constexpr Blk ClientToAffixedBlock(const Blk& blk, const AlignmentMemento& alignment) noexcept
{
return Blk
{
reinterpret_cast<unsigned char*>(blk.Ptr) - detail::RoundToAligned(UnalignedPrefixSize, alignment),
blk.Size + (detail::RoundToAligned(UnalignedPrefixSize, alignment) + SuffixSize + sizeof(AlignmentMemento))
};
}
static constexpr Blk AffixedToClientBlock(const Blk& blk, const AlignmentMemento& alignment) noexcept
{
return Blk
{
reinterpret_cast<unsigned char*>(blk.Ptr) + detail::RoundToAligned(UnalignedPrefixSize, alignment),
blk.Size - (detail::RoundToAligned(UnalignedPrefixSize, alignment) + SuffixSize + sizeof(AlignmentMemento))
};
}
static constexpr void* AffixedToPrefixPtr(const Blk& blk) noexcept
{
return blk.Ptr;
}
static constexpr void* AffixedToSuffixPtr(const Blk& blk) noexcept
{
return static_cast<void*>(reinterpret_cast<unsigned char*>(blk.Ptr) + blk.Size - SuffixSize);
}
static constexpr AlignmentMemento* AffixedToAlignmentMementoPtr(const Blk& blk)
{
return reinterpret_cast<AlignmentMemento*>(reinterpret_cast<unsigned char*>(AffixedToSuffixPtr(blk)) - sizeof(AlignmentMemento));
}
static constexpr void* ClientToPrefixPtr(const Blk& blk, const AlignmentMemento& alignment) noexcept
{
return static_cast<void*>(reinterpret_cast<unsigned char*>(blk.Ptr) - detail::RoundToAligned(UnalignedPrefixSize, alignment));
}
static constexpr void* ClientToSuffixPtr(const Blk& blk) noexcept
{
return static_cast<void*>(reinterpret_cast<unsigned char*>(blk.Ptr) + blk.Size + sizeof(AlignmentMemento));
}
static constexpr AlignmentMemento* ClientToAlignmentMementoPtr(const Blk& blk)
{
return reinterpret_cast<AlignmentMemento*>(reinterpret_cast<unsigned char*>(blk.Ptr) + blk.Size);
}
public:
/* Returns whether or not this allocator is responsible for the block Blk. */
inline bool Owns(const Blk& blk) const noexcept
{
return blk ? m_Allocator.Owns(ClientToAffixedBlock(blk, *ClientToAlignmentMementoPtr(blk))) : false;
}
public:
/* Returns a block of uninitialized memory.
The memory will be surrounded by constructed Affix objects. */
template<typename = std::enable_if_t<detail::CanAllocate<A>::value>>
Blk Allocate(size_t sz) noexcept
{
// Verify that the requested size isn't zero.
if (sz == 0) return{ nullptr, 0 };
// Verify that the requested size is within our allowed bounds
if (sz < MinAllocSize || sz > MaxAllocSize)
return{ nullptr, 0 };
// Allocate the block
auto blk = m_Allocator.Allocate(sz + NonAllocSize);
if (!blk) return{ nullptr, 0 };
// Construct the Prefix and Suffix objects
if constexpr (HasPrefix)
::new (AffixedToPrefixPtr(blk)) Prefix();
if constexpr (HasSuffix)
::new (AffixedToSuffixPtr(blk)) Suffix();
// Store alignment memento
const auto memento = static_cast<AlignmentMemento>(Alignment);
*AffixedToAlignmentMementoPtr(blk) = memento;
return AffixedToClientBlock(blk, memento);
}
/* Returns a block of uninitialized memory (aligned to 'alignment').
The memory will be surrounded by constructed Affix objects. */
template<typename = std::enable_if_t<detail::CanAllocateAligned<A>::value>>
Blk AllocateAligned(size_t sz, size_t alignment = Alignment) noexcept
{
// Verify that the alignment is acceptable
if (!detail::IsGoodAlignment(alignment))
return{ nullptr, 0 };
assert(alignment <= std::numeric_limits<AlignmentMemento>::max() &&
"AffixAllocator::AllocateAligned - Unsupported alignment value");
// Verify that the requested size isn't zero.
if (sz == 0) return{ nullptr, 0 };
// Verify that the requested size is within our allowed bounds
if (sz < MinAllocSize || sz > MaxAllocSize)
return{ nullptr, 0 };
// Allocate the block
const size_t szNew = sz + detail::RoundToAligned(UnalignedPrefixSize, alignment) + sizeof(AlignmentMemento) + SuffixSize;
auto blk = m_Allocator.AllocateAligned(szNew, alignment);
if (!blk) return{ nullptr, 0 };
// Construct the Prefix and Suffix objects
if constexpr (HasPrefix)
::new (AffixedToPrefixPtr(blk)) Prefix();
if constexpr (HasSuffix)
::new (AffixedToSuffixPtr(blk)) Suffix();
// Store alignment memento
const auto memento = static_cast<AlignmentMemento>(alignment);
*AffixedToAlignmentMementoPtr(blk) = memento;
return AffixedToClientBlock(blk, memento);
}
/* Attempts to reallocate the memory of blk to the new size sz.
The Affix objects will be moved as necessary. */
template<typename = std::enable_if_t<detail::CanReallocate<A>::value && detail::AffixBuffer<Suffix>::CanStore>>
bool Reallocate(Blk& blk, size_t sz)
{
// If the block isn't valid, delegate to Allocate
if (!blk)
{
if constexpr (detail::CanAllocate<Type>::value)
return (bool)(blk = Allocate(sz));
}
// If the requested size is zero, delegate to Deallocate
if (sz == 0)
{
if constexpr (detail::CanDeallocate<Type>::value)
Deallocate(blk);
blk = { nullptr, 0 };
return true;
}
// Verify that the requested size is within our allowed bounds
if (sz < MinAllocSize || sz > MaxAllocSize)
return false;
// Move the Suffix object to the stack
auto pSuffix = GetSuffixObject(blk);
detail::AffixBuffer<Suffix> suffix{ pSuffix };
// Reallocate the block
Blk affixedBlk = ClientToAffixedBlock(blk, Alignment);
if (!m_Allocator.Reallocate(affixedBlk, sz + NonAllocSize))
{
suffix.Restore(pSuffix);
return false;
}
// Place the Suffix object and the alignment memento
suffix.Restore(AffixedToSuffixPtr(affixedBlk));
*AffixedToAlignmentMementoPtr(affixedBlk) = Alignment;
blk = AffixedToClientBlock(affixedBlk, Alignment);
return true;
}
/* Attempts to reallocate the memory of blk to the new size 'sz' (aligned to 'alignment').
It must have been allocated through AllocateAligned().
The Affix objects will be moved as necessary. */
template<typename = std::enable_if_t<detail::CanReallocateAligned<A>::value && detail::AffixBuffer<Suffix>::CanStore>>
bool ReallocateAligned(Blk& blk, size_t sz, size_t alignment = Alignment)
{
// Verify that the alignment is acceptable
if (!detail::IsGoodAlignment(alignment))
return false;
assert(alignment <= std::numeric_limits<AlignmentMemento>::max() &&
"AffixAllocator::ReallocateAligned - Unsupported alignment value");
// If the block isn't valid, delegate to AllocateAligned
if (!blk)
{
if constexpr (detail::CanAllocateAligned<Type>::value)
return (bool)(blk = AllocateAligned(sz, alignment));
}
// If the requested size is zero, delegate to DeallocateAligned
if (sz == 0)
{
if constexpr (detail::CanDeallocateAligned<Type>::value)
DeallocateAligned(blk);
blk = { nullptr, 0 };
return true;
}
// Verify that the requested size is within our allowed bounds
if (sz < MinAllocSize || sz > MaxAllocSize)
return false;
// Verify alignment memento
const AlignmentMemento memento = *ClientToAlignmentMementoPtr(blk);
assert(detail::IsGoodAlignment(memento) &&
"AffixAllocator::ReallocateAligned - Either this block was not allocated aligned or the heap has been corrupted");
assert(alignment == memento &&
"AffixAllocator::ReallocateAligned - Once allocated, the alignment of an allocated block cannot be changed");
// Move the Suffix object to the stack
auto pSuffix = GetSuffixObject(blk);
detail::AffixBuffer<Suffix> suffix{ pSuffix };
// Reallocate the block
Blk affixedBlk = ClientToAffixedBlock(blk, memento);
size_t szNew = sz + detail::RoundToAligned(UnalignedPrefixSize, alignment) + sizeof(AlignmentMemento) + SuffixSize;
if (!m_Allocator.ReallocateAligned(affixedBlk, szNew))
{
suffix.Restore(pSuffix);
return false;
}
// Place the Suffix object and the alignment memento
suffix.Restore(AffixedToSuffixPtr(affixedBlk));
*AffixedToAlignmentMementoPtr(affixedBlk) = memento;
blk = AffixedToClientBlock(affixedBlk, memento);
return true;
}
public:
/* Frees the memory for blk.
The surrounding Affix objects will also be destroyed. */
template<typename = std::enable_if_t<detail::CanDeallocate<A>::value>>
void Deallocate(const Blk& blk)
{
if (!blk) return;
assert(Owns(blk) &&
"AffixAllocator::Deallocate - "
"Attempted to free a block that was not allocated by this allocator");
// Deconstruct the affix objects
if (HasPrefix) GetPrefixObject(blk)->~Prefix();
if (HasSuffix) GetSuffixObject(blk)->~Suffix();
// Deallocate the affixed block
m_Allocator.Deallocate(ClientToAffixedBlock(blk, static_cast<AlignmentMemento>(Alignment)));
}
/* Frees the memory for blk. It must have been allocated through AllocateAligned().
The surrounding Affix objects will also be destroyed. */
template<typename = std::enable_if_t<detail::CanDeallocateAligned<A>::value>>
void DeallocateAligned(const Blk& blk)
{
if (!blk) return;
assert(Owns(blk) &&
"AffixAllocator::DeallocateAligned - "
"Attempted to free a block that was not allocated by this allocator");
// Verify alignment memento
assert(detail::IsGoodAlignment(*ClientToAlignmentMementoPtr(blk)) &&
"AffixAllocator::DeallocateAligned - "
"Either this block was not allocated aligned or the heap has been corrupted");
// Deconstruct the affix objects
if (HasPrefix) GetPrefixObject(blk)->~Prefix();
if (HasSuffix) GetSuffixObject(blk)->~Suffix();
// Deallocate the affixed block
m_Allocator.DeallocateAligned(ClientToAffixedBlock(blk, *ClientToAlignmentMementoPtr(blk)));
}
public:
static constexpr Prefix* GetPrefixObject(const Blk& blk, size_t alignment = Alignment) noexcept
{
return HasPrefix ?
reinterpret_cast<Prefix*>(ClientToPrefixPtr(blk, static_cast<AlignmentMemento>(alignment))) :
nullptr;
}
static constexpr Suffix* GetSuffixObject(const Blk& blk) noexcept
{
return HasSuffix ? reinterpret_cast<Suffix*>(ClientToSuffixPtr(blk)) : nullptr;
}
};
| 33.80198 | 131 | 0.719098 |
2738cad2ad0f4fd1993a2d3118846cbfdce350c9 | 6,275 | cpp | C++ | src/morda/widgets/label/NinePatch.cpp | Mactor2018/morda | 7194f973783b4472b8671fbb52e8c96e8c972b90 | [
"MIT"
] | 1 | 2018-10-27T05:07:05.000Z | 2018-10-27T05:07:05.000Z | src/morda/widgets/label/NinePatch.cpp | Mactor2018/morda | 7194f973783b4472b8671fbb52e8c96e8c972b90 | [
"MIT"
] | null | null | null | src/morda/widgets/label/NinePatch.cpp | Mactor2018/morda | 7194f973783b4472b8671fbb52e8c96e8c972b90 | [
"MIT"
] | null | null | null | #include <utki/util.hpp>
#include <utki/types.hpp>
#include "../../Morda.hpp"
#include "../../util/util.hpp"
#include "../proxy/ResizeProxy.hpp"
#include "NinePatch.hpp"
using namespace morda;
namespace{
const char* ninePatchLayout_c = R"qwertyuiop(
Row{
layout{dx{fill}}
Image{
name{morda_lt}
}
Image{
layout{dx{0}weight{1}}
name{morda_t}
}
Image{
name{morda_rt}
}
}
Row{
layout{
dx{max}
weight{1}
}
Image{
name{morda_l}
layout{dy{fill}}
}
Pile{
name{morda_content}
layout{
weight{1}
dy{max}
}
Image{
name{morda_m}
layout{dx{fill}dy{fill}}
}
}
Image{
name{morda_r}
layout{dy{fill}}
}
}
Row{
layout{dx{fill}}
Image{
name{morda_lb}
}
Image{
layout{dx{0}weight{1}}
name{morda_b}
}
Image{
name{morda_rb}
}
}
)qwertyuiop";
}
NinePatch::NinePatch(const stob::Node* chain) :
Widget(chain),
BlendingWidget(chain),
Column(stob::parse(ninePatchLayout_c).get())
{
this->imageMatrix_v[0][0] = this->findByNameAs<Image>("morda_lt");
this->imageMatrix_v[0][1] = this->findByNameAs<Image>("morda_t");
this->imageMatrix_v[0][2] = this->findByNameAs<Image>("morda_rt");
this->imageMatrix_v[1][0] = this->findByNameAs<Image>("morda_l");
this->imageMatrix_v[1][1] = this->findByNameAs<Image>("morda_m");
this->imageMatrix_v[1][2] = this->findByNameAs<Image>("morda_r");
this->imageMatrix_v[2][0] = this->findByNameAs<Image>("morda_lb");
this->imageMatrix_v[2][1] = this->findByNameAs<Image>("morda_b");
this->imageMatrix_v[2][2] = this->findByNameAs<Image>("morda_rb");
this->onBlendingChanged();
this->content_v = this->findByNameAs<Pile>("morda_content");
if(auto n = getProperty(chain, "left")){
this->borders.left() = dimValueFromSTOB(*n);//'min' is by default, but not allowed to specify explicitly, as well as 'max' and 'fill'
}else{
this->borders.left() = LayoutParams::min_c;
}
if(auto n = getProperty(chain, "right")){
this->borders.right() = dimValueFromSTOB(*n);
}else{
this->borders.right() = LayoutParams::min_c;
}
if(auto n = getProperty(chain, "top")){
this->borders.top() = dimValueFromSTOB(*n);
}else{
this->borders.top() = LayoutParams::min_c;
}
if(auto n = getProperty(chain, "bottom")){
this->borders.bottom() = dimValueFromSTOB(*n);
}else{
this->borders.bottom() = LayoutParams::min_c;
}
if(auto n = getProperty(chain, "centerVisible")){
this->setCenterVisible(n->asBool());
}
//this should go after setting up border widgets
if(const stob::Node* n = getProperty(chain, "image")){
this->setNinePatch(morda::Morda::inst().resMan.load<ResNinePatch>(n->value()));
}
if(chain){
this->content_v->add(*chain);
}
}
void NinePatch::render(const morda::Matr4r& matrix) const {
this->Column::render(matrix);
}
void NinePatch::setNinePatch(std::shared_ptr<const ResNinePatch> np){
this->image = std::move(np);
this->scaledImage.reset();
this->applyImages();
this->clearCache();
}
Sidesr NinePatch::getActualBorders() const noexcept{
Sidesr ret;
for(auto i = 0; i != ret.size(); ++i){
if(this->borders[i] >= 0){
ret[i] = this->borders[i];
}else if(!this->image){
ret[i] = 0;
}else{
ret[i] = this->image->borders()[i];
}
}
return ret;
}
void NinePatch::applyImages(){
if(!this->image){
for(auto& i : this->imageMatrix_v){
for(auto& j : i){
j->setImage(nullptr);
}
}
return;
}
auto& minBorders = this->image->borders();
// TRACE(<< "minBorders = " << minBorders << std::endl)
{
//non-const call to getLayoutParams requests relayout which is not necessarily needed, so try to avoid it if possible
auto& layoutParams = utki::makePtrToConst(this->imageMatrix_v[0][0].get())->getLayoutParams();
if(this->borders.left() == LayoutParams::min_c){
if(layoutParams.dim.x != minBorders.left()){
auto& lp = this->imageMatrix_v[0][0].get()->getLayoutParams();
lp.dim.x = minBorders.left();
}
}else{
if(layoutParams.dim.x != this->borders.left()){
auto& lp = this->imageMatrix_v[0][0].get()->getLayoutParams();
lp.dim.x = this->borders.left();
}
}
if(this->borders.top() == LayoutParams::min_c){
if(layoutParams.dim.y != minBorders.top()){
auto& lp = this->imageMatrix_v[0][0].get()->getLayoutParams();
lp.dim.y = minBorders.top();
}
}else{
if(layoutParams.dim.y != this->borders.top()){
auto& lp = this->imageMatrix_v[0][0].get()->getLayoutParams();
lp.dim.y = this->borders.top();
}
}
// TRACE(<< "layoutParams.dim = " << layoutParams.dim << std::endl)
}
{
//non-const call to getLayoutParams requests relayout which is not necessarily needed, so try to avoid it if possible
auto& layoutParams = utki::makePtrToConst(this->imageMatrix_v[2][2].get())->getLayoutParams();
if(this->borders.right() == LayoutParams::min_c){
if(layoutParams.dim.x != minBorders.right()){
auto& lp = this->imageMatrix_v[2][2]->getLayoutParams();
lp.dim.x = minBorders.right();
}
}else{
if(layoutParams.dim.x != this->borders.right()){
auto& lp = this->imageMatrix_v[2][2]->getLayoutParams();
lp.dim.x = this->borders.right();
}
}
if(this->borders.bottom() == LayoutParams::min_c){
if(layoutParams.dim.y != minBorders.bottom()){
auto& lp = this->imageMatrix_v[2][2]->getLayoutParams();
lp.dim.y = minBorders.bottom();
}
}else{
if(layoutParams.dim.y != this->borders.bottom()){
auto& lp = this->imageMatrix_v[2][2]->getLayoutParams();
lp.dim.y = this->borders.bottom();
}
}
// TRACE(<< "lp.dim = " << lp.dim << std::endl)
}
// TRACE(<< "this->borders = " << this->borders << std::endl)
this->scaledImage = this->image->get(this->borders);
for(unsigned i = 0; i != 3; ++i){
for(unsigned j = 0; j != 3; ++j){
this->imageMatrix_v[i][j]->setImage(this->scaledImage->images()[i][j]);
}
}
}
void NinePatch::setCenterVisible(bool visible){
ASSERT(this->imageMatrix_v[1][1])
this->imageMatrix_v[1][1]->setVisible(visible);
}
void NinePatch::onBlendingChanged(){
for(unsigned i = 0; i != 3; ++i){
for(unsigned j = 0; j != 3; ++j){
this->imageMatrix_v[i][j]->setBlendingParams(this->blendingParams());
}
}
}
| 23.501873 | 135 | 0.631076 |
27398d4050dfe38b74e7be92aaa139b91bd37c3e | 988 | cpp | C++ | src/input/InputConfiguration.cpp | jaspervdj/JVGS | 59be35ed61b355b445b82bf32796c0f229e21b60 | [
"WTFPL"
] | 31 | 2015-02-02T04:51:10.000Z | 2021-02-20T10:04:41.000Z | src/input/InputConfiguration.cpp | jaspervdj/JVGS | 59be35ed61b355b445b82bf32796c0f229e21b60 | [
"WTFPL"
] | 2 | 2016-08-30T09:26:31.000Z | 2016-09-14T20:01:20.000Z | src/input/InputConfiguration.cpp | jaspervdj/JVGS | 59be35ed61b355b445b82bf32796c0f229e21b60 | [
"WTFPL"
] | 7 | 2015-02-02T05:02:09.000Z | 2021-12-24T06:53:01.000Z | #include "InputConfiguration.h"
#include "../core/LogManager.h"
using namespace jvgs::core;
using namespace std;
namespace jvgs
{
namespace input
{
InputConfiguration::InputConfiguration()
{
}
InputConfiguration::~InputConfiguration()
{
}
InputConfiguration *InputConfiguration::getConfiguration()
{
static InputConfiguration configuration;
return &configuration;
}
const Key &InputConfiguration::getKey(const string &action)
{
map<string, Key>::iterator result = keys.find(action);
if(result != keys.end())
return result->second;
else
LogManager::getInstance()->error(
"No key defined for action '%s'", action.c_str());
}
void InputConfiguration::setKey(const string &action, const Key &key)
{
keys[action] = key;
}
}
}
| 23.52381 | 77 | 0.554656 |
273cc8c66a8ab4bb13e42655a91d801541d9d465 | 1,609 | hpp | C++ | src/Core/Window.hpp | llGuy/Ondine | 325c2d3ea5bd5ef5456b0181c53ad227571fada3 | [
"MIT"
] | 1 | 2022-01-24T18:15:56.000Z | 2022-01-24T18:15:56.000Z | src/Core/Window.hpp | llGuy/Ondine | 325c2d3ea5bd5ef5456b0181c53ad227571fada3 | [
"MIT"
] | null | null | null | src/Core/Window.hpp | llGuy/Ondine | 325c2d3ea5bd5ef5456b0181c53ad227571fada3 | [
"MIT"
] | null | null | null | #pragma once
#include "IO.hpp"
#include <string_view>
#include <GLFW/glfw3.h>
#include <glm/glm.hpp>
#include "Event.hpp"
#include "Time.hpp"
#include "Utils.hpp"
namespace Ondine::Core {
enum class WindowMode {
Fullscreen,
Windowed
};
using SurfaceCreationProc = void(*)(
struct VkInstance_T *instance,
struct VkSurfaceKHR_T **surface,
void *windowHandle);
/* To pass to graphics context */
struct WindowContextInfo {
void *handle;
Resolution resolution;
SurfaceCreationProc surfaceCreateProc;
};
class Window {
public:
Window(
WindowMode mode,
const std::string_view &title,
const Resolution &resolution = {});
WindowContextInfo init(OnEventProc callback);
void pollInput();
void toggleFullscreen();
void changeCursorDisplay(bool show);
static void initWindowAPI();
private:
void keyCallback(int key, int scancode, int action, int mods) const;
void mouseButtonCallback(int button, int action, int mods) const;
void charCallback(unsigned int codePoint) const;
void cursorMoveCallback(float x, float y) const;
void resizeCallback(unsigned width, unsigned height);
void scrollCallback(float x, float y) const;
void closeCallback() const;
static void createVulkanSurface(
struct VkInstance_T *instance,
struct VkSurfaceKHR_T **surface,
void *windowHandle);
private:
GLFWwindow *mHandle;
Resolution mResolution;
Resolution mPreviousWindowedResolution;
OnEventProc mEventCallback;
WindowMode mWindowMode;
bool mIsFullscreen;
bool mResized;
glm::ivec2 mPreviousWindowedPosition;
const std::string_view mTitle;
};
}
| 22.347222 | 70 | 0.747669 |
2744efcee9ee1238eb1db6f9df77044fae3d1a37 | 156 | hpp | C++ | game_server/src/server_ui.hpp | CellWarsOfficial/CellWars | 40b1e956c871ee686062eba1251a9f9a43d86c2c | [
"Apache-2.0"
] | 5 | 2017-07-20T10:36:23.000Z | 2018-01-30T16:18:31.000Z | game_server/src/server_ui.hpp | CellWarsOfficial/CellWars | 40b1e956c871ee686062eba1251a9f9a43d86c2c | [
"Apache-2.0"
] | null | null | null | game_server/src/server_ui.hpp | CellWarsOfficial/CellWars | 40b1e956c871ee686062eba1251a9f9a43d86c2c | [
"Apache-2.0"
] | null | null | null | #ifndef SERVER_UI_H
#define SERVER_UI_H
#include <log.hpp>
extern Game *game;
void signal_interpreter(int s);
void init_server_ui(Logger *log);
#endif
| 12 | 33 | 0.762821 |
2746c88ef909c7345bcb0470a83a4b4fe1616962 | 69,161 | cpp | C++ | cdl/CDL_interface.cpp | disi33/libRetroReversing | 1c825a1971820dbb73fcc96aa444408f6b65803d | [
"MIT"
] | null | null | null | cdl/CDL_interface.cpp | disi33/libRetroReversing | 1c825a1971820dbb73fcc96aa444408f6b65803d | [
"MIT"
] | null | null | null | cdl/CDL_interface.cpp | disi33/libRetroReversing | 1c825a1971820dbb73fcc96aa444408f6b65803d | [
"MIT"
] | null | null | null | #include <stdio.h>
#include <stdlib.h>
#include <string.h>
#ifdef _WIN32
#ifndef _WIN32_WINNT
#define _WIN32_WINNT 0x0500
#endif
#include <windows.h>
#else
#include <sys/time.h>
#endif
#include <stdio.h>
#include <map>
#include <fstream>
#include <iostream>
#include <sstream>
#include "../cdl/CDL_FileWriting.hpp"
#include "nlohmann/json.hpp"
using json = nlohmann::json;
using namespace std;
#include "CDL.hpp"
extern json fileConfig;
extern json reConfig;
extern json playthough_function_usage;
extern json libRR_console_constants;
json libultra_signatures;
json linker_map_file;
#define USE_CDL 1;
extern std::map<uint32_t,string> memory_to_log;
extern std::map<uint32_t,char> jumps;
extern std::map<uint32_t,string> audio_address;
extern std::map<uint32_t,uint8_t> cached_jumps;
std::map<uint32_t, uint8_t*> jump_data;
extern std::map<uint32_t,uint32_t> rsp_reads;
extern std::map<uint32_t,uint32_t> rdram_reads;
std::map<uint32_t,bool> offsetHasAssembly;
extern "C" {
// TODO: move the following includes, they are for N64
// #include "../main/rom.h"
// #include "../device/r4300/tlb.h"
// #include "../device/r4300/r4300_core.h"
// #include "../device/memory/memory.h"
// TODO: need to log input and then call input.keyDown(keymod, keysym);
//
// # Variables
//
string rom_name = "UNKNOWN_ROM"; // ROM_PARAMS.headername
int corrupt_start = 0xb2b77c;
int corrupt_end = 0xb2b77c;
int difference = corrupt_end-corrupt_start;
void find_most_similar_function(uint32_t function_offset, string bytes);
bool libRR_finished_boot_rom = false;
string last_reversed_address = "";
bool should_reverse_jumps = false;
bool should_change_jumps = false;
int frame_last_reversed = 0;
int time_last_reversed = 0;
string libRR_game_name = "";
string ucode_crc = "";
// string next_dma_type = "";
// uint32_t previous_function = 0;
std::vector<uint32_t> function_stack = std::vector<uint32_t>();
std::vector<uint32_t> previous_ra; // previous return address
std::map<uint32_t, std::map<string, string> > addresses;
uint32_t rspboot = 0;
#define NUMBER_OF_MANY_READS 40
#define NUMBER_OF_MANY_WRITES 40
//
// # Toggles
//
bool support_n64_prints = false;
bool cdl_log_memory = false;
bool tag_functions = false;
bool log_notes = false;
bool log_function_calls = false;
bool log_ostasks = false;
bool log_rsp = false;
void cdl_keyevents(int keysym, int keymod) {
#ifndef USE_CDL
return;
#endif
printf("event_sdl_keydown frame:%d key:%d modifier:%d \n", l_CurFrame, keysym, keymod);
should_reverse_jumps = false;
// S key
if (keysym == 115) {
printf("Lets save! \n");
main_state_save(0, NULL);
}
// L Key
if (keysym == 108) {
printf("Lets load! \n");
main_state_load(NULL);
}
// Z Key
if (keysym == 122) {
write_rom_mapping();
cdl_log_memory = !cdl_log_memory;
tag_functions = !tag_functions;
// should_change_jumps = true;
//should_reverse_jumps = true;
// show_interface();
}
}
bool createdCartBackup = false;
void backupCart() {
// libRR_game_name = alphabetic_only_name((char*)rom_name.c_str(), 21);
std::cout << "TODO: backup";
createdCartBackup = true;
}
void resetCart() {
std::cout << "TODO: reset";
}
void readLibUltraSignatures() {
std::ifstream i("libultra.json");
if (i.good()) {
i >> libultra_signatures;
}
if (libultra_signatures.find("function_signatures") == libultra_signatures.end()) {
libultra_signatures["function_signatures"] = R"([])"_json;
}
}
void saveLibUltraSignatures() {
std::ofstream o("libultra.json");
o << libultra_signatures.dump(1) << std::endl;
}
void setTogglesBasedOnConfig() {
cdl_log_memory = reConfig["shouldLogMemory"];
tag_functions = reConfig["shouldTagFunctions"];
log_notes = reConfig["shouldLogNotes"];
log_function_calls = reConfig["shouldLogFunctionCalls"];
support_n64_prints = reConfig["shouldSupportN64Prints"];
log_ostasks = reConfig["shouldLogOsTasks"];
log_rsp = reConfig["shouldLogRsp"];
}
void readJsonFromFile() {
readLibUltraSignatures();
readJsonToObject("symbols.json", linker_map_file);
readJsonToObject("./reconfig.json", reConfig);
setTogglesBasedOnConfig();
string filename = "./configs/";
filename+=rom_name;
filename += ".json";
// read a JSON file
if (!reConfig["startFreshEveryTime"]) {
cout << "Reading previous game config file \n";
readJsonToObject(filename, fileConfig);
}
if (fileConfig.find("jumps") == fileConfig.end()) {
fileConfig["jumps"] = R"([])"_json;
}
if (fileConfig.find("tlbs") == fileConfig.end()) {
fileConfig["tlbs"] = R"([])"_json;
}
if (fileConfig.find("dmas") == fileConfig.end()) {
fileConfig["dmas"] = R"([])"_json;
}
if (fileConfig.find("rsp_reads") == fileConfig.end()) {
fileConfig["rsp_reads"] = R"([])"_json;
}
if (fileConfig.find("rdram_reads") == fileConfig.end())
fileConfig["rdram_reads"] = R"([])"_json;
if (fileConfig.find("reversed_jumps") == fileConfig.end())
fileConfig["reversed_jumps"] = R"({})"_json;
if (fileConfig.find("labels") == fileConfig.end())
fileConfig["labels"] = R"([])"_json;
if (fileConfig.find("jump_returns") == fileConfig.end())
fileConfig["jump_returns"] = R"([])"_json;
if (fileConfig.find("memory_to_log") == fileConfig.end())
fileConfig["memory_to_log"] = R"([])"_json;
memory_to_log = fileConfig["memory_to_log"].get< std::map<uint32_t,string> >();
memory_to_log[0x0E5320] = "rsp.boot";
jumps = fileConfig["jumps"].get< std::map<uint32_t,char> >();
tlbs = fileConfig["tlbs"].get< std::map<uint32_t,cdl_tlb> >();
dmas = fileConfig["dmas"].get< std::map<uint32_t,cdl_dma> >();
rsp_reads = fileConfig["rsp_reads"].get< std::map<uint32_t,uint32_t> >();
rdram_reads = fileConfig["rdram_reads"].get< std::map<uint32_t,uint32_t> >();
labels = fileConfig["labels"].get< std::map<uint32_t,cdl_labels> >();
jump_returns = fileConfig["jump_returns"].get< std::map<uint32_t,cdl_jump_return> >();
}
void saveJsonToFile() {
string filename = "./configs/";
filename += rom_name;
filename += ".json";
std::ofstream o(filename);
o << fileConfig.dump(1) << std::endl;
}
void show_interface() {
int answer;
std::cout << "1) Reset ROM 2) Change corrupt number ";
std::cin >> std::hex >> answer;
if (answer == 1) {
std::cout << "Resetting ROM";
resetCart();
}
else {
std::cout << "Unknown command";
}
printf("Answer: %d \n", answer);
}
void corrupt_if_in_range(uint8_t* mem, uint32_t proper_cart_address) {
// if (proper_cart_address >= corrupt_start && proper_cart_address <= corrupt_end) { //l_CurFrame == 0x478 && length == 0x04) { //} proper_cart_address == 0xb4015c) {
// printf("save_state_before\n");
// main_state_save(0, "before_corruption");
// printBytes(mem, proper_cart_address);
// printf("MODIFIED IT!! %#08x\n\n\n", mem[proper_cart_address+1]);
// corruptBytes(mem, proper_cart_address, 10);
// printBytes(mem, proper_cart_address);
// }
}
void corruptBytes(uint8_t* mem, uint32_t cartAddr, int times) {
#ifndef USE_CDL
return;
#endif
if (times>difference) {
times=difference/4;
}
// srand(time(NULL)); //doesn't work on windows
printf("Corrupt Start: %d End: %d Difference: %d \n", corrupt_start, corrupt_end, difference);
int randomNewValue = rand() % 0xFF;
for (int i=0; i<=times; i++) {
int randomOffset = rand() % difference;
int currentOffset = randomOffset;
printf("Offset: %d OldValue: %#08x NewValue: %#08x \n", currentOffset, mem[cartAddr+currentOffset], randomNewValue);
mem[cartAddr+currentOffset] = randomNewValue;
}
}
void cdl_log_opcode(uint32_t program_counter, uint8_t* op_address) {
// only called in pure_interp mode
// jump_data[program_counter] = op_address;
// if (!labels[function_stack.back()].generatedSignature) {
// printf("Not generated sig yet: %#08x \n", *op_address);
// }
}
int note_count = 0;
void add_note(uint32_t pc, uint32_t target, string problem) {
if (!log_notes) return;
if (labels[function_stack.back()].doNotLog) return;
std::stringstream sstream;
sstream << std::hex << "pc:0x" << pc << "-> 0x" << target;
sstream << problem << " noteNumber:"<<note_count;
// cout << sstream.str();
labels[function_stack.back()].notes[pc] = sstream.str();
note_count++;
}
uint32_t map_assembly_offset_to_rom_offset(uint32_t assembly_offset, uint32_t tlb_mapped_addr) {
// or if its in KSEG0/1
if (assembly_offset >= 0x80000000) {
uint32_t mapped_offset = assembly_offset & UINT32_C(0x1ffffffc);
// std::cout << "todo:" << std::hex << assembly_offset << "\n";
return map_assembly_offset_to_rom_offset(mapped_offset, assembly_offset);
}
for(auto it = tlbs.begin(); it != tlbs.end(); ++it) {
auto t = it->second;
if (assembly_offset>=t.start && assembly_offset <=t.end) {
uint32_t mapped_offset = t.rom_offset + (assembly_offset-t.start);
return map_assembly_offset_to_rom_offset(mapped_offset, assembly_offset);
}
}
for(auto it = dmas.begin(); it != dmas.end(); ++it) {
auto& t = it->second;
if (assembly_offset>=t.dram_start && assembly_offset <=t.dram_end) {
uint32_t mapped_offset = t.rom_start + (assembly_offset-t.dram_start);
t.is_assembly = true;
t.tbl_mapped_addr = tlb_mapped_addr;
// DMA is likely the actual value in rom
return mapped_offset;
}
}
// std::cout << "Not in dmas:" << std::hex << assembly_offset << "\n";
// std::cout << "Unmapped: " << std::hex << assembly_offset << "\n";
return assembly_offset;
}
uint32_t current_function = 0;
void log_dma_write(uint8_t* mem, uint32_t proper_cart_address, uint32_t cart_addr, uint32_t length, uint32_t dram_addr) {
if (dmas.find(proper_cart_address) != dmas.end() )
return;
auto t = cdl_dma();
t.dram_start=dram_addr;
t.dram_end = dram_addr+length;
t.rom_start = proper_cart_address;
t.rom_end = proper_cart_address+length;
t.length = length;
t.ascii_header = get_header_ascii(mem, proper_cart_address);
t.header = mem[proper_cart_address+3];
t.frame = l_CurFrame;
// if (function_stack.size() > 0 && labels.find(current_function) != labels.end()) {
t.func_addr = print_function_stack_trace(); // labels[current_function].func_name;
// }
dmas[proper_cart_address] = t;
// std::cout << "DMA: Dram:0x" << std::hex << t.dram_start << "->0x" << t.dram_end << " Length:0x" << t.length << " " << t.ascii_header << " Stack:" << function_stack.size() << " " << t.func_addr << " last:"<< function_stack.back() << "\n";
}
void cdl_finish_pi_dma(uint32_t a) {
// cout <<std::hex<< "Finish PI DMA:" << a << "\n";
}
void cdl_finish_si_dma(uint32_t a) {
cout <<std::hex<< "Finish SI DMA:" << a << "\n";
}
void cdl_finish_ai_dma(uint32_t a) {
// cout <<std::hex<< "Finish AI DMA:" << (a & 0xffffff) << "\n";
}
void cdl_clear_dma_log() {
// next_dma_type = "cleared";
}
void cdl_clear_dma_log2() {
// next_dma_type = "interesting";
}
void cdl_log_cart_reg_access() {
// next_dma_type = "bin";
add_tag_to_function("_cartRegAccess", function_stack.back());
}
void cdl_log_dma_si_read() {
add_tag_to_function("_dmaSiRead", function_stack.back());
}
void cdl_log_copy_pif_rdram() {
add_tag_to_function("_copyPifRdram", function_stack.back());
}
void cdl_log_si_reg_access() {
// COntrollers, rumble paks etc
add_tag_to_function("_serialInterfaceRegAccess", function_stack.back());
}
void cdl_log_mi_reg_access() {
// The MI performs the read, modify, and write operations for the individual pixels at either one pixel per clock or one pixel for every two clocks. The MI also has special modes for loading the TMEM, filling rectangles (fast clears), and copying multiple pixels from the TMEM into the framebuffer (sprites).
add_tag_to_function("_miRegRead", function_stack.back());
}
void cdl_log_mi_reg_write() {
// The MI performs the read, modify, and write operations for the individual pixels at either one pixel per clock or one pixel for every two clocks. The MI also has special modes for loading the TMEM, filling rectangles (fast clears), and copying multiple pixels from the TMEM into the framebuffer (sprites).
add_tag_to_function("_miRegWrite", function_stack.back());
}
void cdl_log_pi_reg_read() {
if (function_stack.size() > 0)
add_tag_to_function("_piRegRead", function_stack.back());
}
void cdl_log_pi_reg_write() {
if (function_stack.size() > 0)
add_tag_to_function("_piRegWrite", function_stack.back());
}
void cdl_log_read_rsp_regs2() {
add_tag_to_function("_rspReg2Read", function_stack.back());
}
void cdl_log_write_rsp_regs2() {
add_tag_to_function("_rspReg2Write", function_stack.back());
}
void cdl_log_read_rsp_regs() {
if (function_stack.size() > 0)
add_tag_to_function("_rspRegRead", function_stack.back());
}
void cdl_log_write_rsp_regs() {
if (function_stack.size() > 0)
add_tag_to_function("_rspRegWrite", function_stack.back());
}
void cdl_log_update_sp_status() {
if (function_stack.size() > 0)
add_tag_to_function("_updatesSPStatus", function_stack.back());
}
void cdl_common_log_tag(const char* tag) {
if (function_stack.size() > 0)
add_tag_to_function(tag, function_stack.back());
}
void cdl_log_audio_reg_access() {
// TODO speed this up with a check first
add_tag_to_function("_audioRegAccess", function_stack.back());
}
string print_function_stack_trace() {
if (function_stack.size() ==0 || functions.size() ==0 /*|| labels.size() ==0*/ || function_stack.size() > 0xF) {
return "";
}
std::stringstream sstream;
int current_stack_number = 0;
for (auto& it : function_stack) {
if (strcmp(functions[it].func_name.c_str(),"") == 0) {
sstream << "0x" << std::hex << it<< "->";
continue;
}
if (current_stack_number>0) {
sstream << "->";
}
sstream << functions[it].func_name;
current_stack_number++;
}
// cout << "Stack:"<< sstream.str() << "\n";
return sstream.str();
}
void resetReversing() {
// time_last_reversed = time(0); // doesn;t work on windows
last_reversed_address="";
}
void save_cdl_files() {
resetReversing();
find_asm_sections();
find_audio_sections();
find_audio_functions();
save_dram_rw_to_json();
saveJsonToFile();
saveLibUltraSignatures();
}
uint32_t cdl_get_alternative_jump(uint32_t current_jump) {
if (!should_change_jumps) {
return current_jump;
}
for (auto& it : linker_map_file.items()) {
uint32_t new_jump = hex_to_int(it.key());
cout << "it:" << it.value() << " = " << it.key() << " old:" << current_jump << " new:"<< new_jump << "\n";
linker_map_file.erase(it.key());
should_change_jumps = false;
return new_jump;
}
return current_jump;
}
int reverse_jump(int take_jump, uint32_t jump_target) {
// this function doesn't work on windows
// time_t now = time(0);
// string key = n2hexstr(jump_target);
// printf("Reversing jump %#08x %d \n", jump_target, jumps[jump_target]);
// take_jump = !take_jump;
// time_last_reversed = now;
// frame_last_reversed=l_CurFrame;
// last_reversed_address = key;
// fileConfig["reversed_jumps"][key] = jumps[jump_target];
// write_rom_mapping();
return take_jump;
}
void cdl_log_jump_cached(int take_jump, uint32_t jump_target, uint8_t* jump_target_memory) {
if (cached_jumps.find(jump_target) != cached_jumps.end() )
return;
cached_jumps[jump_target] = 1;
cout << "Cached:" << std::hex << jump_target << "\n";
}
int number_of_functions = 0;
bool libRR_full_function_log = false;
bool libRR_full_trace_log = true;
int last_return_address = 0;
uint32_t libRR_call_depth = 0; // Tracks how big our stack trace is in terms of number of function calls
// We store the stackpointers in backtrace_stackpointers everytime a function gets called
uint16_t libRR_backtrace_stackpointers[0x200]; // 0x200 should be tons of function calls
uint32_t libRR_backtrace_size = 0; // Used with backtrace_stackpointers - Tracks how big our stack trace is in terms of number of function calls
extern uint32_t libRR_pc_lookahead;
string current_trace_log = "";
const int trace_messages_until_flush = 40;
int current_trace_count = 0;
bool first_trace_write = true;
void libRR_log_trace_str(string message) {
if (!libRR_full_trace_log) {
return;
}
current_trace_log += message + "\n";
current_trace_count++;
if (current_trace_count >= trace_messages_until_flush) {
libRR_log_trace_flush();
current_trace_count = 0;
current_trace_log="";
}
}
void libRR_log_trace(const char* message) {
libRR_log_trace_str(message);
}
void libRR_log_trace_flush() {
if (!libRR_full_trace_log) {
return;
}
string output_file_path = libRR_export_directory + "trace_log.txt";
if (first_trace_write) {
codeDataLogger::writeStringToFile(output_file_path, current_trace_log);
first_trace_write = false;
} else {
codeDataLogger::appendStringToFile(output_file_path, current_trace_log);
}
}
// libRR_log_return_statement
// stack_pointer is used to make sure our function stack doesn't exceed the actual stack pointer
void libRR_log_return_statement(uint32_t current_pc, uint32_t return_target, uint32_t stack_pointer) {
if (libRR_full_trace_log) {
libRR_log_trace_str("Return:"+n2hexstr(current_pc)+"->"+n2hexstr(return_target));
}
// printf("libRR_log_return_statement pc:%d return:%d stack:%d\n", current_pc, return_target, 65534-stack_pointer);
// check the integrety of the call stack
if (libRR_call_depth < 0) {
printf("Function seems to have returned without changing the stack, PC: %d \n", current_pc);
}
auto function_returning_from = function_stack.back();
auto presumed_return_address = previous_ra.back();
if (return_target != presumed_return_address) {
// printf("ERROR: Presumed return: %d actual return: %d current_pc: %d\n", presumed_return_address, return_target, current_pc);
// sometimes code manually pushes the ret value to the stack and returns
// if so we don't want to log as a function return
// but in the future we might want to consider making the previous jump a function call
return;
} else {
libRR_call_depth--;
// Remove from stacks
function_stack.pop_back();
previous_ra.pop_back();
}
if (!libRR_full_function_log) {
return;
}
current_pc -= libRR_pc_lookahead;
string current_function = n2hexstr(function_returning_from);
string current_pc_str = n2hexstr(current_pc);
// printf("Returning from function: %s current_pc:%s \n", current_function.c_str(), current_pc_str.c_str());
// string function_key = current_function;
playthough_function_usage[current_function]["returns"][current_pc_str] = return_target;
// Add max return to functions
if (functions.find(function_returning_from) != functions.end() ) {
uint32_t relative_return_pc = current_pc - function_returning_from;
if (relative_return_pc > functions[function_returning_from].return_offset_from_start) {
functions[function_returning_from].return_offset_from_start = relative_return_pc;
}
}
// TODO: Calculate Function Signature so we can check for its name
int length = current_pc - function_returning_from;
string length_str = n2hexstr(length);
playthough_function_usage[current_function]["lengths"][length_str] = length;
if (length > 0 && length < 200) {
if (playthough_function_usage[current_function]["signatures"].contains(length_str)) {
} else {
printf("Function Signature: About to get length: %d \n", length);
playthough_function_usage[current_function]["signatures"][n2hexstr(length)] = libRR_get_data_for_function(function_returning_from, length+1, true, true);
}
}
// string bytes_with_branch_delay = printBytesToStr(jump_data[previous_function_backup], byte_len+4)+"_"+n2hexstr(length+4);
// string word_pattern = printWordsToStr(jump_data[previous_function_backup], byte_len+4)+" L"+n2hexstr(length+4,4);
// TODO: need to get the moment where the bytes for the function are located
// printf("Logged inst: %s \n", name.c_str());
}
// libRR_log_full_function_call is expensive as it does extensive logging
void libRR_log_full_function_call(uint32_t current_pc, uint32_t jump_target) {
// Instead of using function name, we just use the location
string function_name = /*game_name + "_func_" +*/ n2hexstr(jump_target);
// printf("libRR_log_full_function_call Full function logging on %s \n", print_function_stack_trace().c_str());
// This is playthough specific
if (!playthough_function_usage.contains(function_name)) {
// printf("Adding new function %s \n", function_name.c_str());
playthough_function_usage[function_name] = json::parse("{}");
playthough_function_usage[function_name]["first_frame_access"] = RRCurrentFrame;
playthough_function_usage[function_name]["number_of_frames"]=0;
playthough_function_usage[function_name]["last_frame_access"] = 0;
playthough_function_usage[function_name]["number_of_calls_per_frame"] = 1;
}
else if (RRCurrentFrame < playthough_function_usage[function_name]["last_frame_access"]) {
// we have already ran this frame before, probably replaying, no need to add more logging
return;
}
if (RRCurrentFrame > playthough_function_usage[function_name]["last_frame_access"]) {
playthough_function_usage[function_name]["last_frame_access"] = RRCurrentFrame;
playthough_function_usage[function_name]["number_of_frames"]= (int)playthough_function_usage[function_name]["number_of_frames"]+1;
playthough_function_usage[function_name]["number_of_calls_per_frame"]=0;
}
else if (RRCurrentFrame == playthough_function_usage[function_name]["last_frame_access"]) {
// we are in the same frame so its called more than once per frame
playthough_function_usage[function_name]["number_of_calls_per_frame"]=(int)playthough_function_usage[function_name]["number_of_calls_per_frame"]+1;
}
// TODO: log read/writes to memory
// TODO: calculate return and paramerters
// TODO: find out how long the function is
}
const char* libRR_log_long_jump(uint32_t current_pc, uint32_t jump_target, const char* type) {
// cout << "Long Jump from:" << n2hexstr(current_pc) << " to:" << n2hexstr(jump_target) << "\n";
if (libRR_full_trace_log) {
libRR_log_trace_str("Long Jump:"+n2hexstr(current_pc)+"->"+n2hexstr(jump_target)+" type:"+type);
}
string target_bank_number = "0000";
string pc_bank_number = "0000";
target_bank_number = n2hexstr(get_current_bank_number_for_address(jump_target), 4);
// now we need the bank number of the function we are calling
pc_bank_number = n2hexstr(get_current_bank_number_for_address(current_pc), 4);
libRR_long_jumps[target_bank_number][n2hexstr(jump_target)][pc_bank_number+"::"+n2hexstr(current_pc)]=type;
return libRR_log_jump_label(jump_target, current_pc);
}
void libRR_log_interrupt_call(uint32_t current_pc, uint32_t jump_target) {
string pc_bank_number = "0000";
pc_bank_number = n2hexstr(get_current_bank_number_for_address(current_pc), 4);
// printf("Interrupt call at: %s::%s target:%s \n", pc_bank_number.c_str(), n2hexstr(current_pc).c_str(), n2hexstr(jump_target).c_str());
libRR_long_jumps["0000"][n2hexstr(jump_target)][pc_bank_number+"::"+n2hexstr(current_pc)]=true;
}
// Restarts are very similar to calls but can only jump to specific targets and only take up 1 byte
void libRR_log_rst(uint32_t current_pc, uint32_t jump_target) {
// for now just log it as a standard function call
libRR_log_function_call(current_pc, jump_target, 0x00);
}
string function_name = ""; // last function name called
const char* libRR_log_function_call(uint32_t current_pc, uint32_t jump_target, uint32_t stack_pointer) {
// TODO: find out why uncommeting the following causes a segfault
// if (!libRR_full_function_log || !libRR_finished_boot_rom) {
// return;
// }
string bank_number = "0000";
uint32_t calculated_jump_target = jump_target;
if (libRR_bank_switching_available) {
int bank = get_current_bank_number_for_address(jump_target);
bank_number = n2hexstr(bank, 4);
// TODO: the following might be gameboy specific
if (jump_target >= libRR_bank_size) {
// printf("TODO: remove this in gameboy!\n");
calculated_jump_target = jump_target + ((bank-1) * libRR_bank_size);
}
// END TODO
}
string jump_target_str = n2hexstr(jump_target);
function_name = "_"+bank_number+"_func_"+jump_target_str;
libRR_called_functions[bank_number][n2hexstr(jump_target)] = function_name;
libRR_log_trace_str("Function call: 0x"+jump_target_str);
// Start Stacktrace handling
libRR_call_depth++;
// End Stacktrace handling
last_return_address = current_pc;
function_stack.push_back(jump_target);
previous_ra.push_back(current_pc);
if (libRR_full_function_log) {
libRR_log_full_function_call(current_pc, jump_target);
}
if (functions.find(jump_target) != functions.end() ) {
// We have already logged this function, so ignore for now
return function_name.c_str();
}
// We have never logged this function so lets create it
auto t = cdl_labels();
t.func_offset = n2hexstr(calculated_jump_target);
// if (functions.find(previous_function_backup) != functions.end()) {
// t.caller_offset = functions[previous_function_backup].func_name+" (ra:"+n2hexstr(ra)+")";
// } else {
// t.caller_offset = n2hexstr(previous_function_backup);
// }
t.func_name = function_name; // /*libRR_game_name+*/"_"+bank_number+"_func_"+jump_target_str;
//t.func_stack = function_stack.size();
//t.export_path = "";
//t.bank_number = bank_number;
//t.bank_offset = jump_target;
// t.stack_trace = print_function_stack_trace();
t.doNotLog = false;
t.many_memory_reads = false;
t.many_memory_writes = false;
// t.additional["callers"][print_function_stack_trace()] = RRCurrentFrame;
printf("Logged new function: %s target:%d number_of_functions:%d \n", t.func_name.c_str(), jump_target, number_of_functions);
functions[jump_target] = t;
number_of_functions++;
return function_name.c_str();
}
// This will be replace be libRR_log_function_call
void log_function_call(uint32_t function_that_is_being_called) {
if (!log_function_calls) return;
uint32_t function_that_is_calling = function_stack.back();
if (labels.find(function_that_is_calling) == labels.end()) return;
if (labels[function_that_is_calling].isRenamed || labels[function_that_is_calling].doNotLog) return;
labels[function_that_is_calling].function_calls[function_that_is_being_called] = labels[function_that_is_being_called].func_name;
}
void cdl_log_jump_always(int take_jump, uint32_t jump_target, uint8_t* jump_target_memory, uint32_t ra, uint32_t pc) {
add_note(ra-8, pc, "Call (jal)");
previous_ra.push_back(ra);
uint32_t previous_function_backup = function_stack.back();
function_stack.push_back(jump_target);
current_function = jump_target;
if (jumps[jump_target] >3) return;
jumps[jump_target] = 0x04;
if (labels.find(jump_target) != labels.end() )
return;
log_function_call(jump_target);
auto t = cdl_labels();
string jump_target_str = n2hexstr(jump_target);
t.func_offset = jump_target_str;
if (labels.find(previous_function_backup) != labels.end()) {
t.caller_offset = labels[previous_function_backup].func_name+" (ra:"+n2hexstr(ra)+")";
} else {
t.caller_offset = n2hexstr(previous_function_backup);
}
t.func_name = libRR_game_name+"_func_"+jump_target_str;
t.func_stack = function_stack.size();
t.stack_trace = print_function_stack_trace();
t.doNotLog = false;
t.many_memory_reads = false;
t.many_memory_writes = false;
labels[jump_target] = t;
jump_data[jump_target] = jump_target_memory;
}
void cdl_log_jump_return(int take_jump, uint32_t jump_target, uint32_t pc, uint32_t ra, int64_t* registers, struct r4300_core* r4300) {
uint32_t previous_function_backup = -1;
if (!libRR_full_function_log || !libRR_finished_boot_rom) {
return;
}
// if (previous_function_backup > ra) {
// // cout << std::hex << " Odd the prev function start should never be before return address ra:" << ra << " previous_function_backup:" << previous_function_backup << "\n";
// return;
// }
if (function_stack.size()>0) {
previous_function_backup = function_stack.back();
}
else {
add_note(pc, jump_target, "function_stack <0");
// probably jumping from exception?
// cout << "Missed push back?" << std::hex << jump_target << " ra" << ra << " pc:"<< pc<< "\n";
// return;
}
if (jump_target == previous_ra.back()) {
add_note(pc, jump_target, "successful return");
} else {
string problem = "Expected $ra to be 0x";
problem += n2hexstr(previous_ra.back());
problem += " but was:";
problem += n2hexstr(jump_target);
add_note(pc, jump_target, problem);
// return;
}
function_stack.pop_back();
current_function = function_stack.back();
previous_ra.pop_back();
console_log_jump_return(take_jump, jump_target, pc, ra, registers, r4300);
if (jumps[jump_target] >3) return;
jumps[jump_target] = 0x04;
if (jump_returns.find(previous_function_backup) != jump_returns.end())
{
return;
}
auto t = cdl_jump_return();
string jump_target_str = n2hexstr(jump_target);
t.return_offset = pc;
t.func_offset = previous_function_backup;
t.caller_offset = jump_target;
jump_returns[previous_function_backup] = t;
uint64_t length = pc-previous_function_backup;
// labels[previous_function_backup].return_offset_from_start = length;
if (length<2) {
return;
}
if (jump_data.find(previous_function_backup) != jump_data.end()) {
uint64_t byte_len = length;
if (byte_len > 0xFFFF) {
byte_len = 0xFFFF;
}
// string bytes = printBytesToStr(jump_data[previous_function_backup], byte_len)+"_"+n2hexstr(length);
string bytes_with_branch_delay = printBytesToStr(jump_data[previous_function_backup], byte_len+4)+"_"+n2hexstr(length+4);
string word_pattern = printWordsToStr(jump_data[previous_function_backup], byte_len+4)+" L"+n2hexstr(length+4,4);
labels[previous_function_backup].function_bytes = bytes_with_branch_delay;
labels[previous_function_backup].doNotLog = true;
labels[previous_function_backup].generatedSignature = true;
// labels[previous_function_backup].function_bytes_endian = Swap4Bytes(bytes);
// now check to see if its in the mario map
// if (/*strcmp(game_name.c_str(),"SUPERMARIO") == 0 &&*/ linker_map_file.find( n2hexstr(previous_function_backup) ) != linker_map_file.end()) {
// string offset = n2hexstr(previous_function_backup);
// string func_name = linker_map_file[offset];
// cout << game_name << "It is in the map file!" << n2hexstr(previous_function_backup) << " as:" << linker_map_file[n2hexstr(previous_function_backup)] << "\n";
// function_signatures[bytes] = func_name;
// if (strcmp(func_name.c_str(),"gcc2_compiled.")==0) return; // we don't want gcc2_compiled labels
// libultra_signatures["function_signatures"][bytes_with_branch_delay] = func_name;
// labels[previous_function_backup].func_name = libultra_signatures["function_signatures"][bytes_with_branch_delay];
// return;
// }
// if it is a libultra function then lets name it
if (libultra_signatures["library_signatures"].find(word_pattern) != libultra_signatures["library_signatures"].end()) {
std::cout << "In library_signatures:" << word_pattern << " name:"<< libultra_signatures["library_signatures"][word_pattern] << "\n";
labels[previous_function_backup].func_name = libultra_signatures["library_signatures"][word_pattern];
labels[previous_function_backup].isRenamed = true;
// return since we have already named this functions, don't need its signature to be saved
return;
}
if (libultra_signatures["game_signatures"].find(word_pattern) != libultra_signatures["game_signatures"].end()) {
// std::cout << "In game_signatures:" << word_pattern << " name:"<< libultra_signatures["game_signatures"][word_pattern] << "\n";
labels[previous_function_backup].func_name = libultra_signatures["game_signatures"][word_pattern];
// return since we have already named this functions, don't need its signature to be saved
return;
}
// if it is a libultra function then lets name it
if (libultra_signatures["function_signatures"].find(bytes_with_branch_delay) != libultra_signatures["function_signatures"].end()) {
std::cout << "In old libultra:" << bytes_with_branch_delay << " name:"<< libultra_signatures["function_signatures"][bytes_with_branch_delay] << "\n";
labels[previous_function_backup].func_name = libultra_signatures["function_signatures"][bytes_with_branch_delay];
if (labels[previous_function_backup].func_name.find("_func_") != std::string::npos) {
// this is a non renamed function as it was auto generated
find_most_similar_function(previous_function_backup, word_pattern);
libultra_signatures["game_signatures"][word_pattern] = labels[previous_function_backup].func_name;
}
else {
libultra_signatures["library_signatures"][word_pattern] = labels[previous_function_backup].func_name;
labels[previous_function_backup].isRenamed = true;
}
libultra_signatures["function_signatures"].erase(bytes_with_branch_delay);
// return since we have already named this functions, don't need its signature to be saved
return;
}
// if it is an OLD libultra function then lets name it (without branch delay)
// if (libultra_signatures["function_signatures"].find(bytes) != libultra_signatures["function_signatures"].end()) {
// std::cout << "In OLDEST libultra:" << bytes << " name:"<< libultra_signatures["function_signatures"][bytes] << "\n";
// labels[previous_function_backup].func_name = libultra_signatures["function_signatures"][bytes];
// labels[previous_function_backup].isRenamed = true;
// libultra_signatures["function_signatures"][bytes_with_branch_delay] = labels[previous_function_backup].func_name;
// // delete the old non-branch delay version
// libultra_signatures["function_signatures"].erase(bytes);
// // return since we have already named this functions, don't need its signature to be saved
// return;
// }
find_most_similar_function(previous_function_backup, word_pattern);
// cout << "word_pattern:" << word_pattern << "\n";
if (function_signatures.find(word_pattern) == function_signatures.end()) {
// save this new function to both libultra and trace json
function_signatures[word_pattern] = labels[previous_function_backup].func_name;
libultra_signatures["game_signatures"][word_pattern] = labels[previous_function_backup].func_name;
} else {
//function_signatures.erase(bytes);
// function_signatures[word_pattern] = "Multiple functions";
std::cout << "Multiple Functions for :" << *jump_data[previous_function_backup] << " len:" << length << " pc:0x"<< pc << " - 0x" << previous_function_backup << "\n";
}
}
}
void find_most_similar_function(uint32_t function_offset, string bytes) {
string named_function_with_highest_distance = "";
// string auto_generated_function_with_highest_distance = "";
double highest_distance = 0;
// double highest_auto_distance = 0;
for(auto it = libultra_signatures["library_signatures"].begin(); it != libultra_signatures["library_signatures"].end(); ++it) {
double distance = jaro_winkler_distance(bytes.c_str(), it.key().c_str());
if (distance >= highest_distance) {
string function_name = it.value();
// if (!is_auto_generated_function_name(function_name)) {
if (distance == highest_distance) {
named_function_with_highest_distance += "_or_";
named_function_with_highest_distance += function_name;
} else {
highest_distance = distance;
named_function_with_highest_distance = function_name;
}
// } else {
// highest_auto_distance = distance;
// auto_generated_function_with_highest_distance=function_name;
// }
}
// cout << "IT:" << it.value() << " distance:" << jaro_winkler_distance(bytes_with_branch_delay.c_str(), it.key().c_str()) << "\n";
}
uint32_t highest_distance_percent = highest_distance*100;
// cout << "generated function_with_highest_distance to "<< std::hex << function_offset << " is:"<<auto_generated_function_with_highest_distance<<" with "<< std::dec << highest_auto_distance <<"%\n";
if (highest_distance_percent>=95) {
cout << "function will be renamed "<< std::hex << function_offset << " is:"<<named_function_with_highest_distance<<" with "<< std::dec << highest_distance_percent <<"%\n";
labels[function_offset].func_name = named_function_with_highest_distance;
labels[function_offset].isRenamed = true;
} else if (highest_distance_percent>=90) {
cout << "function_with_highest_distance to "<< std::hex << function_offset << " is:"<<named_function_with_highest_distance<<" with "<< std::dec << highest_distance_percent <<"%\n";
labels[function_offset].func_name += "_predict_"+named_function_with_highest_distance+"_";
labels[function_offset].func_name += (to_string(highest_distance_percent));
labels[function_offset].func_name += "percent";
}
}
// loop through and erse multiple functions
void erase_multiple_func_signatures() {
// function_signatures
// Multiple functions
}
bool is_auto_generated_function_name(string func_name) {
if (func_name.find("_func_") != std::string::npos) {
// this is a non renamed function as it was auto generated
return true;
}
return false;
}
unsigned int find_first_non_executed_jump() {
for(map<unsigned int, char>::iterator it = jumps.begin(); it != jumps.end(); ++it) {
if ((it->second+0) <3) {
return it->first;
}
}
return -1;
}
int cdl_log_jump(int take_jump, uint32_t jump_target, uint8_t* jump_target_memory, uint32_t pc, uint32_t ra) {
add_note(pc, jump_target, "jump");
// if (previous_ra.size() > 0 && ra != previous_ra.back()) {
// cdl_log_jump_always(take_jump, jump_target, jump_target_memory, ra, pc);
// //previous_ra.push_back(ra);
// return take_jump;
// }
// if (should_reverse_jumps)
// {
// time_t now = time(0);
// if (jumps[jump_target] < 3) {
// // should_reverse_jumps=false;
// if ( now-time_last_reversed > 2) { // l_CurFrame-frame_last_reversed >(10*5) ||
// take_jump = reverse_jump(take_jump, jump_target);
// }
// } else if (now-time_last_reversed > 15) {
// printf("Stuck fixing %d\n", find_first_non_executed_jump());
// take_jump=!take_jump;
// main_state_load(NULL);
// // we are stuck so lets load
// }
// }
if (take_jump) {
jumps[jump_target] |= 1UL << 0;
}
else {
jumps[jump_target] |= 1UL << 1;
}
return take_jump;
}
void save_table_mapping(int entry, uint32_t phys, uint32_t start,uint32_t end, bool isOdd) {
//printf("tlb_map:%d ODD Start:%#08x End:%#08x Phys:%#08x \n",entry, e->start_odd, e->end_odd, e->phys_odd);
uint32_t length = end-start;
auto t = cdl_tlb();
t.start=start;
t.end = end;
t.rom_offset = phys;
tlbs[phys]=t;
string key = "";
key+="[0x";
key+=n2hexstr(phys);
key+=", 0x";
key+=n2hexstr(phys+length);
key+="] Virtual: 0x";
key+=n2hexstr(start);
key+=" to 0x";
key+=n2hexstr(end);
if (isOdd)
key+=" Odd";
else
key+=" Even";
string value = "Entry:";
value += to_string(entry);
// value += " Frame:0x";
value += n2hexstr(l_CurFrame);
bool isInJson = fileConfig["tlb"].find(key) != fileConfig["tlb"].end();
if (isInJson) {
string original = fileConfig["tlb"][key];
bool isSameValue = (strcmp(original.c_str(), value.c_str()) == 0);
if (isSameValue) return;
// printf("isSameValue:%d \noriginal:%s \nnew:%s\n", isSameValue, original.c_str(), value.c_str());
return; // don't replace the original value as it is useful to match frame numbers to the mappings
}
fileConfig["tlb"][key] = value;
printf("TLB %s\n", value.c_str());
}
void cdl_log_dram_read(uint32_t address) {
}
void cdl_log_dram_write(uint32_t address, uint32_t value, uint32_t mask) {
}
void cdl_log_rsp_mem(uint32_t address, uint32_t* mem,int isBootRom) {
if (isBootRom) return;
rsp_reads[address] = (uint32_t)*mem;
}
void cdl_log_rdram(uint32_t address, uint32_t* mem,int isBootRom) {
//printf("RDRAM %#08x \n", address);
if (isBootRom) return;
rdram_reads[address] = (uint32_t)*mem;
}
void cdl_log_mm_cart_rom(uint32_t address,int isBootRom) {
printf("Cart ROM %#08x \n", address);
}
void cdl_log_mm_cart_rom_pif(uint32_t address,int isBootRom) {
printf("PIF? %#08x \n", address);
}
void cdl_log_pif_ram(uint32_t address, uint32_t* value) {
#ifndef USE_CDL
return;
#endif
printf("Game was reset? \n");
if (!createdCartBackup) {
backupCart();
readJsonFromFile();
function_stack.push_back(0);
}
if (should_reverse_jumps) {
// should_reverse_jumps = false;
fileConfig["bad_jumps"][last_reversed_address] = "reset";
main_state_load(NULL);
write_rom_mapping();
}
}
void cdl_log_opcode_error() {
printf("Very bad opcode, caused crash! \n");
fileConfig["bad_jumps"][last_reversed_address] = "crash";
main_state_load(NULL);
}
void find_asm_sections() {
printf("finding asm in sections \n");
for(map<unsigned int, char>::iterator it = jumps.begin(); it != jumps.end(); ++it) {
string jump_target_str = n2hexstr(it->first);
fileConfig["jumps_rom"][jump_target_str] = n2hexstr(map_assembly_offset_to_rom_offset(it->first,0));
}
}
void find_audio_sections() {
printf("finding audio sections \n");
for(map<uint32_t, cdl_dma>::iterator it = dmas.begin(); it != dmas.end(); ++it) {
uint32_t address = it->second.dram_start;
if (audio_address.find(address) == audio_address.end() )
continue;
dmas[address].guess_type = "audio";
it->second.guess_type="audio";
}
}
void add_tag_to_function(string tag, uint32_t labelAddr) {
if (!tag_functions || labels[labelAddr].isRenamed) return;
if (labels[labelAddr].func_name.find(tag) != std::string::npos) return;
labels[labelAddr].func_name += tag;
}
void find_audio_functions() {
printf("finding audio functions \n");
for(map<uint32_t, cdl_labels>::iterator it = labels.begin(); it != labels.end(); ++it) {
cdl_labels label = it->second;
if (label.isRenamed) {
continue; // only do it for new functions
}
if (label.many_memory_reads) {
add_tag_to_function("_manyMemoryReads", it->first);
}
if (label.many_memory_writes) {
add_tag_to_function("_manyMemoryWrites", it->first);
}
for(map<string, string>::iterator it2 = label.read_addresses.begin(); it2 != label.read_addresses.end(); ++it2) {
uint32_t address = hex_to_int(it2->first);
if (audio_address.find(address) != audio_address.end() )
{
cout << "Function IS audio:"<< label.func_name << "\n";
}
if (address>0x10000000 && address <= 0x107fffff) {
cout << "Function accesses cart rom:"<< label.func_name << "\n";
}
}
for(map<string, string>::iterator it2 = label.write_addresses.begin(); it2 != label.write_addresses.end(); ++it2) {
uint32_t address = hex_to_int(it2->first);
if (audio_address.find(address) != audio_address.end() )
{
cout << "Function IS audio:"<< label.func_name << "\n";
}
if (address>0x10000000 && address <= 0x107fffff) {
cout << "Function IS cart rom:"<< label.func_name << "\n";
}
}
}
}
bool isAddressCartROM(uint32_t address) {
return (address>0x10000000 && address <= 0x107fffff);
}
void cdl_log_audio_sample(uint32_t saved_ai_dram, uint32_t saved_ai_length) {
if (audio_samples.find(saved_ai_dram) != audio_samples.end() )
return;
auto t = cdl_dram_cart_map();
t.dram_offset = n2hexstr(saved_ai_dram);
t.rom_offset = n2hexstr(saved_ai_length);
audio_samples[saved_ai_dram] = t;
// printf("audio_plugin_push_samples AI_DRAM_ADDR_REG:%#08x length:%#08x\n", saved_ai_dram, saved_ai_length);
}
void cdl_log_cart_rom_dma_write(uint32_t dram_addr, uint32_t cart_addr, uint32_t length) {
if (cart_rom_dma_writes.find(cart_addr) != cart_rom_dma_writes.end() )
return;
auto t = cdl_dram_cart_map();
t.dram_offset = n2hexstr(dram_addr);
t.rom_offset = n2hexstr(cart_addr);
cart_rom_dma_writes[cart_addr] = t;
printf("cart_rom_dma_write: dram_addr:%#008x cart_addr:%#008x length:%#008x\n", dram_addr, cart_addr, length);
}
void cdl_log_dma_sp_write(uint32_t spmemaddr, uint32_t dramaddr, uint32_t length, unsigned char *dram) {
if (dma_sp_writes.find(dramaddr) != dma_sp_writes.end() )
return;
auto t = cdl_dram_cart_map();
t.dram_offset = n2hexstr(dramaddr);
t.rom_offset = n2hexstr(spmemaddr);
dma_sp_writes[dramaddr] = t;
// FrameBuffer RSP info
printWords(dram, dramaddr, length);
printf("FB: dma_sp_write SPMemAddr:%#08x Dramaddr:%#08x length:%#08x \n", spmemaddr, dramaddr, length);
}
inline void cdl_log_memory_common(const uint32_t lsaddr, uint32_t pc) {
// if (addresses.find(lsaddr) != addresses.end() )
// return;
// addresses[lsaddr] = currentMap;
}
void cdl_log_mem_read(const uint32_t lsaddr, uint32_t pc) {
if (!cdl_log_memory) return;
if (memory_to_log.find(lsaddr) != memory_to_log.end() )
{
cout << "Logging Mem Read for 0x"<< std::hex << lsaddr << " At PC:" << pc <<"\n";
}
if (labels[current_function].isRenamed || labels[current_function].doNotLog) {
// only do it for new functions
return;
}
if (labels[current_function].read_addresses.size() > NUMBER_OF_MANY_READS) {
labels[current_function].many_memory_reads = true;
return;
}
// auto currentMap = addresses[lsaddr];
// currentMap[n2hexstr(lsaddr)]=labels[current_function].func_name+"("+n2hexstr(current_function)+"+"+n2hexstr(pc-current_function)+")";
auto offset = pc-current_function;
labels[current_function].read_addresses[n2hexstr(lsaddr)] = "func+0x"+n2hexstr(offset)+" pc=0x"+n2hexstr(pc);
}
void cdl_log_mem_write(const uint32_t lsaddr, uint32_t pc) {
if (!cdl_log_memory) return;
if (memory_to_log.find(lsaddr) != memory_to_log.end() )
{
cout << "Logging Mem Write to 0x"<< std::hex << lsaddr << " At PC:" << pc <<"\n";
}
if (labels[current_function].isRenamed || labels[current_function].doNotLog) {
// only do it for new functions
return;
}
if (labels[current_function].write_addresses.size() > NUMBER_OF_MANY_WRITES) {
labels[current_function].many_memory_writes = true;
return;
}
// auto currentMap = addresses[lsaddr];
// currentMap[n2hexstr(lsaddr)]=labels[current_function].func_name+"("+n2hexstr(current_function)+"+"+n2hexstr(pc-current_function)+")";
auto offset = pc-current_function;
labels[current_function].write_addresses[n2hexstr(lsaddr)] = "+0x"+n2hexstr(offset)+" pc=0x"+n2hexstr(pc);
}
void cdl_hit_memory_log_point(uint32_t address) {
if (address>0x10000000 && address <= 0x107fffff) {
cout << "Cart Memory access!" << std::hex << address << " in:" << labels[current_function].func_name << "\n";
}
}
void cdl_log_masked_write(uint32_t* address, uint32_t dst2) {
if (!cdl_log_memory) return;
// cout << "masked write:"<<std::hex<<dst<<" : "<<dst2<<"\n";
// if (memory_to_log.find(address) != memory_to_log.end() )
// {
// cout << "Logging Mem Write to 0x"<< std::hex << address << " At PC:" <<"\n";
// }
}
void cdl_log_get_mem_handler(uint32_t address) {
if (!cdl_log_memory) return;
cdl_hit_memory_log_point(address);
if (memory_to_log.find(address) != memory_to_log.end() )
{
cout << "Logging Mem cdl_log_get_mem_handler access 0x"<< std::hex << address <<"\n";
cdl_hit_memory_log_point(address);
}
}
void cdl_log_mem_read32(uint32_t address) {
if (!cdl_log_memory) return;
cdl_hit_memory_log_point(address);
if (memory_to_log.find(address) != memory_to_log.end() )
{
cout << "Logging Mem cdl_log_mem_read32 access 0x"<< std::hex << address <<"\n";
cdl_hit_memory_log_point(address);
}
}
void cdl_log_mem_write32(uint32_t address) {
if (!cdl_log_memory) return;
cdl_hit_memory_log_point(address);
if (memory_to_log.find(address) != memory_to_log.end() )
{
cout << "Logging Mem cdl_log_mem_write32 access 0x"<< std::hex << address <<"\n";
cdl_hit_memory_log_point(address);
}
}
string mapping_names[] = {
"M64P_MEM_NOTHING",
"M64P_MEM_NOTHING",
"M64P_MEM_RDRAM",
"M64P_MEM_RDRAMREG",
"M64P_MEM_RSPMEM",
"M64P_MEM_RSPREG",
"M64P_MEM_RSP",
"M64P_MEM_DP",
"M64P_MEM_DPS",
"M64P_MEM_VI",
"M64P_MEM_AI",
"M64P_MEM_PI",
"M64P_MEM_RI",
"M64P_MEM_SI",
"M64P_MEM_FLASHRAMSTAT",
"M64P_MEM_ROM",
"M64P_MEM_PIF",
"M64P_MEM_MI"
};
#define OSTASK_GFX 1
#define OSTASK_AUDIO 2
void cdl_log_ostask(uint32_t type, uint32_t flags, uint32_t bootcode, uint32_t bootSize, uint32_t ucode, uint32_t ucodeSize, uint32_t ucodeData, uint32_t ucodeDataSize) {
if (!log_ostasks) return;
if (rspboot == 0) {
rspboot = map_assembly_offset_to_rom_offset(bootcode,0);
auto bootDma = cdl_dma();
bootDma.dram_start=rspboot;
bootDma.dram_end = rspboot+bootSize;
bootDma.rom_start = rspboot;
bootDma.rom_end = rspboot+bootSize;
bootDma.length = bootSize;
bootDma.frame = l_CurFrame;
bootDma.func_addr = print_function_stack_trace();
bootDma.known_name = "rsp.boot";
dmas[rspboot] = bootDma;
}
uint32_t ucodeRom = map_assembly_offset_to_rom_offset(ucode,0);
if (dmas.find(ucodeRom) != dmas.end() )
return;
printf("OSTask type:%#08x flags:%#08x bootcode:%#08x ucode:%#08x ucodeSize:%#08x ucodeData:%#08x ucodeDataSize:%#08x \n", type, flags, bootcode, ucode, ucodeSize, ucodeData, ucodeDataSize);
uint32_t ucodeDataRom = map_assembly_offset_to_rom_offset(ucodeData,0);
auto data = cdl_dma();
data.dram_start=ucodeData;
data.dram_end = ucodeData+ucodeDataSize;
data.rom_start = ucodeDataRom;
data.rom_end = ucodeDataRom+ucodeDataSize;
data.length = ucodeDataSize;
data.frame = l_CurFrame;
data.func_addr = print_function_stack_trace();
data.is_assembly = false;
auto t = cdl_dma();
t.dram_start=ucode;
t.dram_end = ucode+ucodeSize;
t.rom_start = ucodeRom;
t.rom_end = ucodeRom+ucodeSize;
t.length = ucodeSize;
t.frame = l_CurFrame;
t.func_addr = print_function_stack_trace();
t.is_assembly = false;
if (type == OSTASK_AUDIO) {
t.guess_type = "rsp.audio";
t.ascii_header = "rsp.audio";
t.known_name = "rsp.audio";
data.ascii_header = "rsp.audio.data";
data.known_name = "rsp.audio.data";
} else if (type == OSTASK_GFX) {
t.guess_type = "rsp.graphics";
t.ascii_header = "rsp.graphics";
t.known_name = "rsp.graphics";
data.ascii_header = "rsp.graphics.data";
data.known_name = "rsp.graphics.data";
} else {
printf("other type:%#08x ucode:%#08x \n",type, ucodeRom);
}
dmas[ucodeRom] = t;
dmas[ucodeDataRom] = data;
}
#define CDL_ALIST 0
#define CDL_UCODE_CRC 2
void cdl_log_rsp(uint32_t log_type, uint32_t address, const char * extra_data) {
if (!log_rsp) return;
if (log_type == CDL_ALIST) {
if (audio_address.find(address) != audio_address.end() )
return;
audio_address[address] = n2hexstr(address)+extra_data;
// cout << "Alist address:" << std::hex << address << " " << extra_data << "\n";
return;
}
if (log_type == CDL_UCODE_CRC) {
ucode_crc = n2hexstr(address);
return;
}
cout << "Log rsp\n";
}
void cdl_log_dpc_reg_write(uint32_t address, uint32_t value, uint32_t mask) {
cdl_common_log_tag("writeDPCRegs");
}
} // end extern C
// C++
uint32_t libRR_offset_to_look_for = 0x8149;
bool libRR_enable_look = false;
json libRR_disassembly = {};
json libRR_memory_reads = {};
json libRR_consecutive_rom_reads = {};
json libRR_called_functions = {};
json libRR_long_jumps = {};
int32_t previous_consecutive_rom_read = 0; // previous read address to check if this read is part of the chain
int16_t previous_consecutive_rom_bank = 0; // previous read address to check if this read is part of the chain
int32_t current_consecutive_rom_start = 0; // start address of the current chain
bool replace(std::string& str, const std::string from, const std::string to) {
size_t start_pos = str.find(from);
if(start_pos == std::string::npos)
return false;
str.replace(start_pos, from.length(), to);
return true;
}
extern "C" void libRR_log_dma(int32_t offset) {
if (offset> 0x7fff) {
return;
}
cout << "DMA: " << n2hexstr(offset) << "\n";
}
static string label_name = "";
extern "C" const char* libRR_log_jump_label_with_name(uint32_t offset, uint32_t current_pc, const char* label_name) {
if (!libRR_full_function_log || !libRR_finished_boot_rom) {
return "";
}
string offset_str = n2hexstr(offset);
int bank = get_current_bank_number_for_address(offset);
string current_bank_str = n2hexstr(bank, 4);
if (offset >libRR_slot_2_max_addr) {
// if its greater than the max bank value then its probably in ram
return "";
}
// debugging code start
if (libRR_enable_look && (offset == libRR_offset_to_look_for || current_pc == libRR_offset_to_look_for)) {
printf("Found long jump label with name offset: %d\n", libRR_offset_to_look_for);
}
// debugging code end
// string label_name = "LAB_" + current_bank_str + "_" + n2hexstr(offset);
if (!libRR_disassembly[current_bank_str][offset_str].contains("label_name")) {
libRR_disassembly[current_bank_str][offset_str]["label_name"] = label_name;
}
libRR_disassembly[current_bank_str][offset_str]["meta"]["label_callers"][current_bank_str + "_" + n2hexstr(current_pc)] = true;
return label_name;
}
extern "C" const char* libRR_log_jump_label(uint32_t offset, uint32_t current_pc) {
if (!libRR_full_function_log || !libRR_finished_boot_rom) {
return "_not_logging";
}
string offset_str = n2hexstr(offset);
int bank = get_current_bank_number_for_address(offset);
string current_bank_str = n2hexstr(bank, 4);
if (offset >libRR_slot_2_max_addr) {
// if its greater than the max bank value then its probably in ram
return "max_bank_value";
}
// debugging code start
if (libRR_enable_look && (offset == libRR_offset_to_look_for || current_pc == libRR_offset_to_look_for)) {
printf("Found long jump label offset: %d\n", libRR_offset_to_look_for);
}
// debugging code end
label_name = "LAB_" + current_bank_str + "_" + n2hexstr(offset);
// return libRR_log_jump_label_with_name(offset, current_pc, label_name.c_str());
if (!libRR_disassembly[current_bank_str][offset_str].contains("label_name")) {
libRR_disassembly[current_bank_str][offset_str]["label_name"] = label_name;
}
libRR_disassembly[current_bank_str][offset_str]["meta"]["label_callers"][current_bank_str + "_" + n2hexstr(current_pc)] = true;
return label_name.c_str();
}
extern "C" void libRR_log_memory_read(int8_t bank, int32_t offset, const char* type, uint8_t byte_size, char* bytes) {
libRR_log_rom_read(bank, offset, type, byte_size, bytes);
}
extern "C" void libRR_log_rom_read(int16_t bank, int32_t offset, const char* type, uint8_t byte_size, char* bytes) {
string bank_str = n2hexstr(bank, 4);
string previous_bank_str = n2hexstr(previous_consecutive_rom_bank, 4);
string offset_str = n2hexstr(offset);
string current_consecutive_rom_start_str = n2hexstr(current_consecutive_rom_start);
if (libRR_full_trace_log) {
libRR_log_trace_str("Rom Read bank:"+bank_str+":"+n2hexstr(offset)+" = "+n2hexstr(bytes[0], 2));
}
// Check to see if the last read address is the same or 1 away
// Check for the same is because sometimes data is checked by reading the first byte
if (previous_consecutive_rom_bank == bank && previous_consecutive_rom_read == offset) {
// do nothing if its the same byte read twice
previous_consecutive_rom_bank = bank;
libRR_consecutive_rom_reads[previous_bank_str][current_consecutive_rom_start_str]["length"] = 1;
return;
}
if (previous_consecutive_rom_bank == bank && previous_consecutive_rom_read == (offset-1)) {
if (libRR_consecutive_rom_reads[previous_bank_str][current_consecutive_rom_start_str].is_null()) {
// check to see if the current read is null and if so create it
libRR_consecutive_rom_reads[previous_bank_str][current_consecutive_rom_start_str]["length"] = 1+ byte_size;
} else {
libRR_consecutive_rom_reads[previous_bank_str][current_consecutive_rom_start_str]["length"] = ((uint32_t) libRR_consecutive_rom_reads[previous_bank_str][current_consecutive_rom_start_str]["length"]) +byte_size;
}
for (int i=0; i<byte_size; i++) {
libRR_consecutive_rom_reads[previous_bank_str][current_consecutive_rom_start_str]["value"][n2hexstr(offset+i)] = n2hexstr(bytes[i]);
}
}
else {
// cout << "previous consecutive length from:" << (int)previous_consecutive_rom_bank << "::" << n2hexstr(current_consecutive_rom_start) << " -> " << n2hexstr(previous_consecutive_rom_read) << " len:" << libRR_consecutive_rom_reads[previous_bank_str][current_consecutive_rom_start_str]["length"] << "\n";
current_consecutive_rom_start = offset;
current_consecutive_rom_start_str = n2hexstr(current_consecutive_rom_start);
// initialise new consecutive run
libRR_consecutive_rom_reads[bank_str][current_consecutive_rom_start_str]["length"] = 1;
for (int i=0; i<byte_size; i++) {
libRR_consecutive_rom_reads[bank_str][current_consecutive_rom_start_str]["value"][n2hexstr(offset+i)] = n2hexstr(bytes[i]);
}
}
previous_consecutive_rom_read = offset+(byte_size-1); // add byte_size to take into account 2 byte reads
previous_consecutive_rom_bank = bank;
string value_str = "";
if (byte_size == 2) {
value_str = n2hexstr(two_bytes_to_16bit_value(bytes[1], bytes[0]));
} else {
value_str = n2hexstr(bytes[0]);
}
// printf("Access data: %d::%s type: %s size: %d value: %s\n", bank, n2hexstr(offset).c_str(), type, byte_size, value_str.c_str());
}
extern "C" void libRR_log_instruction_2int(uint32_t current_pc, const char* c_name, uint32_t instruction_bytes, int number_of_bytes, uint32_t operand, uint32_t operand2) {
if (!libRR_full_function_log || !libRR_finished_boot_rom) {
return;
}
std::string name(c_name);
replace(name, "%int%", libRR_constant_replace(operand));
replace(name, "%int2%", libRR_constant_replace(operand2));
libRR_log_instruction(current_pc, name, instruction_bytes, number_of_bytes);
}
// Takes a single int argument and replaces it in the string
extern "C" void libRR_log_instruction_1int(uint32_t current_pc, const char* c_name, uint32_t instruction_bytes, int number_of_bytes, uint32_t operand) {
return libRR_log_instruction_2int(current_pc, c_name, instruction_bytes, number_of_bytes, operand, 0);
}
extern "C" void libRR_log_instruction_1string(uint32_t current_pc, const char* c_name, uint32_t instruction_bytes, int number_of_bytes, const char* c_register_name) {
if (!libRR_full_function_log || !libRR_finished_boot_rom) {
return;
}
std::string name(c_name);
std::string register_name(c_register_name);
replace(name, "%str%",register_name);
libRR_log_instruction_1int(current_pc, name.c_str(), instruction_bytes, number_of_bytes, 0x00);
}
extern "C" void libRR_log_instruction_1int_registername(uint32_t current_pc, const char* c_name, uint32_t instruction_bytes, int number_of_bytes, uint32_t operand, const char* c_register_name) {
if (!libRR_full_function_log || !libRR_finished_boot_rom) {
return;
}
std::string name(c_name);
std::string register_name(c_register_name);
replace(name, "%r%",register_name);
libRR_log_instruction_1int(current_pc, name.c_str(), instruction_bytes, number_of_bytes, operand);
}
extern "C" void libRR_log_instruction_z80_s_d(uint32_t current_pc, const char* c_name, uint32_t instruction_bytes, int number_of_bytes, const char* source, const char* destination) {
if (!libRR_full_function_log || !libRR_finished_boot_rom) {
return;
}
std::string name(c_name);
replace(name, "%s%", source);
replace(name, "%d%", destination);
libRR_log_instruction(current_pc, name, instruction_bytes, number_of_bytes);
}
//
// Z80 End
//
// current_pc - current program counter
// instruction bytes as integer used for hex
// arguments - number of arguments - currently not really used for anything
// m - used for register number, replaces Rm with R1/R2 etc
void libRR_log_instruction(uint32_t current_pc, string name, uint32_t instruction_bytes, int number_of_bytes, unsigned m, unsigned n, unsigned imm, unsigned d, unsigned ea) {
if (!libRR_full_function_log || !libRR_finished_boot_rom) {
return;
}
replace(name, "%EA", "0x"+n2hexstr(ea));
libRR_log_instruction(current_pc, name, instruction_bytes, number_of_bytes, m, n, imm, d);
}
void libRR_log_instruction(uint32_t current_pc, string name, uint32_t instruction_bytes, int number_of_bytes, unsigned m, unsigned n, unsigned imm, unsigned d) {
if (!libRR_full_function_log || !libRR_finished_boot_rom) {
return;
}
replace(name, "#imm", "#"+to_string(imm));
replace(name, "disp", ""+to_string(d));
if (name.find("SysRegs") != std::string::npos) {
replace(name, "SysRegs[#0]", "MACH");
replace(name, "SysRegs[#1]", "MACL");
replace(name, "SysRegs[#2]", "PR");
}
libRR_log_instruction(current_pc, name, instruction_bytes, number_of_bytes, m, n);
}
void libRR_log_instruction(uint32_t current_pc, string name, uint32_t instruction_bytes, int number_of_bytes, unsigned m, unsigned n) {
if (!libRR_full_function_log || !libRR_finished_boot_rom) {
return;
}
replace(name, "Rm", "R"+to_string(m));
replace(name, "Rn", "R"+to_string(n));
libRR_log_instruction(current_pc, name, instruction_bytes, number_of_bytes);
}
extern "C" void libRR_log_instruction(uint32_t current_pc, const char* name, uint32_t instruction_bytes, int number_of_bytes)
{
if (!libRR_full_function_log || !libRR_finished_boot_rom) {
return;
}
// printf("libRR_log_instruction pc:%d name: %s bytes: %d\n", current_pc, name, instruction_bytes);
std::string str(name);
libRR_log_instruction(current_pc, str, instruction_bytes, number_of_bytes);
}
// C version of the c++ template
extern "C" const char* n2hexstr_c(int number, size_t hex_len) {
return n2hexstr(number, hex_len).c_str();
}
string libRR_constant_replace(uint32_t da8) {
string addr_str = n2hexstr(da8);
if (libRR_console_constants["addresses"].contains(addr_str)) {
return libRR_console_constants["addresses"][addr_str];
}
return "$"+n2hexstr(da8);
}
int32_t previous_pc = 0; // used for debugging
bool has_read_first_ever_instruction = false;
void libRR_log_instruction(uint32_t current_pc, string name, uint32_t instruction_bytes, int number_of_bytes) {
if (!libRR_full_function_log || !libRR_finished_boot_rom) {
return;
}
if (!has_read_first_ever_instruction) {
// special handling for the entry point, we wanr to force a label here to it gets written to output
libRR_log_jump_label_with_name(current_pc, current_pc, "entry");
has_read_first_ever_instruction = true;
libRR_isDelaySlot = false;
}
int bank = get_current_bank_number_for_address(current_pc);
string current_bank_str = n2hexstr(bank, 4);
// trace log each instruction
if (libRR_full_trace_log) {
libRR_log_trace_str(name + "; pc:"+current_bank_str+":"+n2hexstr(current_pc));
}
// Code used for debugging why an address was reached
if (libRR_enable_look && current_pc == libRR_offset_to_look_for) {
printf("Reached %s: previous addr: %s name:%s bank:%d \n ", n2hexstr(libRR_offset_to_look_for).c_str(), n2hexstr(previous_pc).c_str(), name.c_str(), bank);
}
// end debugging code
if (strcmp(libRR_console,"Saturn")==0) {
printf("isSaturn\n");
// For saturn we remove 2 from the program counter, but this will vary per console
current_pc -= 4; // was -2
}
// string current_function = n2hexstr(function_stack.back());
string current_pc_str = n2hexstr(current_pc);
// printf("libRR_log_instruction %s \n", current_function.c_str());
if (strcmp(libRR_console,"Saturn")==0) {
if (libRR_isDelaySlot) {
current_pc_str = n2hexstr(libRR_delay_slot_pc - 2); //subtract 2 as pc is ahead
// printf("Delay Slot %s \n", current_pc_str.c_str());
libRR_isDelaySlot = false;
}
}
// TODO: Hex bytes should change based on number_of_bytes
string hexBytes = n2hexstr((uint32_t)instruction_bytes, number_of_bytes*2);
// if we are below the max addr of bank 0 (e.g 0x4000 for GB) then we are always in bank 0
// if (current_pc <libRR_slot_0_max_addr) {
// current_bank_str="0000";
// }
// libRR_disassembly[current_bank_str][current_pc_str][name]["frame"]=RRCurrentFrame;
libRR_disassembly[current_bank_str][current_pc_str][name]["bytes"]=hexBytes;
libRR_disassembly[current_bank_str][current_pc_str][name]["bytes_length"]=number_of_bytes;
previous_pc = current_pc;
} | 40.186519 | 312 | 0.672836 |
274859fcc3c14d6621bb5912b64e71495ce6c751 | 518 | cpp | C++ | C++/402.remove-k-digits.cpp | WilliamZhaoz/github | 2aa0eb17e272249fc225cf2e9861c4c44bd0e265 | [
"MIT"
] | 1 | 2018-03-06T05:07:22.000Z | 2018-03-06T05:07:22.000Z | C++/402.remove-k-digits.cpp | WilliamZhaoz/github | 2aa0eb17e272249fc225cf2e9861c4c44bd0e265 | [
"MIT"
] | 1 | 2021-12-24T16:41:02.000Z | 2021-12-24T16:41:02.000Z | C++/402.remove-k-digits.cpp | WilliamZhaoz/github | 2aa0eb17e272249fc225cf2e9861c4c44bd0e265 | [
"MIT"
] | null | null | null | class Solution {
public:
string removeKdigits(string num, int k) {
int n = num.size();
int leave = n - k;
string res = "";
for (int i = 0; i < num.size(); i++) {
while (k && res.back() > num[i]) {
k--;
res.pop_back();
}
res += num[i];
}
res.resize(leave);
while (!res.empty() && res[0] == '0') {
res.erase(res.begin());
}
return res.empty() ? "0" : res;
}
}; | 25.9 | 47 | 0.3861 |
27491f61d7399b5fc86b9abe57f70c2615370f62 | 1,688 | cpp | C++ | vs2017/ui/mainwindow/workbench/AppStoreList.cpp | cheechang/cppcc | 0292e9a9b27e0579970c83b4f6a75dcdae1558bf | [
"MIT"
] | null | null | null | vs2017/ui/mainwindow/workbench/AppStoreList.cpp | cheechang/cppcc | 0292e9a9b27e0579970c83b4f6a75dcdae1558bf | [
"MIT"
] | null | null | null | vs2017/ui/mainwindow/workbench/AppStoreList.cpp | cheechang/cppcc | 0292e9a9b27e0579970c83b4f6a75dcdae1558bf | [
"MIT"
] | null | null | null | #include "AppStoreList.h"
#include <QListWidgetItem>
#include "AppStoreListItem.h"
namespace ui{
AppStoreList::AppStoreList(QWidget *parent)
: QListWidget(parent)
{
m_pAppMgr = APPMGRCONTROL;
CONNECT_SERVICE(GetApplication(std::vector<data::AppInfo>));
if (m_pAppMgr != CNull)
{
m_pAppMgr->getAllApplication(CBind
(&AppStoreList::signalSerGetApplication, this,
CPlaceholders _1));
}
this->setSelectionMode(SelectionMode::NoSelection);
this->setObjectName("appStoreList");
}
AppStoreList::~AppStoreList()
{
}
void AppStoreList::onSerGetApplication(std::vector<data::AppInfo> vec)
{
for (int i = 0; i < vec.size(); i++)
{
QListWidgetItem* pItem = new QListWidgetItem(this);
AppStoreListItem* pListItem = new AppStoreListItem(this);
connect(pListItem, SIGNAL(installApp(int64, QString, QString, QString)),
this, SLOT(onInstallApp(int64, QString, QString, QString)));
connect(pListItem, SIGNAL(uninstallApp(int64)),
this, SLOT(onUninstallApp(int64)));
pListItem->setAppID(vec[i].appID);
pListItem->setName(QString::fromUtf8(vec[i].name.data()));
pListItem->setAvatar(QString::fromUtf8(vec[i].icon.data()));
pListItem->setIntroduce(QString::fromUtf8(vec[i].introduction.data()));
pListItem->setUrl(QString::fromUtf8(vec[i].url.data()));
pListItem->setButtonStatus(vec[i].isInstalled);
this->setItemWidget(pItem, pListItem);
}
//this->update();
}
void AppStoreList::onInstallApp(int64 iAppID, QString strName,
QString strIcon, QString strUrl)
{
emit installApp(iAppID, strName, strIcon, strUrl);
}
void AppStoreList::onUninstallApp(int64 iAppID)
{
emit uninstallApp(iAppID);
}
}
| 25.969231 | 75 | 0.716232 |
2749c9f90bf8cb43cd61b4ac13cdec61c38d4d45 | 407 | cpp | C++ | Course 201809/homework/11/C1.cpp | Seizzzz/DailyCodes | 9a617fb64ee27b9f254be161850e9c9a61747cb1 | [
"MIT"
] | null | null | null | Course 201809/homework/11/C1.cpp | Seizzzz/DailyCodes | 9a617fb64ee27b9f254be161850e9c9a61747cb1 | [
"MIT"
] | null | null | null | Course 201809/homework/11/C1.cpp | Seizzzz/DailyCodes | 9a617fb64ee27b9f254be161850e9c9a61747cb1 | [
"MIT"
] | null | null | null | #include <stdio.h>
#include <stdlib.h>
int main()
{
int **a,n ,m;
scanf("%d%d",&n,&m);
a=(int **)malloc(sizeof(int *)*n);
int i=0,j=0;
for(;i<n;i++)
{
a[i]=(int *)malloc(sizeof(int *)*m);
for(int j=0;j<m;j++) scanf("%d",&a[i][j]);
}
for(int i=0;i<n;i++)
{
for(int j=0;j<m;j++) printf("%d ",a[i][j] * (-10));
printf("\n");
}
for(i=0;i<n;i++) free(a[i]);
free(a);
return 0;
}
| 14.034483 | 53 | 0.46683 |
274b82dafccc64c402de9bd66315b1e8e8c56fd1 | 16,654 | cpp | C++ | regex_to_min_dfa.cpp | avinal/C_ode | f056da37c8c56a4a62a06351c2ea3773d16d1b11 | [
"MIT"
] | 1 | 2020-08-23T20:21:35.000Z | 2020-08-23T20:21:35.000Z | regex_to_min_dfa.cpp | avinal/C_ode | f056da37c8c56a4a62a06351c2ea3773d16d1b11 | [
"MIT"
] | null | null | null | regex_to_min_dfa.cpp | avinal/C_ode | f056da37c8c56a4a62a06351c2ea3773d16d1b11 | [
"MIT"
] | 2 | 2019-03-18T10:22:13.000Z | 2021-01-03T10:12:28.000Z | #include <iostream>
#include <vector>
#include <stack>
#include <set>
#include <queue>
#include <map>
#include<string>
using namespace std;
struct nst
{
vector<int> a[2], e;
bool f = 0;
};
vector<nst> nfa;
struct dst
{
int a[2] = {-1, -1};
bool f = 0;
};
vector<dst> dfa;
stack<int> st;
int nfa_size, dfa_size;
string dispregex;
struct nst init_nfa_state;
struct dst init_dfa_state;
void custom_clear()
{
for (int i = 0; i < 100; i++)
cout << endl;
}
/***************************** regex to nfa ****************************/
string insert_concat(string regexp)
{
string ret = "";
char c, c2;
for (unsigned int i = 0; i < regexp.size(); i++)
{
c = regexp[i];
if (i + 1 < regexp.size())
{
c2 = regexp[i + 1];
ret += c;
if (c != '(' && c2 != ')' && c != '+' && c2 != '+' && c2 != '*')
{
ret += '.';
}
}
}
ret += regexp[regexp.size() - 1];
return ret;
}
void character(int i)
{
nfa.push_back(init_nfa_state);
nfa.push_back(init_nfa_state);
nfa[nfa_size].a[i].push_back(nfa_size + 1);
st.push(nfa_size);
nfa_size++;
st.push(nfa_size);
nfa_size++;
}
void union_()
{
nfa.push_back(init_nfa_state);
nfa.push_back(init_nfa_state);
int d = st.top();
st.pop();
int c = st.top();
st.pop();
int b = st.top();
st.pop();
int a = st.top();
st.pop();
nfa[nfa_size].e.push_back(a);
nfa[nfa_size].e.push_back(c);
nfa[b].e.push_back(nfa_size + 1);
nfa[d].e.push_back(nfa_size + 1);
st.push(nfa_size);
nfa_size++;
st.push(nfa_size);
nfa_size++;
}
void concatenation()
{
int d = st.top();
st.pop();
int c = st.top();
st.pop();
int b = st.top();
st.pop();
int a = st.top();
st.pop();
nfa[b].e.push_back(c);
st.push(a);
st.push(d);
}
void kleene_star()
{
nfa.push_back(init_nfa_state);
nfa.push_back(init_nfa_state);
int b = st.top();
st.pop();
int a = st.top();
st.pop();
nfa[nfa_size].e.push_back(a);
nfa[nfa_size].e.push_back(nfa_size + 1);
nfa[b].e.push_back(a);
nfa[b].e.push_back(nfa_size + 1);
st.push(nfa_size);
nfa_size++;
st.push(nfa_size);
nfa_size++;
}
void postfix_to_nfa(string postfix)
{
for (unsigned int i = 0; i < postfix.size(); i++)
{
switch (postfix[i])
{
case 'a':
case 'b':
character(postfix[i] - 'a');
break;
case '*':
kleene_star();
break;
case '.':
concatenation();
break;
case '+':
union_();
}
}
}
void display_nfa()
{
cout << endl
<< endl;
cout << "Phase 1: regex to nfa conversion using thompson's construction algorithm\n";
cout << "------------------------------------------------------------------------\n";
cout << "State\t|\ta\t|\tb\t|\teps\t|accepting state|" << endl;
cout << "------------------------------------------------------------------------\n";
for (unsigned int i = 0; i < nfa.size(); i++)
{
cout << i << "\t|\t";
for (unsigned int j = 0; j < nfa[i].a[0].size(); j++)
cout << nfa[i].a[0][j] << ' ';
cout << "\t|\t";
for (unsigned int j = 0; j < nfa[i].a[1].size(); j++)
cout << nfa[i].a[1][j] << ' ';
cout << "\t|\t";
for (unsigned int j = 0; j < nfa[i].e.size(); j++)
cout << nfa[i].e[j] << ' ';
cout << "\t|\t";
if (nfa[i].f)
cout << "Yes";
else
cout << "No";
cout << "\t|\n";
}
cout << "------------------------------------------------------------------------\n";
}
int priority(char c)
{
switch (c)
{
case '*':
return 3;
case '.':
return 2;
case '+':
return 1;
default:
return 0;
}
}
string regexp_to_postfix(string regexp)
{
string postfix = "";
stack<char> op;
char c;
for (unsigned int i = 0; i < regexp.size(); i++)
{
switch (regexp[i])
{
case 'a':
case 'b':
postfix += regexp[i];
break;
case '(':
op.push(regexp[i]);
break;
case ')':
while (op.top() != '(')
{
postfix += op.top();
op.pop();
}
op.pop();
break;
default:
while (!op.empty())
{
c = op.top();
if (priority(c) >= priority(regexp[i]))
{
postfix += op.top();
op.pop();
}
else
break;
}
op.push(regexp[i]);
}
//cout<<regexp[i]<<' '<<postfix<<endl;
}
while (!op.empty())
{
postfix += op.top();
op.pop();
}
return postfix;
}
/***************************** nfa to dfa ****************************/
void print_dfa()
{
cout << endl;
cout << "NFA TO DFA CONVERSION" << endl;
cout << "---------------------------------------------------------" << endl;
cout << "STATE\t|\t"
<< "a"
<< "\t|\t"
<< "b"
<< "\t|\t"
<< "FINAL"
<< "\t|" << endl;
cout << "---------------------------------------------------------" << endl;
for (int i = 0; i < dfa.size(); i++)
{
cout << i << "\t|\t" << dfa[i].a[0] << "\t|\t" << dfa[i].a[1] << "\t|\t" << dfa[i].f << "\t|" << endl;
}
cout << "---------------------------------------------------------" << endl;
}
void epsilon_closure(int state, set<int> &si)
{
for (unsigned int i = 0; i < nfa[state].e.size(); i++)
{
if (si.count(nfa[state].e[i]) == 0)
{
si.insert(nfa[state].e[i]);
epsilon_closure(nfa[state].e[i], si);
}
}
}
set<int> state_change(int c, set<int> &si)
{
set<int> temp;
if (c == 1)
{
for (std::set<int>::iterator it = si.begin(); it != si.end(); ++it)
{
for (unsigned int j = 0; j < nfa[*it].a[0].size(); j++)
{
temp.insert(nfa[*it].a[0][j]);
}
}
}
else
{
for (std::set<int>::iterator it = si.begin(); it != si.end(); ++it)
{
for (unsigned int j = 0; j < nfa[*it].a[1].size(); j++)
{
temp.insert(nfa[*it].a[1][j]);
}
}
}
return temp;
}
void nfa_to_dfa(set<int> &si, queue<set<int>> &que, int start_state)
{
map<set<int>, int> mp;
mp[si] = -1;
set<int> temp1;
set<int> temp2;
int ct = 0;
si.clear();
si.insert(0);
epsilon_closure(start_state, si);
if (mp.count(si) == 0)
{
mp[si] = ct++;
que.push(si);
}
int p = 0;
bool f1 = false;
while (que.size() != 0)
{
dfa.push_back(init_dfa_state);
si.empty();
si = que.front();
f1 = false;
for (set<int>::iterator it = si.begin(); it != si.end(); ++it)
{
if (nfa[*it].f == true)
f1 = true;
}
dfa[p].f = f1;
temp1 = state_change(1, si);
si = temp1;
for (set<int>::iterator it = si.begin(); it != si.end(); ++it)
{
epsilon_closure(*it, si);
}
if (mp.count(si) == 0)
{
mp[si] = ct++;
que.push(si);
dfa[p].a[0] = ct - 1;
}
else
{
dfa[p].a[0] = mp.find(si)->second;
}
temp1.clear();
si = que.front();
temp2 = state_change(2, si);
si = temp2;
for (set<int>::iterator it = si.begin(); it != si.end(); ++it)
{
epsilon_closure(*it, si);
}
if (mp.count(si) == 0)
{
mp[si] = ct++;
que.push(si);
dfa[p].a[1] = ct - 1;
}
else
{
dfa[p].a[1] = mp.find(si)->second;
}
temp2.clear();
que.pop();
p++;
}
for (int i = 0; i < p; i++)
{
if (dfa[i].a[0] == -1)
dfa[i].a[0] = p;
if (dfa[i].a[1] == -1)
dfa[i].a[1] = p;
}
dfa.push_back(init_dfa_state);
dfa[p].a[0] = p;
dfa[p].a[1] = p;
//cout<<p<<endl;
}
/***************************** min dfa ****************************/
/// Function to minimize DFA
pair<int, vector<tuple<int, int, bool>>> minimize_dfa(vector<dst> dfa)
{
//cout<<dfa.size()<<endl;
vector<int> grp(dfa.size()); /// Group number for states
vector<vector<int>> part(2, vector<int>()); /// Partition for groups
/// Initializing the groups
part[0].push_back(0);
for (int i = 1; i < (int)grp.size(); i++)
{
if (dfa[i].f == dfa[0].f)
{
grp[i] = 0;
part[0].push_back(i);
}
else
{
grp[i] = 1;
part[1].push_back(i);
}
}
if (!part[1].size())
part.erase(part.end());
/// Loop until no new partition is created
bool chk = true; /// Check if any new partition is created
int strt = 0; /// Starting State
while (chk)
{
chk = false;
/*for(int i=0; i<part.size(); i++) {
cout<<i<<":";
for(int j=0; j<part[i].size(); j++) {
cout<<part[i][j]<<" ";
} cout<<endl;
} cout<<endl;*/
/// Iterate over partitions and alphabets
for (int i = 0; i < part.size(); i++)
{
for (int j = 0; j < 2; j++)
{
vector<pair<int, int>> trans(part[i].size()); /// Transitions for the states of partitions
/// Iterate over states of partitions and find transition groups
for (int k = 0; k < part[i].size(); k++)
{
if (dfa[part[i][k]].a[j] >= 0)
trans[k] = make_pair(grp[dfa[part[i][k]].a[j]], part[i][k]);
else
trans[k] = make_pair(-1, part[i][k]);
}
sort(trans.begin(), trans.end());
/// Break partition in case of different transitions
if (trans[0].first != trans[trans.size() - 1].first)
{
chk = true;
int k, m = part.size() - 1;
part[i].clear();
part[i].push_back(trans[0].second);
for (k = 1; k < trans.size() && (trans[k].first == trans[k - 1].first); k++)
{
part[i].push_back(trans[k].second);
}
while (k < trans.size())
{
if (trans[k].first != trans[k - 1].first)
{
part.push_back(vector<int>());
m++;
}
grp[trans[k].second] = m;
part[m].push_back(trans[k].second);
k++;
}
}
}
}
}
for (int i = 0; i < part.size(); i++)
{
for (int j = 0; j < part[i].size(); j++)
{
if (part[i][j] == 0)
strt = i;
}
}
vector<tuple<int, int, bool>> ret(part.size());
//cout<<part.size()<<endl;
//sort(part.begin(), part.end());
for (int i = 0; i < (int)part.size(); i++)
{
//cout<<grp[part[i][0]]<<endl;
get<0>(ret[i]) = (dfa[part[i][0]].a[0] >= 0) ? grp[dfa[part[i][0]].a[0]] : -1;
get<1>(ret[i]) = (dfa[part[i][0]].a[1] >= 0) ? grp[dfa[part[i][0]].a[1]] : -1;
get<2>(ret[i]) = dfa[part[i][0]].f;
}
return make_pair(strt, ret);
}
void print_menu()
{
cout << "\n---------------------------------------\n";
cout << "Input Regex: " << dispregex << endl
<< endl;
cout << "1. NFA\n";
cout << "2. Intermediate DFA\n";
cout << "3. Minimized DFA\n";
cout << "4. Simulation\n";
cout << "Press any other key to exit...\n\n";
}
void print(vector<tuple<int, int, bool>> min_dfa)
{
cout << "---------------------------------------------------------" << endl;
cout << "State\t|\tA\t|\tB\t|\tFinal\t|" << endl;
cout << "---------------------------------------------------------" << endl;
for (int i = 0; i < (int)min_dfa.size(); i++)
{
cout << i << "\t|\t";
cout << get<0>(min_dfa[i]) << "\t|\t";
cout << get<1>(min_dfa[i]) << "\t|\t";
if (get<2>(min_dfa[i]))
cout << "Yes\t|";
else
cout << "No\t|";
cout << endl;
}
cout << "---------------------------------------------------------" << endl;
}
void simulate(int start_st, vector<tuple<int, int, bool>> min_dfa)
{
print_menu();
cout << "Enter string : ";
string input;
cin.ignore();
getline(cin, input);
int curr_state, next_state;
curr_state = start_st;
custom_clear();
cout << "-----------------------------------------" << endl;
cout << "Input\t|\tCurrent\t|\tNext\t|" << endl;
cout << "-----------------------------------------" << endl;
for (unsigned i = 0; i < input.size(); i++)
{
if (input[i] == 'a')
next_state = get<0>(min_dfa[curr_state]);
else
next_state = get<1>(min_dfa[curr_state]);
cout << input[i] << "\t|\t" << curr_state << "\t|\t" << next_state << "\t|\n";
curr_state = next_state;
}
cout << "-----------------------------------------" << endl;
cout << endl
<< "Verdict: ";
if (curr_state >= 0 && get<2>(min_dfa[curr_state]))
cout << "Accepted";
else
cout << "Rejected";
cout << endl;
}
int main()
{
custom_clear();
string regexp, postfix;
cout << "Enter Regular Expression: ";
cin >> regexp;
dispregex = regexp;
regexp = insert_concat(regexp);
postfix = regexp_to_postfix(regexp);
cout << "Postfix Expression: " << postfix << endl;
postfix_to_nfa(postfix);
int final_state = st.top();
st.pop();
int start_state = st.top();
st.pop();
//cout<<start_state<<' '<<final_state<<endl;
nfa[final_state].f = 1;
set<int> si;
queue<set<int>> que;
nfa_to_dfa(si, que, start_state);
cout << endl
<< endl;
pair<int, vector<tuple<int, int, bool>>> min_dfa_tmp = minimize_dfa(dfa);
vector<tuple<int, int, bool>> min_dfa = min_dfa_tmp.second;
int start_st = min_dfa_tmp.first;
getchar();
custom_clear();
while (1)
{
print_menu();
char choice;
choice = getchar();
custom_clear();
switch (choice)
{
case '1':
display_nfa();
getchar();
break;
case '2':
print_dfa();
getchar();
break;
case '3':
print(min_dfa);
getchar();
break;
case '4':
simulate(start_st, min_dfa);
break;
default:
exit(EXIT_SUCCESS);
}
}
cout << endl
<< endl;
cout << "Enter string : ";
string input;
cin.ignore();
getline(cin, input);
int curr_state, next_state;
while (input != "")
{
//cout<<input<<endl;
curr_state = start_st;
for (unsigned i = 0; i < input.size(); i++)
{
if (curr_state >= 0)
{
if (input[i] == 'a')
next_state = get<0>(min_dfa[curr_state]);
else
next_state = get<1>(min_dfa[curr_state]);
if (next_state >= 0)
{
cout << input[i] << " : State " << curr_state << " -> State " << next_state << endl;
}
else
cout << input[i] << " : State " << curr_state << " -> Trap State" << endl;
}
else
cout << input[i] << " : Trapped" << endl;
curr_state = next_state;
}
if (curr_state >= 0 && get<2>(min_dfa[curr_state]))
cout << "accepted";
else
cout << "rejected";
cout << endl
<< endl;
cout << "Enter string : ";
getline(cin, input);
}
return 0;
}
| 25.119155 | 110 | 0.402066 |
274cbc7004d0d77513d27a2b76ca6151e5f7e538 | 2,942 | cc | C++ | cc/ipc/render_pass_struct_traits.cc | Wzzzx/chromium-crosswalk | 768dde8efa71169f1c1113ca6ef322f1e8c9e7de | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | 2 | 2019-01-28T08:09:58.000Z | 2021-11-15T15:32:10.000Z | cc/ipc/render_pass_struct_traits.cc | Wzzzx/chromium-crosswalk | 768dde8efa71169f1c1113ca6ef322f1e8c9e7de | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | null | null | null | cc/ipc/render_pass_struct_traits.cc | Wzzzx/chromium-crosswalk | 768dde8efa71169f1c1113ca6ef322f1e8c9e7de | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | 6 | 2020-09-23T08:56:12.000Z | 2021-11-18T03:40:49.000Z | // Copyright 2016 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "cc/ipc/render_pass_struct_traits.h"
#include "base/numerics/safe_conversions.h"
#include "cc/ipc/shared_quad_state_struct_traits.h"
namespace mojo {
// static
void* StructTraits<cc::mojom::RenderPass, std::unique_ptr<cc::RenderPass>>::
SetUpContext(const std::unique_ptr<cc::RenderPass>& input) {
DCHECK_GT(input->quad_list.size(), 0u);
std::unique_ptr<mojo::Array<uint32_t>> sqs_references(
new mojo::Array<uint32_t>(input->quad_list.size()));
cc::SharedQuadStateList::ConstIterator sqs_iter =
input->shared_quad_state_list.begin();
for (auto it = input->quad_list.begin(); it != input->quad_list.end(); ++it) {
if ((*it)->shared_quad_state != *sqs_iter)
++sqs_iter;
(*sqs_references)[it.index()] =
base::checked_cast<uint32_t>(sqs_iter.index());
DCHECK_NE(nullptr, (*it)->shared_quad_state);
DCHECK_EQ(*sqs_iter, (*it)->shared_quad_state);
}
DCHECK_EQ(input->shared_quad_state_list.size() - 1, sqs_iter.index());
return sqs_references.release();
}
// static
void StructTraits<cc::mojom::RenderPass, std::unique_ptr<cc::RenderPass>>::
TearDownContext(const std::unique_ptr<cc::RenderPass>& input,
void* context) {
// static_cast to ensure the destructor is called.
delete static_cast<mojo::Array<uint32_t>*>(context);
}
// static
bool StructTraits<cc::mojom::RenderPass, std::unique_ptr<cc::RenderPass>>::Read(
cc::mojom::RenderPassDataView data,
std::unique_ptr<cc::RenderPass>* out) {
*out = cc::RenderPass::Create();
if (!data.ReadId(&(*out)->id) || !data.ReadOutputRect(&(*out)->output_rect) ||
!data.ReadDamageRect(&(*out)->damage_rect) ||
!data.ReadTransformToRootTarget(&(*out)->transform_to_root_target)) {
return false;
}
(*out)->has_transparent_background = data.has_transparent_background();
if (!data.ReadQuadList(&(*out)->quad_list) ||
!data.ReadSharedQuadStateList(&(*out)->shared_quad_state_list))
return false;
mojo::Array<uint32_t> shared_quad_state_references;
if (!data.ReadSharedQuadStateReferences(&shared_quad_state_references))
return false;
if ((*out)->quad_list.size() != shared_quad_state_references.size())
return false;
cc::SharedQuadStateList::ConstIterator sqs_iter =
(*out)->shared_quad_state_list.begin();
for (auto it = (*out)->quad_list.begin(); it != (*out)->quad_list.end();
++it) {
if (sqs_iter.index() != shared_quad_state_references[it.index()])
++sqs_iter;
if (shared_quad_state_references[it.index()] != sqs_iter.index())
return false;
(*it)->shared_quad_state = *sqs_iter;
if (!(*it)->shared_quad_state)
return false;
}
return sqs_iter.index() == (*out)->shared_quad_state_list.size() - 1;
}
} // namespace mojo
| 37.717949 | 80 | 0.692386 |
274ce82c885e09cfd9385abc9b22a029ac0417a1 | 1,731 | cc | C++ | netlibcc/base/Socket.cc | kohakus/tiny-netlib | da9998ee06f4e2eb5ebcaf0e383196269dea1f33 | [
"MIT"
] | 1 | 2021-03-05T10:14:27.000Z | 2021-03-05T10:14:27.000Z | netlibcc/base/Socket.cc | kohakus/tiny-netlib | da9998ee06f4e2eb5ebcaf0e383196269dea1f33 | [
"MIT"
] | null | null | null | netlibcc/base/Socket.cc | kohakus/tiny-netlib | da9998ee06f4e2eb5ebcaf0e383196269dea1f33 | [
"MIT"
] | null | null | null | #include "netlibcc/base/Socket.h"
#include <netinet/tcp.h>
#include <netinet/in.h>
#include <cstdio>
#include "netlibcc/base/InetAddr.h"
#include "netlibcc/base/SockOps.h"
#include "netlibcc/core/Logger.h"
namespace netlibcc {
namespace net {
Socket::~Socket() {
sockets::close(sockfd_);
}
void Socket::listen() {
sockets::listen(sockfd_);
}
void Socket::bind(const InetAddr& local_addr) {
sockets::bind(sockfd_, local_addr.getSockAddr());
}
int Socket::accept(InetAddr* peer_addr) {
// address that return from accept
struct sockaddr_in addr;
::memset(&addr, 0, sizeof addr);
int connfd = sockets::accept(sockfd_, &addr);
if (connfd >= 0) {
peer_addr->setSockAddrInet(addr);
}
return connfd;
}
void Socket::shutdownWrite() {
sockets::shutdownWR(sockfd_);
}
// Socket option setting
bool Socket::setTcpNoDelay(bool on) {
int val = on ? 1 : 0;
return ::setsockopt(sockfd_, IPPROTO_TCP, TCP_NODELAY, &val,
static_cast<socklen_t>(sizeof val)) < 0 ? false : true;
}
bool Socket::setReuseAddr(bool on) {
int val = on ? 1 : 0;
return ::setsockopt(sockfd_, SOL_SOCKET, SO_REUSEADDR, &val,
static_cast<socklen_t>(sizeof val)) < 0 ? false : true;
}
bool Socket::setReusePort(bool on) {
int val = on ? 1 : 0;
return ::setsockopt(sockfd_, SOL_SOCKET, SO_REUSEPORT, &val,
static_cast<socklen_t>(sizeof val)) < 0 ? false : true;
}
bool Socket::setKeepAlive(bool on) {
int val = on ? 1 : 0;
return ::setsockopt(sockfd_, SOL_SOCKET, SO_KEEPALIVE, &val,
static_cast<socklen_t>(sizeof val)) < 0 ? false : true;
}
} // namespace net
} // namespace netlibcc | 25.835821 | 79 | 0.638937 |
27525b161306b860b02f28e342178932470bbecf | 21,657 | cpp | C++ | source/add-ons/Quantize/Quantize.cpp | thaflo/Becasso | 9a1411913ee46f4dfa5116def50ebc41495dad28 | [
"MIT"
] | 2 | 2020-10-05T14:18:09.000Z | 2021-08-05T02:56:43.000Z | source/add-ons/Quantize/Quantize.cpp | thaflo/Becasso | 9a1411913ee46f4dfa5116def50ebc41495dad28 | [
"MIT"
] | 26 | 2017-01-10T19:54:10.000Z | 2020-12-17T07:28:57.000Z | source/add-ons/Quantize/Quantize.cpp | thaflo/Becasso | 9a1411913ee46f4dfa5116def50ebc41495dad28 | [
"MIT"
] | 5 | 2017-12-14T18:46:08.000Z | 2020-12-13T18:22:34.000Z | // © 2000-2001 Sum Software
#define BUILDING_ADDON
#include "BecassoAddOn.h"
#include "AddOnSupport.h"
#include "Slider.h"
#include <string.h>
#include <CheckBox.h>
#include <RadioButton.h>
#include <Box.h>
#define bzero(p,n) memset (p, 0, n)
int16 *gLut = 0;
#define FOREGROUND 0
#define BACKGROUND 1
#define R_BITS 5
#define G_BITS 6
#define B_BITS 5
#define R_PREC (1<<R_BITS)
#define G_PREC (1<<G_BITS)
#define B_PREC (1<<B_BITS)
#define ELEM(array,r,g,b) (array[b*R_PREC*G_PREC+r*G_PREC+g])
// This is because on MWCC, the huge array needed for the lut can't be
// created on the stack. Hence this workaround.
//#define FLOAT_WEIGHTS 1
// Strangely, the new weights give worst results.
// With the integer weights, results are almost identical with the old floats,
// and probably a lot faster.
#if defined (FLOAT_WEIGHTS)
# define R_WEIGHT 0.2125
# define G_WEIGHT 0.7154
# define B_WEIGHT 0.0721
#elif defined (OLD_WEIGHTS)
# define R_WEIGHT 0.299
# define G_WEIGHT 0.587
# define B_WEIGHT 0.114
#else
# define R_WEIGHT 2
# define G_WEIGHT 3
# define B_WEIGHT 1
#endif
#define R_SHIFT 3
#define G_SHIFT 2
#define B_SHIFT 3
/* log2(histogram cells in update box) for each axis; this can be adjusted */
#define BOX_R_LOG (R_BITS - 3)
#define BOX_G_LOG (G_BITS - 3)
#define BOX_B_LOG (B_BITS - 3)
#define BOX_R_ELEMS (1 << BOX_R_LOG) /* # of hist cells in update box */
#define BOX_G_ELEMS (1 << BOX_G_LOG)
#define BOX_B_ELEMS (1 << BOX_B_LOG)
#define BOX_R_SHIFT (R_SHIFT + BOX_R_LOG)
#define BOX_G_SHIFT (G_SHIFT + BOX_G_LOG)
#define BOX_B_SHIFT (B_SHIFT + BOX_B_LOG)
class QView : public BView
{
public:
QView (BRect rect) : BView (rect, "Quantize_view", B_FOLLOW_ALL, B_WILL_DRAW)
{
fNumColors = 256;
fDitherCB = NULL;
fPalette = FOREGROUND;
ResizeTo (188, 118);
Slider *nSlid = new Slider (BRect (8, 8, 180, 24), 50, "# Colors", 1, 256, 1, new BMessage ('numC'));
AddChild (nSlid);
nSlid->SetValue (256);
fDitherCB = new BCheckBox (BRect (8, 30, 180, 46), "dither", "Floyd-Steinberg Dithering", new BMessage ('fsDt'));
fDitherCB->SetValue (false);
AddChild (fDitherCB);
BBox *palB = new BBox (BRect (8, 54, 180, 110), "palette");
palB->SetLabel ("Use Colors From");
AddChild (palB);
BRadioButton *fgF = new BRadioButton (BRect (4, 14, 170, 30), "fg", "Foreground Palette", new BMessage ('palF'));
BRadioButton *fgB = new BRadioButton (BRect (4, 32, 170, 48), "bg", "Background Palette", new BMessage ('palB'));
palB->AddChild (fgF);
palB->AddChild (fgB);
fgF->SetValue (true);
}
virtual ~QView () {}
virtual void MessageReceived (BMessage *msg);
int numColors () { return fNumColors; }
bool dither () { return (fDitherCB ? fDitherCB->Value() : false); }
int palette () { return fPalette; }
BCheckBox *fDitherCB;
private:
int fNumColors;
int fPalette;
};
QView *view = NULL;
void QView::MessageReceived (BMessage *msg)
{
switch (msg->what)
{
case 'numC':
fNumColors = int (msg->FindFloat ("value"));
break;
case 'fsDt':
// We query the button itself...
break;
case 'palF':
fPalette = FOREGROUND;
break;
case 'palB':
fPalette = BACKGROUND;
break;
default:
BView::MessageReceived (msg);
return;
}
for (int32 i = 0; i < R_PREC; i++)
for (int32 j = 0; j < G_PREC; j++)
for (int32 k = 0; k < B_PREC; k++)
ELEM (gLut, i, j, k) = -1; // We build the LUT on the fly
addon_preview();
}
status_t addon_init (uint32 index, becasso_addon_info *info)
{
strcpy (info->name, "Quantize");
strcpy (info->author, "Sander Stoks");
strcpy (info->copyright, "© 2000-2001 ∑ Sum Software");
strcpy (info->description, "Quantizes the colors to a given palette");
info->type = BECASSO_FILTER;
info->index = index;
info->version = 0;
info->release = 7;
info->becasso_version = 2;
info->becasso_release = 0;
info->does_preview = PREVIEW_FULLSCALE;
info->flags = LAYER_ONLY;
return B_OK;
}
status_t addon_close (void)
{
delete [] gLut;
gLut = 0;
return B_OK;
}
status_t addon_exit (void)
{
return B_OK;
}
void fill_lut (int16 *lut, rgb_color palette[], int max_colors, int r, int g, int b);
int find_nearby_colors (rgb_color palette[], int numcolors, uint8 color_list[], int min_r, int min_g, int min_b);
void find_best_colors (rgb_color palette[], int numcolors, int minr, int ming, int minb, uint8 colorlist[], uint8 bestcolors[]);
int find_nearby_colors (rgb_color palette[], int numcolors, uint8 color_list[], int minr, int ming, int minb)
{
int maxr, maxg, maxb;
int cr, cg, cb;
int i, x, ncolors;
float minmaxdist, min_dist, max_dist, tdist;
float mindist[256]; // 256 = the maximum palette size, actually.
maxr = minr + ((1 << BOX_R_SHIFT) - (1 << R_SHIFT));
cr = (minr + maxr)/2;
maxg = ming + ((1 << BOX_G_SHIFT) - (1 << G_SHIFT));
cg = (ming + maxg)/2;
maxb = minb + ((1 << BOX_B_SHIFT) - (1 << B_SHIFT));
cb = (minb + maxb)/2;
/* For each color in colormap, find:
* 1. its minimum squared-distance to any point in the update box
* (zero if color is within update box);
* 2. its maximum squared-distance to any point in the update box.
* Both of these can be found by considering only the corners of the box.
* We save the minimum distance for each color in mindist[];
* only the smallest maximum distance is of interest.
*/
minmaxdist = 0x7FFFFFFFL;
for (i = 0; i < numcolors; i++)
{
/* We compute the squared-r-distance term, then add in the other two. */
x = palette[i].red;
if (x < minr)
{
tdist = (x - minr)*R_WEIGHT;
min_dist = tdist*tdist;
tdist = (x - maxr)*R_WEIGHT;
max_dist = tdist*tdist;
}
else if (x > maxr)
{
tdist = (x - maxr)*R_WEIGHT;
min_dist = tdist*tdist;
tdist = (x - minr)*R_WEIGHT;
max_dist = tdist*tdist;
}
else // within cell range so no contribution to min_dist
{
min_dist = 0;
if (x <= cr)
{
tdist = (x - maxr)*R_WEIGHT;
max_dist = tdist*tdist;
}
else
{
tdist = (x - minr)*R_WEIGHT;
max_dist = tdist*tdist;
}
}
x = palette[i].green;
if (x < ming)
{
tdist = (x - ming)*G_WEIGHT;
min_dist += tdist*tdist;
tdist = (x - maxg)*G_WEIGHT;
max_dist += tdist*tdist;
}
else if (x > maxg)
{
tdist = (x - maxg)*G_WEIGHT;
min_dist += tdist*tdist;
tdist = (x - ming)*G_WEIGHT;
max_dist += tdist*tdist;
}
else
{
if (x <= cg)
{
tdist = (x - maxg)*G_WEIGHT;
max_dist += tdist*tdist;
}
else
{
tdist = (x - ming)*G_WEIGHT;
max_dist += tdist*tdist;
}
}
x = palette[i].blue;
if (x < minb)
{
tdist = (x - minb)*B_WEIGHT;
min_dist += tdist*tdist;
tdist = (x - maxb)*B_WEIGHT;
max_dist += tdist*tdist;
}
else if (x > maxb)
{
tdist = (x - maxb)*B_WEIGHT;
min_dist += tdist*tdist;
tdist = (x - minb)*B_WEIGHT;
max_dist += tdist*tdist;
}
else
{
if (x <= cb)
{
tdist = (x - maxb)*B_WEIGHT;
max_dist += tdist*tdist;
}
else
{
tdist = (x - minb)*B_WEIGHT;
max_dist += tdist*tdist;
}
}
mindist[i] = min_dist; /* save away the results */
if (max_dist < minmaxdist)
minmaxdist = max_dist;
}
/* Now we know that no cell in the update box is more than minmaxdist
* away from some colormap entry. Therefore, only colors that are
* within minmaxdist of some part of the box need be considered.
*/
ncolors = 0;
for (i = 0; i < numcolors; i++)
{
if (mindist[i] <= minmaxdist)
color_list[ncolors++] = i;
}
return ncolors;
}
void find_best_colors (rgb_color palette[], int numcolors, int minr, int ming, int minb, uint8 colorlist[], uint8 bestcolors[])
{
int ir, ig, ib;
int i, icolor;
register float *bptr; // pointer into bestdist[] array
uint8 *cptr; // pointer into bestcolor[] array
float dist0, dist1; // initial distance values
register float dist2; // current distance in inner loop
float xx0, xx1; // distance increments
register float xx2;
float inc0, inc1, inc2; // initial values for increments
// This array holds the distance to the nearest-so-far color for each cell
float bestdist[BOX_R_ELEMS*BOX_G_ELEMS*BOX_B_ELEMS];
/* Initialize best-distance for each cell of the update box */
bptr = bestdist - 1;
for (i = BOX_R_ELEMS*BOX_G_ELEMS*BOX_B_ELEMS - 1; i >= 0; i--)
*(++bptr) = 0x7FFFFFFFL;
/* For each color selected by find_nearby_colors,
* compute its distance to the center of each cell in the box.
* If that's less than best-so-far, update best distance and color number.
*/
/* Nominal steps between cell centers ("x" in Thomas article) */
#define STEP_R ((1 << R_SHIFT)*R_WEIGHT)
#define STEP_G ((1 << G_SHIFT)*G_WEIGHT)
#define STEP_B ((1 << B_SHIFT)*B_WEIGHT)
for (i = 0; i < numcolors; i++)
{
icolor = colorlist[i];
/* Compute (square of) distance from minr/g/b to this color */
inc0 = (minr - palette[icolor].red)*R_WEIGHT;
dist0 = inc0*inc0;
inc1 = (ming - palette[icolor].green)*G_WEIGHT;
dist0 += inc1*inc1;
inc2 = (minb - palette[icolor].blue)*B_WEIGHT;
dist0 += inc2*inc2;
/* Form the initial difference increments */
inc0 = inc0*(2*STEP_R) + STEP_R*STEP_R;
inc1 = inc1*(2*STEP_G) + STEP_G*STEP_G;
inc2 = inc2*(2*STEP_B) + STEP_B*STEP_B;
/* Now loop over all cells in box, updating distance per Thomas method */
bptr = bestdist;
cptr = bestcolors;
xx0 = inc0;
for (ir = BOX_R_ELEMS - 1; ir >= 0; ir--)
{
dist1 = dist0;
xx1 = inc1;
for (ig = BOX_G_ELEMS - 1; ig >= 0; ig--)
{
dist2 = dist1;
xx2 = inc2;
for (ib = BOX_B_ELEMS - 1; ib >= 0; ib--)
{
if (dist2 < *bptr)
{
*bptr = dist2;
*cptr = icolor;
}
dist2 += xx2;
xx2 += 2*STEP_B*STEP_B;
bptr++;
cptr++;
}
dist1 += xx1;
xx1 += 2*STEP_G*STEP_G;
}
dist0 += xx0;
xx0 += 2*STEP_R*STEP_R;
}
}
}
void fill_lut (int16 *lut, rgb_color palette[], int max_colors, int r, int g, int b)
{
int minr, ming, minb; /* lower left corner of update box */
int ir, ig, ib;
register uint8 *cptr; /* pointer into bestcolor[] array */
/* This array lists the candidate colormap indexes. */
uint8 colorlist[256];
int numcolors; /* number of candidate colors */
/* This array holds the actually closest colormap index for each cell. */
uint8 bestcolor[BOX_R_ELEMS*BOX_G_ELEMS*BOX_B_ELEMS];
/* Convert cell coordinates to update box ID */
r >>= BOX_R_LOG;
g >>= BOX_G_LOG;
b >>= BOX_B_LOG;
/* Compute true coordinates of update box's origin corner.
* Actually we compute the coordinates of the center of the corner
* histogram cell, which are the lower bounds of the volume we care about.
*/
minr = (r << BOX_R_SHIFT) + ((1 << R_SHIFT) >> 1);
ming = (g << BOX_G_SHIFT) + ((1 << G_SHIFT) >> 1);
minb = (b << BOX_B_SHIFT) + ((1 << B_SHIFT) >> 1);
/* Determine which colormap entries are close enough to be candidates
* for the nearest entry to some cell in the update box.
*/
numcolors = find_nearby_colors (palette, max_colors, colorlist, minr, ming, minb);
/* Determine the actually nearest colors. */
find_best_colors (palette, numcolors, minr, ming, minb, colorlist, bestcolor);
/* Save the best color numbers (plus 1) in the main cache array */
r <<= BOX_R_LOG; /* convert ID back to base cell indexes */
g <<= BOX_G_LOG;
b <<= BOX_B_LOG;
cptr = bestcolor - 1;
for (ir = 0; ir < BOX_R_ELEMS; ir++)
for (ig = 0; ig < BOX_G_ELEMS; ig++)
for (ib = 0; ib < BOX_B_ELEMS; ib++)
ELEM (lut, (r + ir), (g + ig), (b + ib)) = *(++cptr);
}
status_t addon_make_config (BView **vw, BRect rect)
{
view = new QView (rect);
*vw = view;
gLut = new int16 [R_PREC*G_PREC*B_PREC];
for (int32 i = 0; i < R_PREC; i++)
for (int32 j = 0; j < G_PREC; j++)
for (int32 k = 0; k < B_PREC; k++)
ELEM (gLut, i, j, k) = -1; // We build the LUT on the fly
return B_OK;
}
status_t process (Layer *inLayer, Selection *inSelection,
Layer **outLayer, Selection **outSelection, int32 mode,
BRect * /* frame */, bool final, BPoint /* point */, uint32 /* buttons */)
{
int error = ADDON_OK;
BRect bounds = inLayer->Bounds();
// printf ("Bounds: ");
// bounds.PrintToStream();
// printf ("Frame: ");
// frame->PrintToStream();
if (*outLayer == NULL && mode== M_DRAW)
*outLayer = new Layer (*inLayer);
if (mode == M_SELECT)
{
if (inSelection)
*outSelection = new Selection (*inSelection);
else // No Selection to Quantize
return (0);
}
if (*outLayer)
(*outLayer)->Lock();
if (*outSelection)
(*outSelection)->Lock();
uint32 h = bounds.IntegerHeight() + 1;
uint32 w = bounds.IntegerWidth() + 1;
grey_pixel *mapbits = NULL;
uint32 mbpr = 0;
uint32 mdiff = 0;
if (inSelection)
{
mapbits = (grey_pixel *) inSelection->Bits() - 1;
mbpr = inSelection->BytesPerRow();
mdiff = mbpr - w;
}
if (final)
addon_start();
float delta = 100.0/h; // For the Status Bar.
switch (mode)
{
case M_DRAW:
{
bgra_pixel *sbits = (bgra_pixel *) inLayer->Bits() - 1;
bgra_pixel *dbits = (bgra_pixel *) (*outLayer)->Bits() - 1;
rgb_color *palette;
if (view->palette() == BACKGROUND)
palette = lowpalette();
else
palette = highpalette();
int numcolors = view->numColors();
if (!view->dither()) // Simple quantizer
{
for (uint32 y = 0; y < h; y++)
{
if (final)
{
addon_update_statusbar (delta);
if (addon_stop())
{
error = ADDON_ABORT;
break;
}
}
for (uint32 x = 0; x < w; x++)
{
bgra_pixel pixel = *(++sbits);
if (!inSelection || *(++mapbits))
{
uint8 r = RED (pixel);
uint8 g = GREEN (pixel);
uint8 b = BLUE (pixel);
// uint16 appr = ((r << 8) & 0xF700)|((g << 3) & 0x07E0)|((b >> 3) & 0x001F);
int rs = r >> R_SHIFT;
int gs = g >> G_SHIFT;
int bs = b >> B_SHIFT;
if (ELEM (gLut, rs, gs, bs) < 0) // Not filled in yet
{
fill_lut (gLut, palette, numcolors, r >> R_SHIFT, g >> G_SHIFT, b >> B_SHIFT);
}
*(++dbits) = rgb2bgra (palette[ELEM (gLut, rs, gs, bs)]);
}
else
*(++dbits) = *(++sbits);
}
mapbits += mdiff;
}
}
else // FS Dither
{
// Foley & Van Dam, pp 572.
// Own note: Probably the errors in the different color channels should be weighted
// according to visual sensibility. But this version is primarily meant to
// be quick.
uint32 width = bounds.IntegerWidth() + 1;
uint32 slpr = inLayer->BytesPerRow()/4;
bgra_pixel *src = sbits; //(bgra_pixel *) inLayer->Bits() + int (bounds.top)*slpr + int (bounds.left) - 1;
int32 sdif = slpr - width;
uint32 dbpr = (*outLayer)->BytesPerRow()/4;
bgra_pixel *dest = dbits; //(bgra_pixel *) (*outLayer)->Bits() + int (bounds.top)*dbpr + int (bounds.left) - 1;
int32 ddif = dbpr - width;
int *nera = new int[width];
int *nega = new int[width];
int *neba = new int[width];
int *cera = new int[width];
int *cega = new int[width];
int *ceba = new int[width];
bzero (nera, width*sizeof(int));
bzero (nega, width*sizeof(int));
bzero (neba, width*sizeof(int));
bzero (cera, width*sizeof(int));
bzero (cega, width*sizeof(int));
bzero (ceba, width*sizeof(int));
int r, g, b, er, eg, eb, per, peg, peb;
uint8 apix;
uint32 x, y;
rgb_color a;
for (y = uint32 (bounds.top); y < uint32 (bounds.bottom); y++)
{
// printf ("%ld", y); fflush (stdout);
if (final)
{
addon_update_statusbar (delta);
if (addon_stop())
{
error = ADDON_ABORT;
break;
}
}
x = 0;
// Special case: First pixel in a row
bgra_pixel s = *(++src);
r = clip8 (RED (s) + cera[0]);
g = clip8 (GREEN (s) + cega[0]);
b = clip8 (BLUE (s) + ceba[0]);
cera[0] = 0;
cega[0] = 0;
ceba[0] = 0;
// Find the nearest match in the palette and write it out
int rs = r >> R_SHIFT;
int gs = g >> G_SHIFT;
int bs = b >> B_SHIFT;
if (ELEM (gLut, rs, gs, bs) < 0) // Not filled in yet
fill_lut (gLut, palette, numcolors, rs, gs, bs);
apix = ELEM (gLut, rs, gs, bs);
// And the corresponding RGB color
a = palette[apix];
if (!inSelection || *(++mapbits))
*(++dest) = rgb2bgra (a);
else
*(++dest) = s;
// Calculate the error terms
er = r - a.red;
eg = g - a.green;
eb = b - a.blue;
per = 7*er/16;
peg = 7*eg/16;
peb = 7*eb/16;
// Put all the remaining error in the pixels down and down-right
// (since there is no pixel down-left...)
nera[x] += er/2;
nega[x] += eg/2;
neba[x] += eb/2;
nera[x + 1] += er/16;
nega[x + 1] += eg/16;
neba[x + 1] += eb/16;
for (x = 1; x < width - 1; x++)
{
// printf (","); fflush (stdout);
// Get one source pixel
s = *(++src);
// Get color components and add errors from previous pixel
r = clip8 (RED (s) + per + cera[x]);
g = clip8 (GREEN (s) + peg + cega[x]);
b = clip8 (BLUE (s) + peb + ceba[x]);
cera[x] = 0;
cega[x] = 0;
ceba[x] = 0;
// Find the nearest match in the palette and write it out
int rs = r >> R_SHIFT;
int gs = g >> G_SHIFT;
int bs = b >> B_SHIFT;
if (ELEM (gLut, rs, gs, bs) < 0) // Not filled in yet
fill_lut (gLut, palette, numcolors, rs, gs, bs);
apix = ELEM (gLut, rs, gs, bs);
// And the corresponding RGB color
a = palette[apix];
// printf ("%c.", 8); fflush (stdout);
if (!inSelection || *(++mapbits))
*(++dest) = rgb2bgra (a);
else
*(++dest) = s;
// printf ("%c:", 8); fflush (stdout);
// Calculate the error terms
er = r - a.red;
eg = g - a.green;
eb = b - a.blue;
per = 7*er/16;
peg = 7*eg/16;
peb = 7*eb/16;
nera[x - 1] += 3*er/16;
nega[x - 1] += 3*eg/16;
neba[x - 1] += 3*eb/16;
nera[x] += 5*er/16;
nega[x] += 5*eg/16;
neba[x] += 5*eb/16;
nera[x + 1] += er/16;
nega[x + 1] += eg/16;
neba[x + 1] += eb/16;
}
// Special case: Last pixel
// printf ("Writing last pixel - "); fflush (stdout);
s = *(++src);
// printf ("1"); fflush (stdout);
// Get color components and add errors from previous pixel
r = clip8 (RED (s) + per + cera[x]);
g = clip8 (GREEN (s) + peg + cega[x]);
b = clip8 (BLUE (s) + peb + ceba[x]);
cera[x] = 0;
cega[x] = 0;
ceba[x] = 0;
// Find the nearest match in the palette and write it out
rs = r >> R_SHIFT;
gs = g >> G_SHIFT;
bs = b >> B_SHIFT;
if (ELEM (gLut, rs, gs, bs) < 0) // Not filled in yet
fill_lut (gLut, palette, numcolors, rs, gs, bs);
apix = ELEM (gLut, rs, gs, bs);
// printf ("@"); fflush (stdout);
// And the corresponding RGB color
a = palette[apix];
// printf ("2"); fflush (stdout);
if (!inSelection || *(++mapbits))
*(++dest) = rgb2bgra (a);
else
*(++dest) = s;
// printf ("Still alive.\n");
// Calculate the error terms
er = r - a.red;
eg = g - a.green;
eb = b - a.blue;
// Put all the error in the pixels down and down-left
nera[x - 1] += er/2;
nega[x - 1] += eg/2;
neba[x - 1] += eb/2;
nera[x] += er/2;
nega[x] += eg/2;
neba[x] += eb/2;
// Switch the scratch data
int *tmp;
tmp = cera; cera = nera; nera = tmp;
tmp = cega; cega = nega; nega = tmp;
tmp = ceba; ceba = neba; neba = tmp;
dest += ddif;
src += sdif;
mapbits += mdiff;
}
// Special case: Last line
// All the error goes into the right pixel.
er = 0;
eg = 0;
eb = 0;
// printf ("Entering last line...\n");
for (x = 0; x < width - 1; x++)
{
// Get one source pixel
bgra_pixel s = *(++src);
// Get color components and add errors from previous pixel
r = clip8 (RED (s) + er + cera[x]);
g = clip8 (GREEN (s) + eg + cega[x]);
b = clip8 (BLUE (s) + eb + ceba[x]);
// Find the nearest match in the palette and write it out
int rs = r >> R_SHIFT;
int gs = g >> G_SHIFT;
int bs = b >> B_SHIFT;
if (ELEM (gLut, rs, gs, bs) < 0) // Not filled in yet
fill_lut (gLut, palette, numcolors, rs, gs, bs);
apix = ELEM (gLut, rs, gs, bs);
// And the corresponding RGB color
a = palette[apix];
if (!inSelection || *(++mapbits))
*(++dest) = rgb2bgra (a);
else
*(++dest) = s;
// Calculate the error terms
er = r - a.red;
eg = g - a.green;
eb = b - a.blue;
}
// Last but not least, the bottom right pixel.
bgra_pixel s = *(++src);
r = clip8 (RED (s) + er + cera[x]);
g = clip8 (GREEN (s) + eg + cega[x]);
b = clip8 (BLUE (s) + eb + ceba[x]);
int rs = r >> R_SHIFT;
int gs = g >> G_SHIFT;
int bs = b >> B_SHIFT;
if (ELEM (gLut, rs, gs, bs) < 0) // Not filled in yet
fill_lut (gLut, palette, numcolors, rs, gs, bs);
apix = ELEM (gLut, rs, gs, bs);
if (!inSelection || *(++mapbits))
*(++dest) = rgb2bgra (palette[apix]);
else
*(++dest) = s;
delete [] nera;
delete [] nega;
delete [] neba;
delete [] cera;
delete [] cega;
delete [] ceba;
}
delete [] palette;
break;
}
case M_SELECT:
{
break;
}
default:
fprintf (stderr, "Quantize: Unknown mode\n");
error = ADDON_UNKNOWN;
}
if (*outSelection)
(*outSelection)->Unlock();
if (*outLayer)
(*outLayer)->Unlock();
if (final)
addon_done();
return (error);
}
| 26.540441 | 128 | 0.586323 |
27529bcb836fad9ead65325abb59bf5376582755 | 5,373 | cpp | C++ | 55479c656d65636fdb050000/code/RobotAI.cpp | MechEmpire/Mechempire-meches | aa95b15f061f4179c9061595e73c7127587cc4df | [
"Apache-2.0"
] | 1 | 2020-07-29T05:50:16.000Z | 2020-07-29T05:50:16.000Z | 55479ffa6d65636fdb0d0000/code/RobotAI.cpp | MechEmpire/Mechempire-meches | aa95b15f061f4179c9061595e73c7127587cc4df | [
"Apache-2.0"
] | null | null | null | 55479ffa6d65636fdb0d0000/code/RobotAI.cpp | MechEmpire/Mechempire-meches | aa95b15f061f4179c9061595e73c7127587cc4df | [
"Apache-2.0"
] | null | null | null | #include "RobotAI.h"
#include<math.h>
#include<iostream>
using namespace std;
RobotAI::RobotAI()
{
}
RobotAI::~RobotAI()
{
}
//-----------------------------------------------------
//1.必须完成的战斗核心
//-----------------------------------------------------
struct node
{
double x,y,dis;
};
double max_num(double a,double b)
{
return a>b?a:b;
}
void RobotAI::Update(RobotAI_Order& order,const RobotAI_BattlefieldInformation& info,int myID)
{
int enery;
if(myID==1)
enery=0;
else
enery=1;
int x=info.robotInformation[myID].circle.x;
int y=info.robotInformation[myID].circle.y;
int x1=info.robotInformation[enery].circle.x;
int y1=info.robotInformation[enery].circle.y;
int x2=300;
int y2=250;
int x3=1066;
int y3=430;
int d=120;
int dis;
int ddx;
int ddy;
if(myID==1)
{
dis=(int)sqrt((x3-x1)*(x3-x1)+(y3-y1)*(y3-y1));
ddx=(120*(x3-x1))/dis+x3;
ddy=(120*(y3-y1))/dis+y3;
}
else
{
dis=(int)sqrt((x2-x1)*(x2-x1)+(y2-y1)*(y2-y1));
ddx=x2-dis*(x1-x2)/120;
ddy=y2-dis*(y1-y2)/120;
}
int dx=(x1-x);
int dy=(y1-y);
double k=Random0_1();
double kk,kk1;
if(myID==1)
{
kk=(y1-430)/max_num(0.01,(x1-1066));
kk1=(430-y)/(max_num(0.01,(1066-x)));
}
else
{
kk=(y1-250)/max_num(0.01,(x1-300));
kk1=(250-y)/(max_num(0.01,(300-x)));
}
//1234 左右上下
if(k<0.5)
{
if(ddx>x)
order.run=2;
else
order.run=1;
}
else
{
if(ddy>y)
order.run=4;
else
order.run=3;
}
if(myID==1)
{
if(info.robotInformation[myID].circle.x>1066+d)
order.run=1;
if(info.robotInformation[myID].circle.x<1066-d)
order.run=2;
if(info.robotInformation[myID].circle.y>430+d)
order.run=3;
if(info.robotInformation[myID].circle.y<430-d)
order.run=4;
}
if(myID==0)
{
if(info.robotInformation[myID].circle.x>300+d)
order.run=1;
if(info.robotInformation[myID].circle.x<300-d)
order.run=2;
if(info.robotInformation[myID].circle.y>250+d)
order.run=3;
if(info.robotInformation[myID].circle.y<250-d)
order.run=4;
}
double kiss=Random0_1();
if(info.robotInformation[myID].remainingAmmo==0)
{
for(int i=0;i<2;i++)
{
if(info.arsenal[i].respawning_time==0)
{
if(kiss<0.5)
{
if(info.arsenal[i].circle.x+30>info.robotInformation[myID].circle.x)
{
order.run=2;
break;
}
if(info.arsenal[i].circle.x+30<info.robotInformation[myID].circle.x)
{
order.run=1;
break;
}
}
else
{
if(info.arsenal[i].circle.y+30>info.robotInformation[myID].circle.y)
{
order.run=4;
break;
}
if(info.arsenal[i].circle.y+30<info.robotInformation[myID].circle.y)
{
order.run=3;
break;
}
}
}
}
}
double ck;
Beam shoot;
double ck1=info.robotInformation[myID].weaponRotation;
shoot.x=x;
shoot.y=y;
shoot.rotation=ck1;
Circle kis;
if(myID==1)
{
kis.x=1066;
kis.y=430;
kis.r=100;
if(HitTestBeamCircle(shoot,kis))
order.wturn=1;
}
else
{
kis.x=300;
kis.y=250;
kis.r=80;
if(HitTestBeamCircle(shoot,kis))
order.wturn=1;
}
if(myID==0)
order.fire=2;
else
order.fire=1;
}
void RobotAI::ChooseArmor(weapontypename& weapon,enginetypename& engine,bool a)
{
//挑选装备函数
//功能:在战斗开始时为你的机甲选择合适的武器炮塔和引擎载具
//参数:weapon ... 代表你选择的武器,在函数体中给它赋值
// engine ... 代表你选择的引擎,在函数体中给它赋值
//tip: 括号里的参数是枚举类型 weapontypename 或 enginetypename
// 开发文档中有详细说明,你也可以在RobotAIstruct.h中直接找到它们的代码
//tip: 最后一个bool是没用的。。那是一个退化的器官
weapon = WT_MissileLauncher;
engine = ET_Spider;
}
//-----------------------------------------------------
//2.个性信息
//-----------------------------------------------------
string RobotAI::GetName()
{
//返回你的机甲的名字
return "bird_raincoatV0.19";
}
string RobotAI::GetAuthor()
{
//返回机甲制作人或团队的名字
return "qscqesze";
}
//返回一个(-255,255)之间的机甲武器炮塔的颜色偏移值(红、绿、蓝)
//你可以在flash客户端的参数预览中预览颜色搭配的效果
int RobotAI::GetWeaponRed()
{
//返回一个-255-255之间的整数,代表武器红色的偏移值
return 255;
}
int RobotAI::GetWeaponGreen()
{
//返回一个-255-255之间的整数,代表武器绿色的偏移值
return -69;
}
int RobotAI::GetWeaponBlue()
{
//返回一个-255-255之间的整数,代表武器蓝色的偏移值
return 31;
}
//返回一个(-255,255)之间的机甲引擎载具的颜色偏移值(红、绿、蓝)
//你可以在flash客户端的参数预览中预览颜色搭配的效果
int RobotAI::GetEngineRed()
{
//返回一个-255-255之间的数,代表载具红色的偏移值
return -255;
}
int RobotAI::GetEngineGreen()
{
//返回一个-255-255之间的整数,代表载具绿色的偏移值
return -106;
}
int RobotAI::GetEngineBlue()
{
//返回一个-255-255之间的整数,代表载具蓝色的偏移值
return -4;
}
//-----------------------------------------------------
//3.用不用随你的触发函数
//-----------------------------------------------------
void RobotAI::onBattleStart(const RobotAI_BattlefieldInformation& info,int myID)
{
//一场战斗开始时被调用,可能可以用来初始化
//参数:info ... 战场信息
// myID ... 自己机甲在info中robot数组对应的下标
}
void RobotAI::onBattleEnd(const RobotAI_BattlefieldInformation& info,int myID)
{
//一场战斗结束时被调用,可能可以用来析构你动态分配的内存空间(如果你用了的话)
//参数:info ... 战场信息
// myID ... 自己机甲在info中robot数组对应的下标
}
void RobotAI::onSomeoneFire(int fireID)
{
//有机甲开火时被调用
//参数:fireID ... 开火的机甲下标
}
void RobotAI::onHit(int launcherID,bullettypename btn)
{
//被子弹击中时被调用
//参数:btn ... 击中你的子弹种类(枚举类型)
}
//TODO:这里可以实现你自己的函数 | 17.166134 | 95 | 0.577703 |
27535f079eb414837f11b815cca167a6b7fe7654 | 10,997 | cpp | C++ | webkit/WebCore/dom/Text.cpp | s1rcheese/nintendo-3ds-internetbrowser-sourcecode | 3dd05f035e0a5fc9723300623e9b9b359be64e11 | [
"Unlicense"
] | 15 | 2016-01-05T12:43:41.000Z | 2022-03-15T10:34:47.000Z | webkit/WebCore/dom/Text.cpp | s1rcheese/nintendo-3ds-internetbrowser-sourcecode | 3dd05f035e0a5fc9723300623e9b9b359be64e11 | [
"Unlicense"
] | null | null | null | webkit/WebCore/dom/Text.cpp | s1rcheese/nintendo-3ds-internetbrowser-sourcecode | 3dd05f035e0a5fc9723300623e9b9b359be64e11 | [
"Unlicense"
] | 2 | 2020-11-30T18:36:01.000Z | 2021-02-05T23:20:24.000Z | /*
* Copyright (C) 1999 Lars Knoll (knoll@kde.org)
* (C) 1999 Antti Koivisto (koivisto@kde.org)
* Copyright (C) 2003, 2004, 2005, 2006, 2007, 2008, 2009 Apple Inc. All rights reserved.
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Library General Public
* License as published by the Free Software Foundation; either
* version 2 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Library General Public License for more details.
*
* You should have received a copy of the GNU Library General Public License
* along with this library; see the file COPYING.LIB. If not, write to
* the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
* Boston, MA 02110-1301, USA.
*/
#include "config.h"
#include "Text.h"
#include "CString.h"
#include "ExceptionCode.h"
#include "RenderText.h"
#include "TextBreakIterator.h"
#if ENABLE(SVG)
#include "RenderSVGInlineText.h"
#include "SVGNames.h"
#endif
#if ENABLE(WML)
#include "WMLDocument.h"
#include "WMLVariables.h"
#endif
using namespace std;
namespace WebCore {
Text::Text(Document* document, const String& data)
: CharacterData(document, data, CreateText)
{
}
PassRefPtr<Text> Text::create(Document* document, const String& data)
{
return adoptRef(new Text(document, data));
}
PassRefPtr<Text> Text::splitText(unsigned offset, ExceptionCode& ec)
{
ec = 0;
// INDEX_SIZE_ERR: Raised if the specified offset is negative or greater than
// the number of 16-bit units in data.
if (offset > length()) {
ec = INDEX_SIZE_ERR;
return 0;
}
RefPtr<StringImpl> oldStr = dataImpl();
RefPtr<Text> newText = virtualCreate(oldStr->substring(offset));
setDataImpl(oldStr->substring(0, offset));
dispatchModifiedEvent(oldStr.get());
if (parentNode())
parentNode()->insertBefore(newText.get(), nextSibling(), ec);
if (ec)
return 0;
if (parentNode())
document()->textNodeSplit(this);
if (renderer())
toRenderText(renderer())->setText(dataImpl());
return newText.release();
}
static const Text* earliestLogicallyAdjacentTextNode(const Text* t)
{
const Node* n = t;
while ((n = n->previousSibling())) {
Node::NodeType type = n->nodeType();
if (type == Node::TEXT_NODE || type == Node::CDATA_SECTION_NODE) {
t = static_cast<const Text*>(n);
continue;
}
// We would need to visit EntityReference child text nodes if they existed
ASSERT(type != Node::ENTITY_REFERENCE_NODE || !n->hasChildNodes());
break;
}
return t;
}
static const Text* latestLogicallyAdjacentTextNode(const Text* t)
{
const Node* n = t;
while ((n = n->nextSibling())) {
Node::NodeType type = n->nodeType();
if (type == Node::TEXT_NODE || type == Node::CDATA_SECTION_NODE) {
t = static_cast<const Text*>(n);
continue;
}
// We would need to visit EntityReference child text nodes if they existed
ASSERT(type != Node::ENTITY_REFERENCE_NODE || !n->hasChildNodes());
break;
}
return t;
}
String Text::wholeText() const
{
const Text* startText = earliestLogicallyAdjacentTextNode(this);
const Text* endText = latestLogicallyAdjacentTextNode(this);
Node* onePastEndText = endText->nextSibling();
unsigned resultLength = 0;
for (const Node* n = startText; n != onePastEndText; n = n->nextSibling()) {
if (!n->isTextNode())
continue;
const Text* t = static_cast<const Text*>(n);
const String& data = t->data();
#if 1
// added at webkit.org trunk r68705
if (std::numeric_limits<unsigned>::max() - data.length() < resultLength)
CRASH();
#endif
resultLength += data.length();
}
UChar* resultData;
String result = String::createUninitialized(resultLength, resultData);
UChar* p = resultData;
for (const Node* n = startText; n != onePastEndText; n = n->nextSibling()) {
if (!n->isTextNode())
continue;
const Text* t = static_cast<const Text*>(n);
const String& data = t->data();
unsigned dataLength = data.length();
memcpy(p, data.characters(), dataLength * sizeof(UChar));
p += dataLength;
}
ASSERT(p == resultData + resultLength);
return result;
}
PassRefPtr<Text> Text::replaceWholeText(const String& newText, ExceptionCode&)
{
// Remove all adjacent text nodes, and replace the contents of this one.
// Protect startText and endText against mutation event handlers removing the last ref
RefPtr<Text> startText = const_cast<Text*>(earliestLogicallyAdjacentTextNode(this));
RefPtr<Text> endText = const_cast<Text*>(latestLogicallyAdjacentTextNode(this));
RefPtr<Text> protectedThis(this); // Mutation event handlers could cause our last ref to go away
Node* parent = parentNode(); // Protect against mutation handlers moving this node during traversal
ExceptionCode ignored = 0;
for (RefPtr<Node> n = startText; n && n != this && n->isTextNode() && n->parentNode() == parent;) {
RefPtr<Node> nodeToRemove(n.release());
n = nodeToRemove->nextSibling();
parent->removeChild(nodeToRemove.get(), ignored);
}
if (this != endText) {
Node* onePastEndText = endText->nextSibling();
for (RefPtr<Node> n = nextSibling(); n && n != onePastEndText && n->isTextNode() && n->parentNode() == parent;) {
RefPtr<Node> nodeToRemove(n.release());
n = nodeToRemove->nextSibling();
parent->removeChild(nodeToRemove.get(), ignored);
}
}
if (newText.isEmpty()) {
if (parent && parentNode() == parent)
parent->removeChild(this, ignored);
return 0;
}
setData(newText, ignored);
return protectedThis.release();
}
String Text::nodeName() const
{
return textAtom.string();
}
Node::NodeType Text::nodeType() const
{
return TEXT_NODE;
}
PassRefPtr<Node> Text::cloneNode(bool /*deep*/)
{
return create(document(), data());
}
bool Text::rendererIsNeeded(RenderStyle *style)
{
if (!CharacterData::rendererIsNeeded(style))
return false;
bool onlyWS = containsOnlyWhitespace();
if (!onlyWS)
return true;
RenderObject *par = parentNode()->renderer();
if (par->isTable() || par->isTableRow() || par->isTableSection() || par->isTableCol() || par->isFrameSet())
return false;
if (style->preserveNewline()) // pre/pre-wrap/pre-line always make renderers.
return true;
RenderObject *prev = previousRenderer();
if (prev && prev->isBR()) // <span><br/> <br/></span>
return false;
if (par->isRenderInline()) {
// <span><div/> <div/></span>
if (prev && !prev->isInline())
return false;
} else {
if (par->isRenderBlock() && !par->childrenInline() && (!prev || !prev->isInline()))
return false;
RenderObject *first = par->firstChild();
while (first && first->isFloatingOrPositioned())
first = first->nextSibling();
RenderObject *next = nextRenderer();
if (!first || next == first)
// Whitespace at the start of a block just goes away. Don't even
// make a render object for this text.
return false;
}
return true;
}
RenderObject* Text::createRenderer(RenderArena* arena, RenderStyle*)
{
#if ENABLE(SVG)
if (parentNode()->isSVGElement()
#if ENABLE(SVG_FOREIGN_OBJECT)
&& !parentNode()->hasTagName(SVGNames::foreignObjectTag)
#endif
)
return new (arena) RenderSVGInlineText(this, dataImpl());
#endif
return new (arena) RenderText(this, dataImpl());
}
void Text::attach()
{
#if ENABLE(WML)
if (document()->isWMLDocument() && !containsOnlyWhitespace()) {
String text = data();
ASSERT(!text.isEmpty());
text = substituteVariableReferences(text, document());
ExceptionCode code = 0;
setData(text, code);
ASSERT(!code);
}
#endif
createRendererIfNeeded();
CharacterData::attach();
}
void Text::recalcStyle(StyleChange change)
{
if (change != NoChange && parentNode()) {
if (renderer())
renderer()->setStyle(parentNode()->renderer()->style());
}
if (needsStyleRecalc()) {
if (renderer()) {
if (renderer()->isText())
toRenderText(renderer())->setText(dataImpl());
} else {
if (attached())
detach();
attach();
}
}
setNeedsStyleRecalc(NoStyleChange);
}
bool Text::childTypeAllowed(NodeType)
{
return false;
}
PassRefPtr<Text> Text::virtualCreate(const String& data)
{
return create(document(), data);
}
PassRefPtr<Text> Text::createWithLengthLimit(Document* document, const String& data, unsigned& charsLeft, unsigned maxChars)
{
unsigned dataLength = data.length();
if (charsLeft == dataLength && charsLeft <= maxChars) {
charsLeft = 0;
return create(document, data);
}
unsigned start = dataLength - charsLeft;
unsigned end = start + min(charsLeft, maxChars);
// Check we are not on an unbreakable boundary.
// Some text break iterator implementations work best if the passed buffer is as small as possible,
// see <https://bugs.webkit.org/show_bug.cgi?id=29092>.
// We need at least two characters look-ahead to account for UTF-16 surrogates.
if (end < dataLength) {
TextBreakIterator* it = characterBreakIterator(data.characters() + start, (end + 2 > dataLength) ? dataLength - start : end - start + 2);
if (!isTextBreak(it, end - start))
end = textBreakPreceding(it, end - start) + start;
}
// If we have maxChars of unbreakable characters the above could lead to
// an infinite loop.
// FIXME: It would be better to just have the old value of end before calling
// textBreakPreceding rather than this, because this exceeds the length limit.
if (end <= start)
end = dataLength;
charsLeft = dataLength - end;
return create(document, data.substring(start, end - start));
}
#ifndef NDEBUG
void Text::formatForDebugger(char *buffer, unsigned length) const
{
String result;
String s;
s = nodeName();
if (s.length() > 0) {
result += s;
}
s = data();
if (s.length() > 0) {
if (result.length() > 0)
result += "; ";
result += "value=";
result += s;
}
strncpy(buffer, result.utf8().data(), length - 1);
}
#endif
} // namespace WebCore
| 29.964578 | 145 | 0.626807 |