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 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
2120ca9059d1a019933d30148bad6f127d2943e5 | 8,945 | cpp | C++ | ai/vs/Source/ai.cpp | iterami/SC-AI.cpp | 5778a0c5bf01b9eccf7573b95027034509ab5c66 | [
"CC0-1.0"
] | 1 | 2017-04-28T23:21:51.000Z | 2017-04-28T23:21:51.000Z | ai/vs/Source/ai.cpp | iterami/SC-AI.cpp | 5778a0c5bf01b9eccf7573b95027034509ab5c66 | [
"CC0-1.0"
] | null | null | null | ai/vs/Source/ai.cpp | iterami/SC-AI.cpp | 5778a0c5bf01b9eccf7573b95027034509ab5c66 | [
"CC0-1.0"
] | null | null | null | #include <iostream>
#include <stdlib.h>
#include <time.h>
#include "ai.h"
using namespace BWAPI;
using namespace Filter;
// Global variables.
bool supplyNeeded;
int infantryBuildingCheckTimer;
int infantryBuildingCost;
int infantryBuildingLimit;
int infantryCost;
int resourceDepotBuildingCheckTimer;
int resourceDepotBuildingCost;
int resourceDepotBuildingLimit;
int savingMinerals;
int supplyCheckTimer;
int workerLimit;
Race playerRace;
static int infantryBuildingChecked;
static int resourceDepotBuildingChecked;
static int supplyChecked;
UnitType infantryBuilding;
UnitType infantryType;
UnitType resourceDepotBuilding;
UnitType supplyProviderType;
UnitType workerType;
void ai::onEnd(bool isWinner){
Broodwar->sendText("ggwp");
}
void ai::onFrame(){
int frameCount = Broodwar->getFrameCount();
if(!Broodwar->self()
|| frameCount % Broodwar->getLatencyFrames() != 0
|| Broodwar->isPaused()
|| Broodwar->isReplay()){
return;
}
int infantryBuildingCount = Broodwar->self()->allUnitCount(infantryBuilding);
int minerals = Broodwar->self()->minerals();
int resourceDepotBuildingCount = Broodwar->self()->allUnitCount(resourceDepotBuilding);
int supplyTotal = Broodwar->self()->supplyTotal();
int supplyUsed = Broodwar->self()->supplyUsed();
int workerCount = Broodwar->self()->allUnitCount(workerType);
int supplyCutoff = (int)(supplyUsed / 10);
if(supplyCutoff < 4){
supplyCutoff = 4;
}
if(supplyTotal < 400
&& supplyTotal - supplyUsed <= supplyCutoff
&& Broodwar->self()->incompleteUnitCount(supplyProviderType) == 0){
savingMinerals = 100;
supplyNeeded = true;
}else{
savingMinerals = 0;
supplyNeeded = false;
}
if(minerals >= infantryBuildingCost
&& infantryBuildingCount < infantryBuildingLimit){
savingMinerals += infantryBuildingCost;
}
if(minerals >= resourceDepotBuildingCost
&& resourceDepotBuildingCount < resourceDepotBuildingLimit){
savingMinerals += resourceDepotBuildingCost;
}
for(auto &unit : Broodwar->self()->getUnits()){
if(!unit->exists()
|| !unit->isCompleted()
|| unit->isConstructing()
|| unit->isLoaded()
|| unit->isLockedDown()
|| unit->isMaelstrommed()
|| !unit->isPowered()
|| unit->isStasised()
|| unit->isStuck()){
continue;
}
// Setup unit information variables.
bool unitIsIdle = unit->isIdle();
UnitType unitType = unit->getType();
// Handle workers.
if(unitType.isWorker()){
// Handle insufficient supply by building Pylon or building Supply Depot.
if(playerRace != Races::Zerg
&& supplyNeeded
&& minerals >= savingMinerals
&& supplyChecked + supplyCheckTimer < frameCount){
supplyChecked = frameCount;
Unit supplyBuilder = unit->getClosestUnit(GetType == supplyProviderType.whatBuilds().first
&& (IsIdle || IsGatheringMinerals)
&& IsOwned);
buildBuilding(
supplyBuilder,
supplyProviderType
);
// Build Command Centers, Hatcheries, and Nexuses.
}else if(resourceDepotBuildingCount < resourceDepotBuildingLimit
&& minerals >= resourceDepotBuildingCost
&& resourceDepotBuildingChecked + resourceDepotBuildingCheckTimer < frameCount){
resourceDepotBuildingChecked = frameCount;
buildBuilding(
unit,
resourceDepotBuilding
);
// Build Barracks/Gateway/Spawning Pool.
}else if(infantryBuildingCount < infantryBuildingLimit
&& minerals >= infantryBuildingCost
&& infantryBuildingChecked + infantryBuildingCheckTimer < frameCount){
infantryBuildingChecked = frameCount;
buildBuilding(
unit,
infantryBuilding
);
}else if(unitIsIdle){
// Return resources.
if(unit->isCarryingMinerals()
|| unit->isCarryingGas()){
unit->returnCargo();
// Gather resources.
}else{
unit->gather(unit->getClosestUnit(IsMineralField || IsRefinery));
}
}
}else if(unitIsIdle){
// Handle Command Centers, Hatcheries, and Nexuses.
if(unitType.isResourceDepot()){
if(playerRace == Races::Zerg
&& supplyNeeded
&& playerRace == Races::Zerg
&& minerals >= savingMinerals
&& supplyChecked + supplyCheckTimer < frameCount){
supplyChecked = frameCount;
// Train Overlords.
unit->train(supplyProviderType);
}else if(workerCount < workerLimit
&& minerals >= savingMinerals + 50){
// Train workers.
unit->train(workerType);
}else if(playerRace == Races::Zerg
&& minerals >= savingMinerals + infantryCost){
// Train Zerglings.
unit->train(infantryType);
}
// Handle Barracks and Gateways.
}else if(playerRace != Races::Zerg
&& unit->canTrain(infantryType)){
if(minerals >= savingMinerals + infantryCost){
// Train Marines and Zealots.
unit->train(infantryType);
}
// Everything else should attack-move scout.
}else{
Position position = unit->getPosition();
position.x += rand() % 501 - 250;
position.y += rand() % 501 - 250;
if(!unit->attack(position)){
unit->move(position);
}
}
}
}
}
void ai::onNukeDetect(BWAPI::Position target){
}
void ai::onPlayerLeft(BWAPI::Player player){
}
void ai::onReceiveText(BWAPI::Player player, std::string text){
}
void ai::onSaveGame(std::string gameName){
}
void ai::onSendText(std::string text){
Broodwar->sendText("%s", text.c_str());
}
void ai::onStart(){
Broodwar->setCommandOptimizationLevel(1);
srand(time(NULL));
// Setup global variables.
infantryBuildingChecked = 0;
infantryBuildingCheckTimer = 1900;
playerRace = Broodwar->self()->getRace();
resourceDepotBuildingChecked = 0;
resourceDepotBuildingCheckTimer = 1900;
savingMinerals = 0;
supplyChecked = 0;
supplyCheckTimer = 500;
supplyNeeded = false;
supplyProviderType = playerRace.getSupplyProvider();
workerLimit = 25;
workerType = playerRace.getWorker();
// Handle race-specific stuff.
if(playerRace == Races::Zerg){
infantryBuilding = UnitTypes::Zerg_Spawning_Pool;
infantryBuildingCost = 200;
infantryBuildingLimit = 1;
infantryCost = 50;
infantryType = UnitTypes::Zerg_Zergling;
resourceDepotBuilding = UnitTypes::Zerg_Hatchery;
resourceDepotBuildingCost = 300;
resourceDepotBuildingLimit = 5;
}else if(playerRace == Races::Terran){
infantryBuilding = UnitTypes::Terran_Barracks;
infantryBuildingCost = 150;
infantryBuildingLimit = 5;
infantryCost = 50;
infantryType = UnitTypes::Terran_Marine;
resourceDepotBuilding = UnitTypes::Terran_Command_Center;
resourceDepotBuildingCost = 400;
resourceDepotBuildingLimit = 1;
}else{
infantryBuilding = UnitTypes::Protoss_Gateway;
infantryBuildingCost = 200;
infantryBuildingLimit = 5;
infantryCost = 100;
infantryType = UnitTypes::Protoss_Zealot;
resourceDepotBuilding = UnitTypes::Protoss_Nexus;
resourceDepotBuildingCost = 400;
resourceDepotBuildingLimit = 1;
}
Broodwar->sendText("glhf");
}
void ai::onUnitComplete(BWAPI::Unit unit){
}
void ai::onUnitCreate(BWAPI::Unit unit){
}
void ai::onUnitDestroy(BWAPI::Unit unit){
}
void ai::onUnitDiscover(BWAPI::Unit unit){
}
void ai::onUnitEvade(BWAPI::Unit unit){
}
void ai::onUnitHide(BWAPI::Unit unit){
}
void ai::onUnitMorph(BWAPI::Unit unit){
}
void ai::onUnitRenegade(BWAPI::Unit unit){
}
void ai::onUnitShow(BWAPI::Unit unit){
}
bool buildBuilding(Unit builder, UnitType building){
TilePosition targetBuildLocation = Broodwar->getBuildLocation(
builing,
builder->getTilePosition()
);
if(targetBuildLocation){
return builder->build(
building,
targetBuildLocation
);
}
return false;
}
| 29.521452 | 106 | 0.601453 |
21226db6b728ae585642f38bf1fefebb733d5f6f | 1,109 | cpp | C++ | Source/FactoryGame/FGTrainStationIdentifier.cpp | iam-Legend/Project-Assembly | 1ff3587704232d5e330515bc0d2aceb64ff09a7f | [
"MIT"
] | null | null | null | Source/FactoryGame/FGTrainStationIdentifier.cpp | iam-Legend/Project-Assembly | 1ff3587704232d5e330515bc0d2aceb64ff09a7f | [
"MIT"
] | null | null | null | Source/FactoryGame/FGTrainStationIdentifier.cpp | iam-Legend/Project-Assembly | 1ff3587704232d5e330515bc0d2aceb64ff09a7f | [
"MIT"
] | null | null | null | // This file has been automatically generated by the Unreal Header Implementation tool
#include "FGTrainStationIdentifier.h"
AFGTrainStationIdentifier::AFGTrainStationIdentifier(){ }
void AFGTrainStationIdentifier::GetLifetimeReplicatedProps( TArray< FLifetimeProperty >& OutLifetimeProps) const{ }
void AFGTrainStationIdentifier::PreSaveGame_Implementation( int32 saveVersion, int32 gameVersion){ }
void AFGTrainStationIdentifier::PostSaveGame_Implementation( int32 saveVersion, int32 gameVersion){ }
void AFGTrainStationIdentifier::PreLoadGame_Implementation( int32 saveVersion, int32 gameVersion){ }
void AFGTrainStationIdentifier::PostLoadGame_Implementation( int32 saveVersion, int32 gameVersion){ }
void AFGTrainStationIdentifier::GatherDependencies_Implementation( TArray< UObject* >& out_dependentObjects){ }
bool AFGTrainStationIdentifier::NeedTransform_Implementation(){ return bool(); }
bool AFGTrainStationIdentifier::ShouldSave_Implementation() const{ return bool(); }
void AFGTrainStationIdentifier::SetStationName( const FText& text){ }
void AFGTrainStationIdentifier::OnRep_StationName(){ }
| 69.3125 | 115 | 0.844905 |
2124cf8ff359f5a282dceaf7782c4d55b2d40165 | 16,693 | cpp | C++ | Source/Samples/65_PhysicsTest/ConvexCast.cpp | extobias/Urho3D | 7d08ccac1ff9e9e28076ea879530c6b23974ba42 | [
"MIT"
] | null | null | null | Source/Samples/65_PhysicsTest/ConvexCast.cpp | extobias/Urho3D | 7d08ccac1ff9e9e28076ea879530c6b23974ba42 | [
"MIT"
] | null | null | null | Source/Samples/65_PhysicsTest/ConvexCast.cpp | extobias/Urho3D | 7d08ccac1ff9e9e28076ea879530c6b23974ba42 | [
"MIT"
] | null | null | null | #include "ConvexCast.h"
#include <Urho3D/Core/Profiler.h>
#include <Urho3D/IO/Log.h>
#include <Urho3D/Scene/Node.h>
#include <Urho3D/Scene/Scene.h>
#include <Urho3D/Graphics/StaticModel.h>
#include <Urho3D/Graphics/Model.h>
#include <Urho3D/Graphics/DebugRenderer.h>
#include <Urho3D/Resource/ResourceCache.h>
#include <Urho3D/Physics/RigidBody.h>
#include <Urho3D/Physics/CollisionShape.h>
#include <Urho3D/Physics/PhysicsWorld.h>
#include <Urho3D/Physics/PhysicsUtils.h>
#include <Urho3D/Physics/PhysicsEvents.h>
#include <Urho3D/Math/Ray.h>
#include <Urho3D/Editor/EditorModelDebug.h>
#include <Bullet/BulletDynamics/Dynamics/btRigidBody.h>
#include <Bullet/BulletCollision/CollisionShapes/btCompoundShape.h>
#include <BulletDynamics/Dynamics/btDiscreteDynamicsWorld.h>
#include <Bullet/BulletCollision/CollisionDispatch/btCollisionWorld.h>
static const btVector3 WHITE(1.0f, 1.0f, 1.0f);
static const btVector3 GREEN(0.0f, 1.0f, 0.0f);
struct AllConvexResultCallback : public btCollisionWorld::ConvexResultCallback
{
AllConvexResultCallback(const btVector3& convexFromWorld, const btVector3& convexToWorld)
:m_convexFromWorld(convexFromWorld),
m_convexToWorld(convexToWorld),
m_hitCollisionObject(0)
{
// URHO3D_LOGERRORF("AllConvexResultCallback ctor <%i>", m_hitPointWorld.size());
}
btVector3 m_convexFromWorld;//used to calculate hitPointWorld from hitFraction
btVector3 m_convexToWorld;
// btVector3 m_hitNormalWorld;
// btVector3 m_hitPointWorld;
const btCollisionObject* m_hitCollisionObject;
btAlignedObjectArray<const btCollisionObject*> m_collisionObjects;
btAlignedObjectArray<btVector3> m_hitNormalWorld;
btAlignedObjectArray<btVector3> m_hitPointWorld;
btAlignedObjectArray<btVector3> m_hitPointLocal;
btAlignedObjectArray<btScalar> m_hitFractions;
btAlignedObjectArray<int> m_hitShapePart;
btAlignedObjectArray<int> m_hitTriangleIndex;
virtual btScalar addSingleResult(btCollisionWorld::LocalConvexResult& convexResult, bool normalInWorldSpace)
{
//caller already does the filter on the m_closestHitFraction
// Assert(convexResult.m_hitFraction <= m_closestHitFraction);
//m_closestHitFraction = convexResult.m_hitFraction;
//m_hitCollisionObject = convexResult.m_hitCollisionObject;
//if (normalInWorldSpace)
//{
// m_hitNormalWorld = convexResult.m_hitNormalLocal;
//}
//else
//{
// ///need to transform normal into worldspace
// m_hitNormalWorld = m_hitCollisionObject->getWorldTransform().getBasis()*convexResult.m_hitNormalLocal;
//}
//m_hitPointWorld = convexResult.m_hitPointLocal;
//return convexResult.m_hitFraction;
// return m_closestHitFraction;
// URHO3D_LOGERRORF("addSingleResult fraction <%f>", convexResult.m_hitFraction);
m_closestHitFraction = convexResult.m_hitFraction;
m_hitCollisionObject = convexResult.m_hitCollisionObject;
m_collisionObjects.push_back(convexResult.m_hitCollisionObject);
btVector3 hitNormalWorld;
if (normalInWorldSpace)
{
hitNormalWorld = convexResult.m_hitNormalLocal;
}
else
{
///need to transform normal into worldspace
hitNormalWorld = m_hitCollisionObject->getWorldTransform().getBasis() * convexResult.m_hitNormalLocal;
}
m_hitNormalWorld.push_back(hitNormalWorld);
btVector3 hitPointWorld;
hitPointWorld.setInterpolate3(m_convexFromWorld, m_convexToWorld, convexResult.m_hitFraction);
m_hitPointWorld.push_back(hitPointWorld);
m_hitFractions.push_back(convexResult.m_hitFraction);
m_hitPointLocal.push_back(convexResult.m_hitPointLocal);
if (convexResult.m_localShapeInfo)
{
m_hitShapePart.push_back(convexResult.m_localShapeInfo->m_shapePart);
m_hitTriangleIndex.push_back(convexResult.m_localShapeInfo->m_triangleIndex);
}
else
{
m_hitShapePart.push_back(-1);
m_hitTriangleIndex.push_back(-1);
}
return convexResult.m_hitFraction;
}
};
ConvexCast::ConvexCast(Context* context)
: Component(context),
hasHit_(false),
radius_(0.40f),
hitPointsSize_(0),
hitBody_(nullptr)
{
}
ConvexCast::~ConvexCast()
{
}
void ConvexCast::RegisterObject(Context* context)
{
context->RegisterFactory<ConvexCast>();
}
void ConvexCast::OnNodeSet(Node* node)
{
if (!node)
return;
ResourceCache* cache = GetSubsystem<ResourceCache>();
// auto* wheelObject = shapeNode_->CreateComponent<StaticModel>();
// wheelObject->SetModel(cache->GetResource<Model>("Models/Cylinder.mdl"));
// auto* wheelBody = wheelNode->CreateComponent<RigidBody>();
shape_ = node->CreateComponent<CollisionShape>();
// shape_->SetCylinder(radius_ * 2, radius_, Vector3::ZERO);
shape_->SetSphere(radius_ * 2);
}
void ConvexCast::SetRadius(float r)
{
radius_ = r;
shape_->SetCylinder(radius_ * 2, radius_, Vector3::ZERO);
}
void ConvexCast::UpdateTransform(WheelInfo& wheel, float steeringTimer)
{
// cylinder rotation
Quaternion rot(90.0f, Vector3::FORWARD);
// steering rotation
rot = rot * Quaternion(45.0f * Urho3D::Sign(wheel.steering_) * 1.0f, Vector3::RIGHT);
shape_->SetRotation(rot);
// va relativo al centro del nodo, sino habria que hacer la transformacion con hardPointCS_
// respecto a la posicion/rotacion del nodo
// Quaternion rot = node_->GetRotation();
// hardPointWS_ = node_->GetPosition() + rot * offset_;
}
float ConvexCast::Update(WheelInfo& wheel, RigidBody* hullBody, float steeringTimer, bool debug, bool interpolateNormal)
{
URHO3D_PROFILE(ConvexCastUpdate);
UpdateTransform(wheel, steeringTimer);
Scene* scene = GetScene();
if (!scene)
return 0.0f;
PhysicsWorld* pw = scene->GetComponent<PhysicsWorld>();
btCollisionWorld* world = pw->GetWorld();
Quaternion worldRotation = node_->GetRotation() * shape_->GetRotation();
Vector3 direction = wheel.raycastInfo_.wheelDirectionWS_.Normalized();
// Ray ray(wheel.raycastInfo_.hardPointWS_, wheel.wheelDirectionCS_);
Ray ray(wheel.raycastInfo_.hardPointWS_, direction);
Vector3 startPos = ray.origin_;
Vector3 endPos = ray.origin_ + wheel.raycastInfo_.suspensionLength_ * 1.0f * ray.direction_;
//Vector3 startPos = Vector3(0.0f, 1.0f, 0.0f);
//Vector3 endPos = Vector3(0.0f, -1.0f, 0.0f);
Quaternion startRot = worldRotation;
Quaternion endRot = worldRotation;
AllConvexResultCallback convexCallback(ToBtVector3(startPos), ToBtVector3(endPos));
convexCallback.m_collisionFilterGroup = (short)0xffff;
convexCallback.m_collisionFilterMask = (short)1 << 0;
btCollisionShape* shape = shape_->GetCollisionShape();
world->convexSweepTest(reinterpret_cast<btConvexShape*>(shape),
btTransform(ToBtQuaternion(startRot), convexCallback.m_convexFromWorld),
btTransform(ToBtQuaternion(endRot), convexCallback.m_convexToWorld),
convexCallback, world->getDispatchInfo().m_allowedCcdPenetration);
hasHit_ = false;
hitPointsSize_ = 0;
hitIndex_ = -1;
hitDistance_.Clear();
hitFraction_.Clear();
hitPointWorld_.Clear();
hitNormalWorld_.Clear();
hitPointLocal_.Clear();
hitShapePart_.Clear();
hitTriangleIndex_.Clear();
float distance = 1000.0f;
hitPointsSize_ = convexCallback.m_hitPointWorld.size();
for (int i = 0; i < hitPointsSize_; i++)
{
hitPoint_ = ToVector3(convexCallback.m_hitPointWorld.at(i));
hitPointWorld_.Push(hitPoint_);
hitPointLocal_.Push(ToVector3(convexCallback.m_hitPointLocal.at(i)));
hitNormal_ = ToVector3(convexCallback.m_hitNormalWorld.at(i));
hitNormalWorld_.Push(hitNormal_);
hitFraction_.Push((float)convexCallback.m_hitFractions.at(i));
if (i < convexCallback.m_hitShapePart.size())
{
hitShapePart_.Push(convexCallback.m_hitShapePart.at(i));
hitTriangleIndex_.Push(convexCallback.m_hitTriangleIndex.at(i));
}
// use most closest to startPos point as index
float d = (hitPoint_ - startPos).Length();
hitDistance_.Push(d);
if (distance > d)
{
distance = d;
hitIndex_ = i;
}
}
float angNormal = 0.0f;
if (convexCallback.hasHit() && hitIndex_ != -1)
{
hasHit_ = true;
hitBody_ = static_cast<RigidBody*>(convexCallback.m_collisionObjects.at(hitIndex_)->getUserPointer());
wheel.raycastInfo_.isInContact_ = true;
wheel.raycastInfo_.distance_ = Max(hitDistance_.At(hitIndex_), wheel.raycastInfo_.suspensionMinRest_);
if (hitDistance_.At(hitIndex_) < wheel.raycastInfo_.suspensionMinRest_)
{
// wheel.raycastInfo_.contactPoint_ = wheel.raycastInfo_.hardPointWS_ + wheel.wheelDirectionCS_ * wheel.raycastInfo_.suspensionMinRest_;
wheel.raycastInfo_.contactPoint_ = wheel.raycastInfo_.hardPointWS_ + direction * wheel.raycastInfo_.suspensionMinRest_;
}
// else if (hitDistance_.At(hitIndex_) > wheel.raycastInfo_.suspensionMaxRest_)
// {
// wheel.raycastInfo_.contactPoint_ = wheel.raycastInfo_.hardPointWS_ + wheel.wheelDirectionCS_ * wheel.raycastInfo_.suspensionMaxRest_;
// }
else
{
wheel.raycastInfo_.contactPoint_ = hitPointWorld_.At(hitIndex_);
}
wheel.raycastInfo_.contactPointLocal_ = hitPointLocal_.At(hitIndex_);
//
angNormal = hitNormalWorld_.At(hitIndex_).DotProduct(wheel.raycastInfo_.contactNormal_);
// if((acos(angNormal) * M_RADTODEG) > 30.0f)
// {
// wheel.raycastInfo_.contactNormal_ = -wheel.wheelDirectionCS_;
// }
// else
{
if (interpolateNormal)
{
const btRigidBody* hitBody = btRigidBody::upcast(convexCallback.m_collisionObjects.at(hitIndex_));
btCollisionShape* hitShape = (btCollisionShape*)hitBody->getCollisionShape();
if (hitShape->getShapeType() == SCALED_TRIANGLE_MESH_SHAPE_PROXYTYPE)
{
btVector3 in = pw->InterpolateMeshNormal(hitBody->getWorldTransform(), hitShape, hitShapePart_.At(hitIndex_), hitTriangleIndex_.At(hitIndex_),
ToBtVector3(hitPointWorld_.At(hitIndex_)), GetComponent<DebugRenderer>());
wheel.raycastInfo_.contactNormal_ = ToVector3(in);
}
else
{
// result.normal_ = ToVector3(rayCallback.m_hitNormalWorld);
wheel.raycastInfo_.contactNormal_ = hitNormalWorld_.At(hitIndex_);
}
}
else
{
wheel.raycastInfo_.contactNormal_ = hitNormalWorld_.At(hitIndex_);
}
}
// Node* node = hitBody_->GetNode();
// btVector3 scale = ToBtVector3(node->GetScale());
// IntVector3 vc;
// if (hitIndex_ < hitShapePart_.Size())
// {
// bool collisionOk = PhysicsWorld::GetCollisionMask(convexCallback.m_collisionObjects[hitIndex_],
// ToBtVector3(hitPointWorld_.At(hitIndex_)), hitShapePart_.At(hitIndex_),
// hitTriangleIndex_.At(hitIndex_), scale, vc);
// if (collisionOk)
// {
// const VertexCollisionMaskFlags& c0 = (const VertexCollisionMaskFlags)(vc.x_);
// const VertexCollisionMaskFlags& c1 = (const VertexCollisionMaskFlags)(vc.y_);
// const VertexCollisionMaskFlags& c2 = (const VertexCollisionMaskFlags)(vc.z_);
// // color = GetFaceColor(c0);
// if((c0 & (TRACK_ROAD | TRACK_BORDER | OFFTRACK_WEAK | OFFTRACK_HEAVY))
// && (c1 & (TRACK_ROAD | TRACK_BORDER | OFFTRACK_WEAK | OFFTRACK_HEAVY))
// && (c2 & (TRACK_ROAD | TRACK_BORDER | OFFTRACK_WEAK | OFFTRACK_HEAVY))
// && c0 == c1 && c0 == c2 && c1 == c2)
// {
// wheel.raycastInfo_.contactMaterial_ = c0.AsInteger();
// }
// else
// {
// wheel.raycastInfo_.contactMaterial_ = TRACK_ROAD;
// }
// }
// else
// {
// wheel.raycastInfo_.contactMaterial_ = TRACK_ROAD;
// }
// }
// else
// {
// wheel.raycastInfo_.contactMaterial_ = TRACK_ROAD;
// }
float project = wheel.raycastInfo_.contactNormal_.DotProduct(wheel.raycastInfo_.wheelDirectionWS_);
angNormal = project;
Vector3 relPos = wheel.raycastInfo_.contactPoint_ - hullBody->GetPosition();
Vector3 contactVel = hullBody->GetVelocityAtPoint(relPos);
float projVel = wheel.raycastInfo_.contactNormal_.DotProduct(contactVel);
if (project >= -0.1f)
{
wheel.raycastInfo_.suspensionRelativeVelocity_ = 0.0f;
}
else
{
float inv = btScalar(-1.) / project;
wheel.raycastInfo_.suspensionRelativeVelocity_ = projVel * inv;
}
}
else
{
hitBody_ = nullptr;
wheel.raycastInfo_.isInContact_ = false;
wheel.raycastInfo_.distance_ = 0.0f;
wheel.raycastInfo_.contactNormal_ = -wheel.raycastInfo_.wheelDirectionWS_;
wheel.raycastInfo_.contactPoint_ = wheel.raycastInfo_.hardPointWS_ + wheel.raycastInfo_.wheelDirectionWS_;
// wheel.raycastInfo_.suspensionRelativeVelocity_ = 0.0f;
}
return wheel.raycastInfo_.suspensionRelativeVelocity_;
}
void ConvexCast::DebugDraw(const WheelInfo& wheel, Vector3 centerOfMass, bool first, float speed, Vector3 angularVel)
{
DebugRenderer* debug = GetScene()->GetComponent<DebugRenderer>();
PhysicsWorld* pw = GetScene()->GetComponent<PhysicsWorld>();
btCollisionWorld* world = pw->GetWorld();
Ray ray(wheel.raycastInfo_.hardPointWS_, wheel.raycastInfo_.wheelDirectionWS_);
Vector3 startPos = ray.origin_;
Vector3 endPos = ray.origin_ + wheel.raycastInfo_.suspensionLength_ * 1.0f * ray.direction_;
Sphere startSphere(startPos, 0.1f);
debug->AddSphere(startSphere, Color::GREEN, false);
Sphere endSphere(endPos, 0.15f);
debug->AddSphere(endSphere, Color::RED, false);
Vector<Color> colors;
colors.Push(Color::WHITE);
colors.Push(Color::GRAY);
colors.Push(Color::BLACK);
colors.Push(Color::RED);
colors.Push(Color::GREEN);
colors.Push(Color::BLUE);
colors.Push(Color::CYAN);
colors.Push(Color::MAGENTA);
colors.Push(Color::YELLOW);
// Vector3 local(hitPointLocal_.At(i));
Vector3 local(wheel.raycastInfo_.contactPointLocal_);
// Color color = colors.At(i % 9);
Sphere sphere(local, 0.01f);
debug->AddSphere(sphere, Color::YELLOW, false);
// Vector3 hit(wheel.raycastInfo_.contactPoint_ - centerOfMass);
Vector3 hit(wheel.raycastInfo_.contactPoint_);
Sphere sphereHit(hit, 0.005f);
debug->AddSphere(sphereHit, wheel.raycastInfo_.isInContact_ ? Color::GREEN : Color::BLUE, false);
// normal
Vector3 normal(wheel.raycastInfo_.contactNormal_);
debug->AddLine(hit, hit + normal.Normalized(), Color::YELLOW, false);
// debug->AddCylinder(hit, radius_, radius_, Color::BLUE, false);
pw->SetDebugRenderer(debug);
pw->SetDebugDepthTest(true);
Matrix3x4 worldTransform = node_->GetTransform();
Quaternion rotation = shape_->GetRotation();
Quaternion torqueRot(speed, Vector3::UP);
Quaternion worldRotation(worldTransform.Rotation() * rotation * torqueRot);
Vector3 worldPosition(hit);
world->debugDrawObject(btTransform(ToBtQuaternion(worldRotation), ToBtVector3(worldPosition)),
shape_->GetCollisionShape(), btVector3(0.0f, first ? 1.0 : 0.0f, !first ? 1.0f : 0.0f));
pw->SetDebugRenderer(nullptr);
// cylinder
// Vector3 shapePosition(hitPoint_);
// Quaternion shapeRotation(worldTransform.Rotation() * shape_->GetRotation());
// bool bodyActive = false;
// pw->SetDebugRenderer(debug);
// pw->SetDebugDepthTest(false);
// world->debugDrawObject(btTransform(ToBtQuaternion(shapeRotation), ToBtVector3(shapePosition)), shape_->GetCollisionShape(), bodyActive ? WHITE : GREEN);
// pw->SetDebugRenderer(nullptr);
}
| 38.641204 | 162 | 0.669322 |
213161364f5852b94b7252b7341bc026849b6443 | 396 | cpp | C++ | clang/test/SemaCXX/atomic-ops.cpp | medismailben/llvm-project | e334a839032fe500c3bba22bf976ab7af13ce1c1 | [
"Apache-2.0"
] | 3,102 | 2015-01-04T02:28:35.000Z | 2022-03-30T12:53:41.000Z | clang/test/SemaCXX/atomic-ops.cpp | medismailben/llvm-project | e334a839032fe500c3bba22bf976ab7af13ce1c1 | [
"Apache-2.0"
] | 3,740 | 2019-01-23T15:36:48.000Z | 2022-03-31T22:01:13.000Z | clang/test/SemaCXX/atomic-ops.cpp | medismailben/llvm-project | e334a839032fe500c3bba22bf976ab7af13ce1c1 | [
"Apache-2.0"
] | 1,868 | 2015-01-03T04:27:11.000Z | 2022-03-25T13:37:35.000Z | // RUN: %clang_cc1 %s -verify -fsyntax-only -triple=i686-linux-gnu -std=c++11
// We crashed when we couldn't properly convert the first arg of __atomic_* to
// an lvalue.
void PR28623() {
void helper(int); // expected-note{{target}}
void helper(char); // expected-note{{target}}
__atomic_store_n(helper, 0, 0); // expected-error{{reference to overloaded function could not be resolved}}
}
| 39.6 | 109 | 0.709596 |
213226a3b9022a3fe4e11c9ac1eb3b5125a2a6aa | 1,631 | cpp | C++ | src/prod/src/Reliability/Failover/fm/BackgroundThreadContext.cpp | gridgentoo/ServiceFabricAzure | c3e7a07617e852322d73e6cc9819d266146866a4 | [
"MIT"
] | 2,542 | 2018-03-14T21:56:12.000Z | 2019-05-06T01:18:20.000Z | src/prod/src/Reliability/Failover/fm/BackgroundThreadContext.cpp | gridgentoo/ServiceFabricAzure | c3e7a07617e852322d73e6cc9819d266146866a4 | [
"MIT"
] | 994 | 2019-05-07T02:39:30.000Z | 2022-03-31T13:23:04.000Z | src/prod/src/Reliability/Failover/fm/BackgroundThreadContext.cpp | gridgentoo/ServiceFabricAzure | c3e7a07617e852322d73e6cc9819d266146866a4 | [
"MIT"
] | 300 | 2018-03-14T21:57:17.000Z | 2019-05-06T20:07:00.000Z | // ------------------------------------------------------------
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License (MIT). See License.txt in the repo root for license information.
// ------------------------------------------------------------
#include "stdafx.h"
using namespace std;
using namespace Common;
using namespace Reliability;
using namespace Reliability::FailoverManagerComponent;
BackgroundThreadContext::BackgroundThreadContext(wstring const & contextId)
: contextId_(contextId)
{
}
void BackgroundThreadContext::TransferUnprocessedFailoverUnits(BackgroundThreadContext & original)
{
swap(unprocessedFailoverUnits_, original.unprocessedFailoverUnits_);
}
bool BackgroundThreadContext::MergeUnprocessedFailoverUnits(set<FailoverUnitId> const & failoverUnitIds)
{
if (unprocessedFailoverUnits_.size() == 0)
{
unprocessedFailoverUnits_ = failoverUnitIds;
}
else
{
for (auto it = unprocessedFailoverUnits_.begin(); it != unprocessedFailoverUnits_.end();)
{
if (failoverUnitIds.find(*it) == failoverUnitIds.end())
{
unprocessedFailoverUnits_.erase(it++);
}
else
{
++it;
}
}
}
return (unprocessedFailoverUnits_.size() == 0);
}
void BackgroundThreadContext::ClearUnprocessedFailoverUnits()
{
unprocessedFailoverUnits_.clear();
}
void BackgroundThreadContext::WriteTo(TextWriter& w, FormatOptions const &) const
{
w.Write("{0}: Unprocessed={1:3}", contextId_, unprocessedFailoverUnits_);
}
| 29.125 | 104 | 0.642551 |
2133f6985c01b081e1458d696d0ba701f66c2136 | 369 | cpp | C++ | Space-Invaders/Space-Invaders/src/main.cpp | vnescape/Space-Invaders | 907e91f594048a3c835ea43903cf7332d7fa82c2 | [
"MIT"
] | 1 | 2022-03-05T22:09:50.000Z | 2022-03-05T22:09:50.000Z | Space-Invaders/Space-Invaders/src/main.cpp | vnescape/Space-Invaders | 907e91f594048a3c835ea43903cf7332d7fa82c2 | [
"MIT"
] | null | null | null | Space-Invaders/Space-Invaders/src/main.cpp | vnescape/Space-Invaders | 907e91f594048a3c835ea43903cf7332d7fa82c2 | [
"MIT"
] | null | null | null | //Source: https://www.glfw.org/documentation.html
#include <GL/glew.h>
#include <GLFW/glfw3.h>
#include <iostream>
#include <string>
#include <sstream>
#include <fstream>
#include "Game.h"
#include "Shader.h"
#include "Renderer.h"
#include "VertexBuffer.h"
#include "VertexArray.h"
#include "IndexBuffer.h"
int main(void)
{
Game::Game(640, 480);
return 0;
} | 16.772727 | 49 | 0.696477 |
2133fea2d2f423786a1f5dff1923a21c5d135256 | 1,218 | hpp | C++ | src/clustering/generic/registration_metadata.hpp | sauter-hq/rethinkdb | f34541d501bcf109c2825a7a1b67cf8fd39b9133 | [
"Apache-2.0"
] | null | null | null | src/clustering/generic/registration_metadata.hpp | sauter-hq/rethinkdb | f34541d501bcf109c2825a7a1b67cf8fd39b9133 | [
"Apache-2.0"
] | null | null | null | src/clustering/generic/registration_metadata.hpp | sauter-hq/rethinkdb | f34541d501bcf109c2825a7a1b67cf8fd39b9133 | [
"Apache-2.0"
] | null | null | null | // Copyright 2010-2014 RethinkDB, all rights reserved.
#ifndef CLUSTERING_GENERIC_REGISTRATION_METADATA_HPP_
#define CLUSTERING_GENERIC_REGISTRATION_METADATA_HPP_
#include "containers/uuid.hpp"
#include "rpc/mailbox/typed.hpp"
#include "rpc/semilattice/joins/macros.hpp"
template<class business_card_t>
class registrar_business_card_t {
public:
typedef uuid_u registration_id_t;
typedef mailbox_t<void(registration_id_t, peer_id_t, business_card_t)> create_mailbox_t;
typename create_mailbox_t::address_t create_mailbox;
typedef mailbox_t<void(registration_id_t)> delete_mailbox_t;
typename delete_mailbox_t::address_t delete_mailbox;
registrar_business_card_t() { }
registrar_business_card_t(
const typename create_mailbox_t::address_t &cm,
const typename delete_mailbox_t::address_t &dm) :
create_mailbox(cm), delete_mailbox(dm)
{ }
RDB_MAKE_ME_SERIALIZABLE_2(registrar_business_card_t,
create_mailbox, delete_mailbox);
};
template <class business_card_t>
RDB_MAKE_EQUALITY_COMPARABLE_2(registrar_business_card_t<business_card_t>,
create_mailbox, delete_mailbox);
#endif /* CLUSTERING_GENERIC_REGISTRATION_METADATA_HPP_ */
| 32.918919 | 92 | 0.791461 |
213501518e2260911a4440b08ed8399758618c3c | 5,921 | cc | C++ | mojo/services/media/common/cpp/video_converter.cc | jason-simmons/flutter_buildroot | 1c9494e60378bd119d910d530344077fc091b3a5 | [
"BSD-3-Clause"
] | null | null | null | mojo/services/media/common/cpp/video_converter.cc | jason-simmons/flutter_buildroot | 1c9494e60378bd119d910d530344077fc091b3a5 | [
"BSD-3-Clause"
] | null | null | null | mojo/services/media/common/cpp/video_converter.cc | jason-simmons/flutter_buildroot | 1c9494e60378bd119d910d530344077fc091b3a5 | [
"BSD-3-Clause"
] | null | null | null | // 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 "mojo/services/media/common/cpp/video_converter.h"
namespace mojo {
namespace media {
VideoConverter::VideoConverter() {
BuildColorspaceTable();
}
VideoConverter::~VideoConverter() {}
namespace {
uint8_t ToByte(float f) {
if (f < 0.0f) {
return 0u;
}
if (f > 255.0f) {
return 255u;
}
return static_cast<uint8_t>(f);
}
size_t ColorspaceTableOffset(uint8_t y, uint8_t u, uint8_t v) {
return (y << 8u | u) << 8u | v;
}
} // namespace
void VideoConverter::BuildColorspaceTable() {
colorspace_table_.reset(new uint32_t[256 * 256 * 256]);
uint32_t* p = colorspace_table_.get();
for (size_t iy = 0; iy < 256; ++iy) {
for (size_t iu = 0; iu < 256; ++iu) {
for (size_t iv = 0; iv < 256; ++iv) {
float y = static_cast<float>(iy);
float u = static_cast<float>(iu);
float v = static_cast<float>(iv);
// R = 1.164(Y - 16) + 1.596(V - 128)
uint8_t r = ToByte(1.164f * (y - 16.0f) + 1.596f * (v - 128.0f));
// G = 1.164(Y - 16) - 0.813(V - 128) - 0.391(U - 128)
uint8_t g = ToByte(1.164f * (y - 16.0f) - 0.813f * (v - 128.0f) -
0.391f * (u - 128.0f));
// B = 1.164(Y - 16) + 2.018(U - 128)
uint8_t b = ToByte(1.164f * (y - 16.0f) + 2.018f * (u - 128.0f));
*p = r | (g << 8u) | (b << 16u) | (255u << 24u);
++p;
}
}
}
}
void VideoConverter::SetMediaType(const MediaTypePtr& media_type) {
MOJO_DCHECK(media_type);
MOJO_DCHECK(media_type->medium == MediaTypeMedium::VIDEO);
MOJO_DCHECK(media_type->encoding == MediaType::kVideoEncodingUncompressed);
MOJO_DCHECK(media_type->details);
const VideoMediaTypeDetailsPtr& details = media_type->details->get_video();
MOJO_DCHECK(details);
MOJO_DCHECK(details->pixel_format == PixelFormat::YV12)
<< "only YV12 video conversion is currently implemented";
layout_ =
VideoPacketLayout(details->pixel_format, details->width, details->height,
details->coded_width, details->coded_height);
media_type_set_ = true;
}
Size VideoConverter::GetSize() {
Size size;
if (media_type_set_) {
size.width = layout_.width();
size.height = layout_.height();
} else {
size.width = 0;
size.height = 0;
}
return size;
}
void VideoConverter::ConvertFrame(uint8_t* rgba_buffer,
uint32_t view_width,
uint32_t view_height,
void* payload,
uint64_t payload_size) {
MOJO_DCHECK(rgba_buffer != nullptr);
MOJO_DCHECK(view_width != 0);
MOJO_DCHECK(view_height != 0);
MOJO_DCHECK(payload != nullptr);
MOJO_DCHECK(payload_size != 0);
MOJO_DCHECK(media_type_set_)
<< "need to call SetMediaType before ConvertFrame";
uint32_t height = std::min(layout_.height(), view_height);
uint32_t width = std::min(layout_.width(), view_width);
// YV12 frames have three separate planes. The Y plane has 8-bit Y values for
// each pixel. The U and V planes have 8-bit U and V values for 2x2 grids of
// pixels, so those planes are each 1/4 the size of the Y plane. Both the
// inner and outer loops below are unrolled to deal with the 2x2 logic.
size_t dest_line_stride = view_width;
size_t y_line_stride =
layout_.line_stride_for_plane(VideoPacketLayout::kYPlaneIndex);
size_t u_line_stride =
layout_.line_stride_for_plane(VideoPacketLayout::kUPlaneIndex);
size_t v_line_stride =
layout_.line_stride_for_plane(VideoPacketLayout::kVPlaneIndex);
uint32_t* dest_line = reinterpret_cast<uint32_t*>(
rgba_buffer + dest_line_stride * (view_height - 1) * sizeof(uint32_t));
uint8_t* y_line =
reinterpret_cast<uint8_t*>(payload) +
layout_.plane_offset_for_plane(VideoPacketLayout::kYPlaneIndex);
uint8_t* u_line =
reinterpret_cast<uint8_t*>(payload) +
layout_.plane_offset_for_plane(VideoPacketLayout::kUPlaneIndex);
uint8_t* v_line =
reinterpret_cast<uint8_t*>(payload) +
layout_.plane_offset_for_plane(VideoPacketLayout::kVPlaneIndex);
for (uint32_t line = 0; line < height; ++line) {
ConvertLine(dest_line, y_line, u_line, v_line, width);
dest_line -= dest_line_stride;
y_line += y_line_stride;
// Notice we aren't updating u_line and v_line here.
// If we hadn't unrolled the loop, it would have ended here.
if (++line == height) {
break;
}
ConvertLine(dest_line, y_line, u_line, v_line, width);
dest_line -= dest_line_stride;
y_line += y_line_stride;
// Here, we ARE updating u_line and v_line, because we've moved vertically
// out of the 2x2 grid.
u_line += u_line_stride;
v_line += v_line_stride;
}
}
void VideoConverter::ConvertLine(uint32_t* dest_pixel,
uint8_t* y_pixel,
uint8_t* u_pixel,
uint8_t* v_pixel,
uint32_t width) {
for (uint32_t pixel = 0; pixel < width; ++pixel) {
*dest_pixel =
colorspace_table_
.get()[ColorspaceTableOffset(*y_pixel, *u_pixel, *v_pixel)];
++dest_pixel;
++y_pixel;
// Notice we aren't incrementing u_pixel and v_pixel here.
// If we hadn't unrolled the loop, it would have ended here.
if (++pixel == width) {
break;
}
*dest_pixel =
colorspace_table_
.get()[ColorspaceTableOffset(*y_pixel, *u_pixel, *v_pixel)];
++dest_pixel;
++y_pixel;
// Here, we ARE incrementing u_pixel and v_pixel, because we've moved
// horizontally out of the 2x2 grid.
++u_pixel;
++v_pixel;
}
}
} // namespace media
} // namespace mojo
| 31 | 79 | 0.629623 |
2138950715d1c7f2b8c86bd9a09b4d6ba5a296dc | 1,247 | cpp | C++ | gk/spritesheet.cpp | rpav/GameKernel | 1f3eb863b58243f5f14aa76283b60a259d881522 | [
"MIT"
] | 11 | 2016-04-28T15:09:19.000Z | 2019-07-15T15:58:59.000Z | gk/spritesheet.cpp | rpav/GameKernel | 1f3eb863b58243f5f14aa76283b60a259d881522 | [
"MIT"
] | null | null | null | gk/spritesheet.cpp | rpav/GameKernel | 1f3eb863b58243f5f14aa76283b60a259d881522 | [
"MIT"
] | null | null | null | #include <rpav/log.hpp>
#include <stdlib.h>
#include "gk/gk.hpp"
#include "gk/gl.hpp"
#include "gk/spritesheet.hpp"
using namespace rpav;
void gk_process_spritesheet_create(gk_context* gk, gk_cmd_spritesheet_create* cmd)
{
auto sheet = (gk_spritesheet*)malloc(sizeof(gk_spritesheet));
switch(cmd->format) {
case GK_SSF_TEXTUREPACKER_JSON:
gk_load_ssf_texturepacker_json(gk, cmd, sheet);
break;
default:
say("Unknown sprite sheet format ", cmd->format);
gk_seterror(gk, GK_ERROR_SSF_UNKNOWN);
break;
}
// If there is an error, the loader should free everything it
// allocates
if(gk_haserror(gk)) goto error;
cmd->sheet = sheet;
return;
error:
free(sheet);
}
void gk_free_one_sheet(gk_spritesheet* sheet)
{
GL_CHECK(glDeleteTextures(1, (GLuint*)&sheet->tex));
gl_error:
free(sheet->sprites);
for(size_t i = 0; i < sheet->nsprites; ++i) free(sheet->names[i]);
free(sheet->names);
free(sheet);
}
void gk_process_spritesheet_destroy(gk_context*, gk_cmd_spritesheet_destroy* cmd)
{
for(size_t i = 0; i < cmd->nsheets; ++i) {
auto sheet = cmd->sheets[i];
gk_free_one_sheet(sheet);
}
}
| 22.672727 | 82 | 0.648757 |
213abf05b084f9f7df27ceb2c4505f6b15f9c57d | 797 | cpp | C++ | Example/datetime_21/main.cpp | KwangjoJeong/Boost | 29c4e2422feded66a689e3aef73086c5cf95b6fe | [
"MIT"
] | null | null | null | Example/datetime_21/main.cpp | KwangjoJeong/Boost | 29c4e2422feded66a689e3aef73086c5cf95b6fe | [
"MIT"
] | null | null | null | Example/datetime_21/main.cpp | KwangjoJeong/Boost | 29c4e2422feded66a689e3aef73086c5cf95b6fe | [
"MIT"
] | null | null | null | #include <boost/date_time/gregorian/gregorian.hpp>
#include <string>
#include <vector>
#include <locale>
#include <iostream>
using namespace boost::gregorian;
int main()
{
std::locale::global(std::locale{"German"});
std::string months[12]{"Januar", "Februar", "M\xe4rz", "April",
"Mai", "Juni", "Juli", "August", "September", "Oktober",
"November", "Dezember"};
std::string weekdays[7]{"Sonntag", "Montag", "Dienstag",
"Mittwoch", "Donnerstag", "Freitag", "Samstag"};
date d{2014, 5, 12};
date_facet *df = new date_facet{"%A, %d. %B %Y"};
df->long_month_names(std::vector<std::string>{months, months + 12});
df->long_weekday_names(std::vector<std::string>{weekdays,
weekdays + 7});
std::cout.imbue(std::locale{std::cout.getloc(), df});
std::cout << d << '\n';
} | 33.208333 | 70 | 0.643664 |
213ae5345d9ad68812860bb69e049e602d81045e | 683 | cpp | C++ | FPS_Multiplayer_UE4/Source/TestRyseUp/Private/Items/ConsumableActor.cpp | agerith/FPS_Multiplayer_UE4 | 61e2d330c06740de1f19219833ff177c444fdb5c | [
"MIT"
] | 1 | 2022-03-22T07:27:29.000Z | 2022-03-22T07:27:29.000Z | FPS_Multiplayer_UE4/Source/TestRyseUp/Private/Items/ConsumableActor.cpp | agerith/FPS_Multiplayer_UE4 | 61e2d330c06740de1f19219833ff177c444fdb5c | [
"MIT"
] | null | null | null | FPS_Multiplayer_UE4/Source/TestRyseUp/Private/Items/ConsumableActor.cpp | agerith/FPS_Multiplayer_UE4 | 61e2d330c06740de1f19219833ff177c444fdb5c | [
"MIT"
] | null | null | null | // Fill out your copyright notice in the Description page of Project Settings.
#include "ConsumableActor.h"
#include "TestRyseUp.h"
#include "ConsumableActor.h"
#include "TestRyseUpCharacter.h"
AConsumableActor::AConsumableActor(const class FObjectInitializer& ObjectInitializer)
: Super(ObjectInitializer)
{
/* A default to tweak per food variation in Blueprint */
Nutrition = 40;
bAllowRespawn = true;
RespawnDelay = 60.0f;
RespawnDelayRange = 20.0f;
}
void AConsumableActor::OnUsed(APawn* InstigatorPawn)
{
ATestRyseUpCharacter* Pawn = Cast<ATestRyseUpCharacter>(InstigatorPawn);
if (Pawn)
{
Pawn->RestoreLife(Nutrition);
}
Super::OnUsed(InstigatorPawn);
}
| 20.088235 | 85 | 0.764275 |
213bbd49b3a68fc5ca0914014d611b44f3cc9037 | 1,348 | cpp | C++ | array_and_matrixs/Kth_smallest_element_in_a_sorted_matrix.cpp | zm66260/Data_Structure_and_Algorithms | f3e6d60a9f0ddf1a8fe943dedc089172bc8c833e | [
"MIT"
] | null | null | null | array_and_matrixs/Kth_smallest_element_in_a_sorted_matrix.cpp | zm66260/Data_Structure_and_Algorithms | f3e6d60a9f0ddf1a8fe943dedc089172bc8c833e | [
"MIT"
] | null | null | null | array_and_matrixs/Kth_smallest_element_in_a_sorted_matrix.cpp | zm66260/Data_Structure_and_Algorithms | f3e6d60a9f0ddf1a8fe943dedc089172bc8c833e | [
"MIT"
] | null | null | null | // 378 kth smallest element in a sorted matrix
// Given a n x n matrix where each of the rows and columns are sorted in ascending order, find the kth smallest element in the matrix.
// Note that it is the kth smallest element in the sorted order, not the kth distinct element.
// Example:
// matrix = [
// [ 1, 5, 9],
// [10, 11, 13],
// [12, 13, 15]
// ],
// k = 8,
// return 13.
// Note:
// You may assume k is always valid, 1 ≤ k ≤ n2.
#include<vector>
using namespace std;
class Solution {
public:
int kthSmallest(vector<vector<int>>& matrix, int k) {
int left = matrix[0][0];
int right = matrix[matrix.size()-1][matrix.size()-1];
while(left < right){
int mid = (left + right) / 2;
int count = searchMatrix(matrix, mid);
if(count < k){
left = mid+1;
}
else{right = mid;}
}
return left;
}
int searchMatrix(vector<vector<int>>& matrix, int midvalue){
int r = matrix.size()-1;
int c = 0;
int count = 0;
while(r >= 0 && c < matrix[0].size()){
if(matrix[r][c] <= midvalue){
c++;
count += r + 1;
}
else{r--;}
}
return count;
}
};
| 24.962963 | 135 | 0.488131 |
213c8cfd95f2e6d3357ab23aca5ea12ebe29e7b8 | 27,246 | cpp | C++ | Crypt.cpp | srinskit/Crypt | 3197bd82092f29fe0df3959754c0f340d6170ab4 | [
"MIT"
] | null | null | null | Crypt.cpp | srinskit/Crypt | 3197bd82092f29fe0df3959754c0f340d6170ab4 | [
"MIT"
] | null | null | null | Crypt.cpp | srinskit/Crypt | 3197bd82092f29fe0df3959754c0f340d6170ab4 | [
"MIT"
] | null | null | null | /*
Made with ❤ by srinSkit.
Created on 28 May 2018.
*/
#include "Crypt.h"
#define print_err if(print_errors) printf
#define print_err1 if(my_crypt->print_errors) printf
// Use macro carefully
/*
* Initialize libraries
* return true on success, false on Crypture
*/
bool Crypt::initialize(cs personalize, bool print_errors) {
this->print_errors = print_errors;
mbedtls_entropy_init(&entropy);
mbedtls_ctr_drbg_init(&ctr_drbg);
auto ret = mbedtls_ctr_drbg_seed(&ctr_drbg, mbedtls_entropy_func, &entropy, rccuc(personalize.c_str()),
personalize.length());
if (ret != 0) {
print_err("[Crypt] mbedtls_ctr_drbg_seed returned -0x%04x\n", ret);
return false;
}
if ((ret = mbedtls_ctr_drbg_random(&ctr_drbg, aes_iv, sizeof(aes_iv))) != 0) {
print_err("[Crypt] mbedtls_ctr_drbg_random returned -0x%04x\n", -ret);
return false;
}
mbedtls_x509_crt_init(&my_cert);
mbedtls_pk_init(&my_private_key);
return true;
}
/*
* Cleanup
*/
void Crypt::terminate() {
// Unchain before free
for (auto &certificate : certificates)
certificate.second->next = nullptr;
my_cert.next = nullptr;
// Free
for (auto &certificate : certificates) {
mbedtls_x509_crt_free(certificate.second);
delete (certificate.second);
}
for (auto &pair:aes_context_map) {
mbedtls_aes_free(pair.second);
delete (pair.second);
}
mbedtls_pk_free(&my_private_key);
mbedtls_x509_crt_free(&my_cert);
mbedtls_ctr_drbg_free(&ctr_drbg);
mbedtls_entropy_free(&entropy);
}
/*
* Clear string with null chars
* TODO: find alternatives to store passwords in memory
*/
void Crypt::clear_string(s buff) {
for (char &i : buff)
i = '\0';
}
/*
* Load private key at 'path' using password 'password' into 'my_private_key'
* return true on success, false on parse Crypt
*/
bool Crypt::load_my_key(cs path, cs password) {
mbedtls_pk_free(&my_private_key);
mbedtls_pk_init(&my_private_key);
auto ret = mbedtls_pk_parse_keyfile(&my_private_key, path.c_str(), password.c_str());
if (ret != 0) {
print_err("[Crypt] mbedtls_pk_parse_keyfile returned -0x%04x\n", -ret);
return false;
}
return true;
}
/*
*
*/
bool Crypt::load_my_cert(cs path, cs next, bool name_it_self) {
if (name_it_self && certificates.find("self") != certificates.end()) {
print_err("[Crypt] certificate tagged self already exists\n");
return false;
}
mbedtls_x509_crt_free(&my_cert);
mbedtls_x509_crt_init(&my_cert);
int ret;
if ((ret = mbedtls_x509_crt_parse_file(&my_cert, path.c_str())) != 0) {
print_err("[Crypt] mbedtls_x509_crt_parse_file returned -0x%04x\n", -ret);
return false;
}
if (next.length() != 0)
my_cert.next = certificates[next];
if (name_it_self)
return add_cert("self", path, next);
return true;
}
/*
* Load certificate from 'path' and store it in map 'certificates' against 'name'
* returns true on success, false if certificate of 'name' exists or file parse Crypted
*/
bool Crypt::add_cert(cs name, cs path, cs next) {
if (certificates.find(name) != certificates.end()) {
print_err("[Crypt] certificate tag taken\n");
return false;
}
auto certificate = new mbedtls_x509_crt;
mbedtls_x509_crt_init(certificate);
int ret;
if ((ret = mbedtls_x509_crt_parse_file(certificate, path.c_str())) != 0) {
print_err("[Crypt] mbedtls_x509_crt_parse_file returned -0x%04x\n", -ret);
return false;
}
certificates[name] = certificate;
if (next.length() != 0) {
auto it_next = certificates.find(next);
if (it_next == certificates.end()) {
print_err("[Crypt] next certificate tag not found\n");
return false;
}
certificate->next = it_next->second;
}
return true;
}
/*
* Remove certificate associated with 'name'
*/
void Crypt::rem_cert(cs name) {
auto cert = certificates[name];
certificates.erase(name);
// Unchain before free
cert->next = nullptr;
mbedtls_x509_crt_free(cert);
delete (cert);
}
/*
* Encrypt 'msg' using public key in certificate associated with 'certificate_name'
* and dump result into 'dump'
* return true on success, false on encrypt Crypture
*/
bool Crypt::encrypt(cs msg, cs certificate_name, s dump) {
if (certificates.find(certificate_name) == certificates.end()) {
print_err("[Crypt] certificate not found\n");
return false;
}
unsigned char result[MBEDTLS_MPI_MAX_SIZE];
// Todo: check if enc msg can fit in 'result'
size_t olen = 0;
auto ret = mbedtls_pk_encrypt(&certificates[certificate_name]->pk,
rccuc(msg.c_str()), msg.length(), result, &olen,
sizeof(result), mbedtls_ctr_drbg_random, &ctr_drbg);
if (ret != 0) {
print_err("[Crypt] mbedtls_pk_encrypt returned -0x%04x\n", -ret);
return false;
}
dump.append(rcc(result), olen);
return true;
}
/*
* decrypts 'dump' using 'my_private_key' and restore it in 'msg'
* returns true on success, false on Crypted decryption
*/
bool Crypt::decrypt(cs dump, s msg) {
unsigned char result[MBEDTLS_MPI_MAX_SIZE];
// Todo: check if enc msg can fit in 'result'
size_t olen = 0;
auto ret = mbedtls_pk_decrypt(&my_private_key, rccuc(dump.c_str()), dump.length(),
result, &olen, sizeof(result), mbedtls_ctr_drbg_random, &ctr_drbg);
if (ret != 0) {
print_err("[Crypt] mbedtls_pk_decrypt returned -0x%04x\n", -ret);
return false;
}
msg.append(rcc(result), olen);
return true;
}
/*
* Dumps signed(using 'my_private_key') sha256 hash of 'msg' into 'dump'
* returns true on success, false on signing Crypture
*/
bool Crypt::sign(cs msg, s dump) {
unsigned char result[MBEDTLS_MPI_MAX_SIZE];
// Todo: check if dec msg can fit in 'result'
unsigned char hash[256 / 8];
size_t olen = 0;
mbedtls_sha256(rccuc(msg.c_str()), msg.length(), hash, 0);
auto ret = mbedtls_pk_sign(&my_private_key, MBEDTLS_MD_SHA256, hash, 0, result, &olen, mbedtls_ctr_drbg_random,
&ctr_drbg);
if (ret != 0) {
print_err("[Crypt] mbedtls_pk_sign returned -0x%04x\n", -ret);
return false;
}
dump.append(rcc(result), olen);
return true;
}
/*
* Checks if 'dump' is equal to signed sha256 hash of 'msg' using certificate 'name'
* returns true if sign is verified, false on Crypture
*/
bool Crypt::verify_sign(cs msg, cs dump, cs name) {
if (certificates.find(name) == certificates.end())
return false;
unsigned char hash[256 / 8];
mbedtls_sha256(rccuc(msg.c_str()), msg.length(), hash, 0);
// TODO: check if verify returns true if 'signed' using public key as it returns true when verified using pub/private key
auto ret = mbedtls_pk_verify(&certificates[name]->pk, MBEDTLS_MD_SHA256, hash, 0, rccuc(dump.c_str()),
dump.length());
if (ret != 0) {
print_err("[Crypt] mbedtls_pk_verify returned -0x%04x\n", -ret);
return false;
}
return true;
}
/*
* Copy the SHA256 checksum of 'msg' into 'sum'
* returns true always
*/
bool Crypt::checksum(cs msg, s sum) {
unsigned char u_hash[256 / 8];
mbedtls_sha256(rccuc(msg.c_str()), msg.length(), u_hash, 0);
sum.assign(rcc(u_hash), sizeof(u_hash));
return true;
}
/*
* Verify if 'sum' is the SHA256 checksum of 'msg'
* returns true on successful verification, else false
*/
bool Crypt::verify_checksum(cs msg, cs sum) {
unsigned char u_hash[256 / 8];
if (sum.length() != sizeof(u_hash)) return false;
mbedtls_sha256(rccuc(msg.c_str()), msg.length(), u_hash, 0);
return sum.compare(0, sum.length(), reinterpret_cast<const char *>(u_hash), sizeof(u_hash)) == 0;
}
/*
* Get the size of a SHA256 checksum
* returns the size of a SHA256 checksum
*/
int Crypt::checksum_size() {
return 256 / 8;
}
/*
* Verify certificate named 'name' using certificate named 'root' as CA
* return true if verification successful, else false
*/
bool Crypt::verify_cert(cs root, cs name) {
auto it_root = certificates.find(root), it_name = certificates.find(name);
if (it_root == certificates.end() || it_name == certificates.end()) {
perror("[Crypt] cannot resolve tag(s)\n");
return false;
}
unsigned result;
return mbedtls_x509_crt_verify(it_name->second, it_root->second, nullptr, nullptr, &result, nullptr, nullptr) == 0;
}
/*
* Verify certificate named 'name' and its common name 'common_name'
* using certificate named 'root' as CA
* return true if verification successful, else false
*/
bool Crypt::verify_cert(cs root, cs name, cs common_name) {
auto it_root = certificates.find(root), it_name = certificates.find(name);
if (it_root == certificates.end() || it_name == certificates.end()) {
perror("[Crypt] cannot resolve tag(s)\n");
return false;
}
unsigned result;
return mbedtls_x509_crt_verify(it_name->second, it_root->second, nullptr, common_name.c_str(), &result, nullptr,
nullptr) == 0;
}
std::string Crypt::stringify_cert(cs name) {
if (certificates.find(name) == certificates.end())
return "";
return std::string(rcc(certificates[name]->raw.p), certificates[name]->raw.len);
}
bool Crypt::certify_string(cs buff, cs common_name) {
if (certificates.find(common_name) != certificates.end())
return false;
auto certificate = new mbedtls_x509_crt;
mbedtls_x509_crt_init(certificate);
if (mbedtls_x509_crt_parse(certificate, rccuc(buff.c_str()), buff.length()) ==
0) {
bool verified = false;
for (auto &pair: certificates) {
// Todo: check against only trusted sources
uint32_t result;
if (mbedtls_x509_crt_verify(certificate, pair.second, nullptr, common_name.c_str(), &result, nullptr,
nullptr) == 0) {
verified = true;
break;
}
}
if (verified) {
certificates[common_name] = certificate;
return true;
}
}
delete (certificate);
return false;
}
/*
* Generate a 256 bit AES key and store in into 'key'
* return true on success, false on Crypture
*/
bool Crypt::aes_gen_key(s key) {
unsigned char buff[32];
int ret;
if ((ret = mbedtls_ctr_drbg_random(&ctr_drbg, buff, sizeof(buff))) != 0) {
print_err("[Crypt] mbedtls_ctr_drbg_random returned -0x%04x\n", -ret);
return false;
}
key.assign(rcc(buff), sizeof(buff));
return true;
}
/*
* Save the AES key 'key' such that it can be addressable by 'name'
* Save the key in a name-vs-key map (to enable raw access)
* Initialize and save the name-vs-aes_context map
* return true on success, false on Crypture
* Todo: global keys not thread-safe
*/
bool Crypt::aes_save_key(cs name, cs key) {
auto aes_e = new mbedtls_aes_context;
mbedtls_aes_init(aes_e);
int ret;
if ((ret = mbedtls_aes_setkey_enc(aes_e, rccuc(key.c_str()), 256)) != 0) {
mbedtls_aes_free(aes_e);
delete (aes_e);
print_err("[Crypt] mbedtls_aes_setkey_enc returned -0x%04x\n", -ret);
return false;
}
aes_context_map[name] = aes_e;
aes_key_map[name] = key;
return true;
}
/*
* Generate a 256 bit AES key that can be addressed by 'name'
* return true on success, false on Crypture
*/
bool Crypt::aes_save_key(cs name) {
std::string key;
if (!aes_gen_key(key))return false;
return aes_save_key(name, key);
}
/*
* Delete key addressed by 'name'
* Free the referenced aes_context erase map records
* return true on success, false if 'name' was not found
* Todo: global keys not thread-safe
*/
bool Crypt::aes_del_key(cs name) {
if (aes_key_map.find(name) == aes_key_map.end()) {
perror("[Crypt] cannot resolve tag\n");
return false;
}
auto aes_e = aes_context_map[name];
mbedtls_aes_free(aes_e);
aes_context_map.erase(name);
aes_key_map.erase(name);
delete aes_e;
return true;
}
/*
* Encrypt 'msg' using AES key referred to by 'key_name' and assign the result to 'dump'
* Mind the max message size of 2048(buff) - 16(IV) bytes
* return true on success, false if 'key_name' was not found, 'msg' too big
* or encryption Crypture
* Todo: fix conservative assumption: output.len = IV.len + msg.len.
* Todo: common IV and global keys not thread-safe, fix return true if key is wrong too
*/
bool Crypt::aes_encrypt(cs msg, cs key_name, s dump) {
unsigned char output[2048];
if (msg.length() > (sizeof(output) - sizeof(aes_iv))) {
perror("[Crypt] msg too large\n");
return false;
}
auto it = aes_context_map.find(key_name);
if (it == aes_context_map.end()) {
perror("[Crypt] cannot resolve tag\n");
return false;
}
auto aes = it->second;
dump.assign(rcc(aes_iv), sizeof(aes_iv));
int ret;
if ((ret = mbedtls_aes_crypt_cfb8(aes, MBEDTLS_AES_ENCRYPT, msg.length(), aes_iv, rccuc(msg.c_str()), output)) !=
0) {
print_err("[Crypt] mbedtls_aes_crypt_cfb8 returned -0x%04x\n", -ret);
dump.clear();
return false;
}
dump.append(rcc(output), msg.length());
return true;
}
/*
* Decrypt 'dump' using AES key referred to by 'key_name' and append result to 'msg'
* Mind the max dump size of 2048(buff) + 16(IV) bytes
* return true on success, false if 'key_name' not found, 'dump' too big or too small
* or decryption Crypture
* Todo: confirm encryption assumptions, make max decrypt dump size = max encrypt dump size
* Todo: global keys not thread-safe
*/
bool Crypt::aes_decrypt(cs dump, cs key_name, s msg) {
unsigned char output[2048];
unsigned char iv[16];
auto msg_size = dump.length() - sizeof(iv);
if (msg_size > sizeof(output)) {
perror("[Crypt] msg too large\n");
return false;
}
auto it = aes_context_map.find(key_name);
if (it == aes_context_map.end()) {
perror("[Crypt] cannot resolve tag\n");
return false;
}
auto aes = it->second;
if (dump.copy(rcc(iv), sizeof(iv)) != sizeof(iv)) return false;
auto enc_msg = dump.substr(sizeof(iv));
int ret;
if ((ret = mbedtls_aes_crypt_cfb8(aes, MBEDTLS_AES_DECRYPT, enc_msg.length(), iv, rccuc(enc_msg.c_str()),
output)) != 0) {
print_err("[Crypt] mbedtls_aes_crypt_cfb8 returned -0x%04x\n", -ret);
return false;
}
msg.append(rcc(output), msg_size);
return true;
}
/*
* Check if a AES key tagged 'name' exists
* return true if exists, else false
*/
bool Crypt::aes_exist_key(cs name) {
return aes_key_map.find(name) != aes_key_map.end();
}
/*
* Copies AES key tagged 'name' into 'key'
* returns true if such a key exists, else false
*/
bool Crypt::aes_get_key(cs name, s key) {
auto it = aes_key_map.find(name);
if (it == aes_key_map.end())
return false;
key = it->second;
return true;
}
/*
* Print error message given mbedtls error code
* For internal use
*/
void Crypt::print_internal_error(int err_code) {
mbedtls_strerror(err_code, error_buff, sizeof(error_buff));
print_err("%s\n", error_buff);
}
/*
* Convert a string of bytes into a hex string
* returns true if conversion was successful, else false
*/
bool Crypt::bytes_to_hex(cs bytes, s hex) {
auto n_to_h = [](int x) {
if (x < 10) return static_cast<char>('0' + x);
if (x < 16) return static_cast<char>(x - 10 + 'a');
return '0';
};
for (auto &ch:bytes) {
hex.append(1, n_to_h((static_cast<unsigned char>(ch) / 16) % 16));
hex.append(1, n_to_h(static_cast<unsigned char>(ch) % 16));
}
return true;
}
/*
* Convert a hex string into a string of bytes
* returns true if conversion was successful, else false
*/
bool Crypt::hex_to_bytes(cs hex, s bytes) {
auto h_to_d = [](char x) {
if (x >= '0' && x <= '9') return static_cast<unsigned char>(x - '0');
return static_cast<unsigned char>(x - 'a' + 10);
};
if (hex.length() % 2) return false;
int i = 0, byte;
while (i < hex.length()) {
byte = 16 * h_to_d(hex[i]) + h_to_d(hex[i + 1]);
if (byte < 0 || byte > 255)
return false;
bytes.append(1, byte);
i += 2;
}
return true;
}
/*
* Pass as debug callback to supported mbedtls functions for debug info on stdout
* For internal use
*/
void my_debug(void *ctx, int level, const char *file, int line,
const char *str) {
return;
const char *p, *basename;
(void) ctx;
/* Extract basename from file */
for (p = basename = file; *p != '\0'; p++) {
if (*p == '/' || *p == '\\') {
basename = p + 1;
}
}
printf("%s:%04d: |%d| %s", basename, line, level, str);
}
SecureSock::Server::Server(Crypt *crypt) {
my_crypt = crypt;
}
bool SecureSock::Server::init() {
mbedtls_net_init(&listen_fd);
mbedtls_ssl_config_init(&conf);
return true;
}
bool SecureSock::Server::bind(int port) {
int ret;
if ((ret = mbedtls_net_bind(&listen_fd, nullptr, std::to_string(port).c_str(), MBEDTLS_NET_PROTO_TCP)) != 0) {
print_err1("[Crypt] mbedtls_net_bind returned %d\n", ret);
return false;
}
return true;
}
bool SecureSock::Server::listen(cs ca_cert, bool require_client_auth) {
int ret;
if ((ret = mbedtls_ssl_config_defaults(&conf, MBEDTLS_SSL_IS_SERVER, MBEDTLS_SSL_TRANSPORT_STREAM,
MBEDTLS_SSL_PRESET_DEFAULT)) != 0) {
print_err1("[Crypt] mbedtls_ssl_config_defaults returned %d\n", ret);
return false;
}
if (require_client_auth) {
mbedtls_ssl_conf_authmode(&conf, MBEDTLS_SSL_VERIFY_REQUIRED);
mbedtls_ssl_conf_ca_chain(&conf, my_crypt->certificates[ca_cert], nullptr);
} else {
mbedtls_ssl_conf_authmode(&conf, MBEDTLS_SSL_VERIFY_OPTIONAL);
}
mbedtls_ssl_conf_rng(&conf, mbedtls_ctr_drbg_random, &my_crypt->ctr_drbg);
mbedtls_ssl_conf_dbg(&conf, my_debug, nullptr);
mbedtls_debug_set_threshold(4);
if ((ret = mbedtls_ssl_conf_own_cert(&conf, &my_crypt->my_cert, &my_crypt->my_private_key)) != 0) {
print_err1("[Crypt] mbedtls_ssl_conf_own_cert returned %d\n", ret);
return false;
}
return true;
}
int SecureSock::Server::accept() {
int ret = 0;
auto client = new SSClient;
mbedtls_ssl_init(&client->ssl);
mbedtls_net_init(&client->client_fd);
if ((ret = mbedtls_ssl_setup(&client->ssl, &conf)) != 0) {
print_err1("[Crypt] mbedtls_ssl_setup returned %d\n", ret);
} else if ((ret = mbedtls_net_accept(&listen_fd, &client->client_fd, nullptr, 0, nullptr)) != 0) {
print_err1("[Crypt] mbedtls_net_accept returned %d\n", ret);
} else {
mbedtls_ssl_set_bio(&client->ssl, &client->client_fd, mbedtls_net_send, mbedtls_net_recv, nullptr);
while ((ret = mbedtls_ssl_handshake(&client->ssl)) != 0) {
if (ret != MBEDTLS_ERR_SSL_WANT_READ && ret != MBEDTLS_ERR_SSL_WANT_WRITE) {
print_err1("[Crypt] mbedtls_ssl_handshake returned %d\n", ret);
my_crypt->print_internal_error(ret);
break;
}
}
// Todo: Confirm if looping is a threat
// if ((ret = mbedtls_ssl_handshake(&client->ssl)) != 0) {
// print_err1("[Crypt] mbedtls_ssl_handshake returned %d\n", ret);
// my_crypt->print_internal_error(ret);
// }
uint32_t flags;
if ((flags = mbedtls_ssl_get_verify_result(&client->ssl)) != 0) {
char vrfy_buf[512];
print_err1("[Crypt]");
mbedtls_x509_crt_verify_info(vrfy_buf, sizeof(vrfy_buf), " ", flags);
print_err1("%s\n", vrfy_buf);
}
}
if (ret != 0) {
mbedtls_ssl_free(&client->ssl);
mbedtls_net_free(&client->client_fd);
delete (client);
return -1;
}
sock_map[client->client_fd.fd] = client;
return client->client_fd.fd;
}
ssize_t SecureSock::Server::read(int fd, s msg, size_t count) {
int ret = 0;
auto client = sock_map[fd];
unsigned char buf[count];
memset(buf, 0, count);
ret = mbedtls_ssl_read(&client->ssl, buf, count);
if (ret == MBEDTLS_ERR_SSL_WANT_READ || ret == MBEDTLS_ERR_SSL_WANT_WRITE)
return -1;
if (ret <= 0) {
switch (ret) {
case MBEDTLS_ERR_SSL_PEER_CLOSE_NOTIFY:
print_err1(" connection was closed gracefully\n");
return 0;
case MBEDTLS_ERR_NET_CONN_RESET:
print_err1(" connection was reset by peer\n");
return 0;
default:
print_err1(" mbedtls_ssl_read returned -0x%x\n", -ret);
}
return ret == 0 ? 0 : -1;
}
msg.append(rcc(buf), static_cast<unsigned long>(ret));
return ret;
}
ssize_t SecureSock::Server::write(int fd, cs msg) {
int ret;
auto client = sock_map[fd];
// Todo: confirm if looping is a threat
while ((ret = mbedtls_ssl_write(&client->ssl, rccuc(msg.c_str()),
msg.length())) <= 0) {
if (ret == MBEDTLS_ERR_NET_CONN_RESET) {
print_err1("[Crypt] peer closed the connection\n");
return 0;
}
if (ret != MBEDTLS_ERR_SSL_WANT_READ && ret != MBEDTLS_ERR_SSL_WANT_WRITE) {
print_err1("[Crypt] mbedtls_ssl_write returned %d\n", ret);
return -1;
}
}
return ret;
}
bool SecureSock::Server::close(int fd) {
auto it = sock_map.find(fd);
if (it == sock_map.end()) return false;
int ret;
auto client = it->second;
while ((ret = mbedtls_ssl_close_notify(&client->ssl)) < 0) {
if (ret != MBEDTLS_ERR_SSL_WANT_READ && ret != MBEDTLS_ERR_SSL_WANT_WRITE) {
print_err1("[Crypt] mbedtls_ssl_close_notify returned %d\n", ret);
return false;
}
}
// Todo: Confirm if looping is a threat
// if ((ret = mbedtls_ssl_close_notify(&client->ssl)) < 0) {
// print_err1("[Crypt] mbedtls_ssl_close_notify returned %d\n", ret);
// return false;
// }
mbedtls_ssl_free(&client->ssl);
mbedtls_net_free(&client->client_fd);
delete (client);
sock_map.erase(fd);
return true;
}
bool SecureSock::Server::close() {
for (auto &pair:sock_map)
close(pair.first);
mbedtls_net_free(&listen_fd);
mbedtls_ssl_config_free(&conf);
return true;
}
bool SecureSock::Server::terminate() {
return true;
}
SecureSock::Client::Client(Crypt *crypt) {
my_crypt = crypt;
}
bool SecureSock::Client::init() {
mbedtls_net_init(&server_fd);
mbedtls_ssl_init(&ssl);
mbedtls_ssl_config_init(&conf);
return true;
}
bool SecureSock::Client::connect(cs hostname, cs server_location, int port,
cs ca_cert, bool require_client_auth) {
int ret = 0;
if ((ret = mbedtls_net_connect(&server_fd, server_location.c_str(), std::to_string(port).c_str(),
MBEDTLS_NET_PROTO_TCP)) != 0) {
print_err1("[Crypt] mbedtls_net_connect returned %d\n", ret);
close();
return false;
}
if ((ret = mbedtls_ssl_config_defaults(&conf, MBEDTLS_SSL_IS_CLIENT, MBEDTLS_SSL_TRANSPORT_STREAM,
MBEDTLS_SSL_PRESET_DEFAULT)) != 0) {
print_err1("[Crypt] mbedtls_ssl_config_defaults returned %d\n", ret);
close();
return false;
}
mbedtls_ssl_conf_authmode(&conf, MBEDTLS_SSL_VERIFY_REQUIRED);
mbedtls_ssl_conf_ca_chain(&conf, my_crypt->certificates[ca_cert], nullptr);
mbedtls_ssl_conf_rng(&conf, mbedtls_ctr_drbg_random, &my_crypt->ctr_drbg);
mbedtls_ssl_conf_dbg(&conf, my_debug, nullptr);
mbedtls_debug_set_threshold(4);
if (require_client_auth) {
if ((ret = mbedtls_ssl_conf_own_cert(&conf, &my_crypt->my_cert, &my_crypt->my_private_key)) != 0) {
print_err1("[Crypt] mbedtls_ssl_conf_own_cert returned %d\n", ret);
return false;
}
}
if ((ret = mbedtls_ssl_setup(&ssl, &conf)) != 0) {
print_err1("[Crypt] mbedtls_ssl_setup returned %d\n", ret);
close();
return false;
}
if ((ret = mbedtls_ssl_set_hostname(&ssl, hostname.c_str())) != 0) {
print_err1("[Crypt] mbedtls_ssl_set_hostname returned %d\n", ret);
close();
return false;
}
mbedtls_ssl_set_bio(&ssl, &server_fd, mbedtls_net_send, mbedtls_net_recv, nullptr);
while ((ret = mbedtls_ssl_handshake(&ssl)) != 0) {
if (ret != MBEDTLS_ERR_SSL_WANT_READ && ret != MBEDTLS_ERR_SSL_WANT_WRITE) {
print_err1("[Crypt] mbedtls_ssl_handshake returned -0x%x\n", -ret);
my_crypt->print_internal_error(ret);
close();
return false;
}
}
// Todo: Confirm if looping is a threat
// if ((ret = mbedtls_ssl_handshake(&ssl)) != 0) {
// print_err1("[Crypt] mbedtls_ssl_handshake returned -0x%x\n", -ret);
// my_crypt->print_internal_error(ret);
// close();
// return false;
// }
uint32_t flags;
if ((flags = mbedtls_ssl_get_verify_result(&ssl)) != 0) {
char vrfy_buf[512];
print_err1("[Crypt]");
mbedtls_x509_crt_verify_info(vrfy_buf, sizeof(vrfy_buf), " ", flags);
print_err1("%s\n", vrfy_buf);
return false;
}
return true;
}
ssize_t SecureSock::Client::read(s msg, size_t count) {
int ret;
unsigned char buf[count];
memset(buf, 0, count);
ret = mbedtls_ssl_read(&ssl, buf, count);
if (ret == MBEDTLS_ERR_SSL_WANT_READ || ret == MBEDTLS_ERR_SSL_WANT_WRITE)
return -1;
if (ret == MBEDTLS_ERR_SSL_PEER_CLOSE_NOTIFY)
return 0;
if (ret < 0) {
print_err1("[Crypt] mbedtls_ssl_read returned %d\n", ret);
return -1;
}
if (ret == 0) {
print_err1("\n\nEOF\n");
return 0;
}
msg.append(rcc(buf), static_cast<unsigned long>(ret));
return ret;
}
ssize_t SecureSock::Client::write(cs msg) {
int ret;
while ((ret = mbedtls_ssl_write(&ssl, rccuc(msg.c_str()), msg.length())) <= 0) {
if (ret == MBEDTLS_ERR_NET_CONN_RESET) {
print_err1("[Crypt] peer closed the connection\n");
return 0;
}
if (ret != MBEDTLS_ERR_SSL_WANT_READ && ret != MBEDTLS_ERR_SSL_WANT_WRITE) {
print_err1("[Crypt] mbedtls_ssl_write returned %d\n", ret);
return -1;
}
}
return ret;
}
bool SecureSock::Client::close() {
mbedtls_ssl_close_notify(&ssl);
mbedtls_net_free(&server_fd);
mbedtls_ssl_free(&ssl);
mbedtls_ssl_config_free(&conf);
return true;
}
bool SecureSock::Client::terminate() {
return false;
}
| 32.985472 | 126 | 0.62545 |
2140e3c5363de17751581b959591bd74662371a7 | 11,246 | cpp | C++ | implementations/ugene/src/plugins/enzymes/src/EnzymesPlugin.cpp | r-barnes/sw_comparison | 1ac2c9cc10a32badd6b8fb1e96516c97f7800176 | [
"BSD-Source-Code"
] | null | null | null | implementations/ugene/src/plugins/enzymes/src/EnzymesPlugin.cpp | r-barnes/sw_comparison | 1ac2c9cc10a32badd6b8fb1e96516c97f7800176 | [
"BSD-Source-Code"
] | null | null | null | implementations/ugene/src/plugins/enzymes/src/EnzymesPlugin.cpp | r-barnes/sw_comparison | 1ac2c9cc10a32badd6b8fb1e96516c97f7800176 | [
"BSD-Source-Code"
] | null | null | null | /**
* UGENE - Integrated Bioinformatics Tools.
* Copyright (C) 2008-2020 UniPro <ugene@unipro.ru>
* http://ugene.net
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation; either version 2
* of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
* MA 02110-1301, USA.
*/
#include "EnzymesPlugin.h"
#include <QDir>
#include <QMenu>
#include <QMessageBox>
#include <U2Core/AnnotationSelection.h>
#include <U2Core/AppContext.h>
#include <U2Core/AutoAnnotationsSupport.h>
#include <U2Core/DNAAlphabet.h>
#include <U2Core/GAutoDeleteList.h>
#include <U2Core/QObjectScopedPointer.h>
#include <U2Gui/DialogUtils.h>
#include <U2Gui/GUIUtils.h>
#include <U2Gui/MainWindow.h>
#include <U2Gui/ToolsMenu.h>
#include <U2Test/GTestFrameworkComponents.h>
#include <U2View/ADVConstants.h>
#include <U2View/ADVSequenceObjectContext.h>
#include <U2View/ADVSequenceWidget.h>
#include <U2View/ADVUtils.h>
#include <U2View/AnnotatedDNAView.h>
#include "ConstructMoleculeDialog.h"
#include "CreateFragmentDialog.h"
#include "DigestSequenceDialog.h"
#include "EnzymesQuery.h"
#include "EnzymesTests.h"
#include "FindEnzymesDialog.h"
#include "FindEnzymesTask.h"
const QString CREATE_PCR_PRODUCT_ACTION_NAME = "Create PCR product";
namespace U2 {
extern "C" Q_DECL_EXPORT Plugin *U2_PLUGIN_INIT_FUNC() {
EnzymesPlugin *plug = new EnzymesPlugin();
return plug;
}
EnzymesPlugin::EnzymesPlugin()
: Plugin(tr("Restriction analysis"), tr("Finds and annotates restriction sites on a DNA sequence.")), ctxADV(NULL) {
if (AppContext::getMainWindow()) {
createToolsMenu();
QList<QAction *> actions;
actions.append(openDigestSequenceDialog);
actions.append(openConstructMoleculeDialog);
actions.append(openCreateFragmentDialog);
ctxADV = new EnzymesADVContext(this, actions);
ctxADV->init();
AppContext::getAutoAnnotationsSupport()->registerAutoAnnotationsUpdater(new FindEnzymesAutoAnnotationUpdater());
}
EnzymesSelectorWidget::setupSettings();
FindEnzymesDialog::initDefaultSettings();
GTestFormatRegistry *tfr = AppContext::getTestFramework()->getTestFormatRegistry();
XMLTestFormat *xmlTestFormat = qobject_cast<XMLTestFormat *>(tfr->findFormat("XML"));
assert(xmlTestFormat != NULL);
QDActorPrototypeRegistry *qdpr = AppContext::getQDActorProtoRegistry();
qdpr->registerProto(new QDEnzymesActorPrototype());
GAutoDeleteList<XMLTestFactory> *l = new GAutoDeleteList<XMLTestFactory>(this);
l->qlist = EnzymeTests::createTestFactories();
foreach (XMLTestFactory *f, l->qlist) {
bool res = xmlTestFormat->registerTestFactory(f);
assert(res);
Q_UNUSED(res);
}
}
void EnzymesPlugin::createToolsMenu() {
openDigestSequenceDialog = new QAction(tr("Digest into fragments..."), this);
openDigestSequenceDialog->setObjectName(ToolsMenu::CLONING_FRAGMENTS);
openConstructMoleculeDialog = new QAction(tr("Construct molecule..."), this);
openConstructMoleculeDialog->setObjectName(ToolsMenu::CLONING_CONSTRUCT);
openCreateFragmentDialog = new QAction(tr("Create fragment..."), this);
openCreateFragmentDialog->setObjectName("Create Fragment");
connect(openDigestSequenceDialog, SIGNAL(triggered()), SLOT(sl_onOpenDigestSequenceDialog()));
connect(openConstructMoleculeDialog, SIGNAL(triggered()), SLOT(sl_onOpenConstructMoleculeDialog()));
connect(openCreateFragmentDialog, SIGNAL(triggered()), SLOT(sl_onOpenCreateFragmentDialog()));
ToolsMenu::addAction(ToolsMenu::CLONING_MENU, openDigestSequenceDialog);
ToolsMenu::addAction(ToolsMenu::CLONING_MENU, openConstructMoleculeDialog);
}
void EnzymesPlugin::sl_onOpenDigestSequenceDialog() {
GObjectViewWindow *w = GObjectViewUtils::getActiveObjectViewWindow();
if (w == NULL) {
QMessageBox::information(QApplication::activeWindow(), openDigestSequenceDialog->text(), tr("There is no active sequence object.\nTo start partition open sequence document."));
return;
}
AnnotatedDNAView *view = qobject_cast<AnnotatedDNAView *>(w->getObjectView());
if (view == NULL) {
QMessageBox::information(QApplication::activeWindow(), openDigestSequenceDialog->text(), tr("There is no active sequence object.\nTo start partition open sequence document."));
return;
}
if (!view->getSequenceInFocus()->getSequenceObject()->getAlphabet()->isNucleic()) {
QMessageBox::information(QApplication::activeWindow(), openDigestSequenceDialog->text(), tr("Can not digest into fragments non-nucleic sequence."));
return;
}
QObjectScopedPointer<DigestSequenceDialog> dlg = new DigestSequenceDialog(view->getSequenceInFocus(), QApplication::activeWindow());
dlg->exec();
}
void EnzymesPlugin::sl_onOpenCreateFragmentDialog() {
GObjectViewWindow *w = GObjectViewUtils::getActiveObjectViewWindow();
if (w == NULL) {
QMessageBox::information(QApplication::activeWindow(), openCreateFragmentDialog->text(), tr("There is no active sequence object.\nTo create fragment open sequence document."));
return;
}
AnnotatedDNAView *view = qobject_cast<AnnotatedDNAView *>(w->getObjectView());
if (view == NULL) {
QMessageBox::information(QApplication::activeWindow(), openCreateFragmentDialog->text(), tr("There is no active sequence object.\nTo create fragment open sequence document."));
return;
}
U2SequenceObject *dnaObj = view->getSequenceInFocus()->getSequenceObject();
assert(dnaObj != NULL);
if (!dnaObj->getAlphabet()->isNucleic()) {
QMessageBox::information(QApplication::activeWindow(), openCreateFragmentDialog->text(), tr("The sequence doesn't have nucleic alphabet, it can not be used in cloning."));
return;
}
QObjectScopedPointer<CreateFragmentDialog> dlg = new CreateFragmentDialog(view->getSequenceInFocus(), QApplication::activeWindow());
dlg->exec();
}
void EnzymesPlugin::sl_onOpenConstructMoleculeDialog() {
Project *p = AppContext::getProject();
if (p == NULL) {
QMessageBox::information(QApplication::activeWindow(), openConstructMoleculeDialog->text(), tr("There is no active project.\nTo start ligation create a project or open an existing."));
return;
}
QList<DNAFragment> fragments = DNAFragment::findAvailableFragments();
QObjectScopedPointer<ConstructMoleculeDialog> dlg = new ConstructMoleculeDialog(fragments, QApplication::activeWindow());
dlg->exec();
}
//////////////////////////////////////////////////////////////////////////
EnzymesADVContext::EnzymesADVContext(QObject *p, const QList<QAction *> &actions)
: GObjectViewWindowContext(p, ANNOTATED_DNA_VIEW_FACTORY_ID), cloningActions(actions) {
}
void EnzymesADVContext::initViewContext(GObjectView *view) {
AnnotatedDNAView *av = qobject_cast<AnnotatedDNAView *>(view);
ADVGlobalAction *a = new ADVGlobalAction(av, QIcon(":enzymes/images/enzymes.png"), tr("Find restriction sites..."), 50);
a->setObjectName("Find restriction sites");
a->addAlphabetFilter(DNAAlphabet_NUCL);
connect(a, SIGNAL(triggered()), SLOT(sl_search()));
GObjectViewAction *createPCRProductAction = new GObjectViewAction(av, av, tr("Create PCR product..."));
createPCRProductAction->setObjectName(CREATE_PCR_PRODUCT_ACTION_NAME);
connect(createPCRProductAction, SIGNAL(triggered()), SLOT(sl_createPCRProduct()));
addViewAction(createPCRProductAction);
}
void EnzymesADVContext::sl_search() {
GObjectViewAction *action = qobject_cast<GObjectViewAction *>(sender());
assert(action != NULL);
AnnotatedDNAView *av = qobject_cast<AnnotatedDNAView *>(action->getObjectView());
assert(av != NULL);
ADVSequenceObjectContext *seqCtx = av->getSequenceInFocus();
assert(seqCtx->getAlphabet()->isNucleic());
QObjectScopedPointer<FindEnzymesDialog> d = new FindEnzymesDialog(seqCtx);
d->exec();
}
// TODO: move definitions to core
#define PRIMER_ANNOTATION_GROUP_NAME "pair"
#define PRIMER_ANNOTATION_NAME "primer"
void EnzymesADVContext::buildMenu(GObjectView *v, QMenu *m) {
AnnotatedDNAView *av = qobject_cast<AnnotatedDNAView *>(v);
SAFE_POINT(NULL != av, "Invalid sequence view", );
CHECK(av->getSequenceInFocus()->getAlphabet()->isNucleic(), );
QMenu *cloningMenu = new QMenu(tr("Cloning"), m);
cloningMenu->menuAction()->setObjectName("Cloning");
cloningMenu->addActions(cloningActions);
QAction *exportMenuAction = GUIUtils::findAction(m->actions(), ADV_MENU_EXPORT);
m->insertMenu(exportMenuAction, cloningMenu);
if (!av->getAnnotationsSelection()->getAnnotations().isEmpty()) {
Annotation *a = av->getAnnotationsSelection()->getAnnotations().first();
const QString annName = a->getName();
const QString groupName = a->getGroup()->getName();
const int annCount = a->getGroup()->getAnnotations().size();
if (annName == PRIMER_ANNOTATION_NAME && groupName.startsWith(PRIMER_ANNOTATION_GROUP_NAME) && 2 == annCount) {
QAction *a = findViewAction(v, CREATE_PCR_PRODUCT_ACTION_NAME);
SAFE_POINT(NULL != a, "Invalid menu action", );
cloningMenu->addAction(a);
}
}
}
void EnzymesADVContext::sl_createPCRProduct() {
GObjectViewAction *action = qobject_cast<GObjectViewAction *>(sender());
SAFE_POINT(action != NULL, "Invalid action object!", );
AnnotatedDNAView *av = qobject_cast<AnnotatedDNAView *>(action->getObjectView());
SAFE_POINT(av != NULL, "Invalid DNA view!", );
const QList<Annotation *> &annotations = av->getAnnotationsSelection()->getAnnotations();
CHECK(!annotations.isEmpty(), )
Annotation *a = annotations.first();
AnnotationGroup *group = a->getGroup();
if (group->getName().startsWith(PRIMER_ANNOTATION_GROUP_NAME)) {
SAFE_POINT(group->getAnnotations().size() == 2, "Invalid selected annotation count!", );
Annotation *a1 = group->getAnnotations().at(0);
Annotation *a2 = group->getAnnotations().at(1);
int startPos = a1->getLocation()->regions.at(0).startPos;
SAFE_POINT(a2->getLocation()->strand == U2Strand::Complementary, "Invalid annotation's strand!", );
int endPos = a2->getLocation()->regions.at(0).endPos();
U2SequenceObject *seqObj = av->getSequenceInFocus()->getSequenceObject();
U2Region region(startPos, endPos - startPos);
QObjectScopedPointer<CreateFragmentDialog> dlg = new CreateFragmentDialog(seqObj, region, av->getSequenceWidgetInFocus());
dlg->setWindowTitle("Create PCR product");
dlg->exec();
}
}
} // namespace U2
| 41.962687 | 192 | 0.719811 |
2144d745cb7793cdcf3192ce282aa7c44d78366f | 1,027 | cpp | C++ | src/terminal/MockTerm.cpp | dandycheung/contour | 1364ec488def8a0494503b9879b370b3669e81f9 | [
"Apache-2.0"
] | 404 | 2021-07-01T11:38:20.000Z | 2022-03-31T19:16:18.000Z | src/terminal/MockTerm.cpp | dandycheung/contour | 1364ec488def8a0494503b9879b370b3669e81f9 | [
"Apache-2.0"
] | 204 | 2021-07-01T10:10:01.000Z | 2022-03-26T09:46:05.000Z | src/terminal/MockTerm.cpp | dandycheung/contour | 1364ec488def8a0494503b9879b370b3669e81f9 | [
"Apache-2.0"
] | 38 | 2019-09-27T19:53:37.000Z | 2021-07-01T09:47:44.000Z | /**
* This file is part of the "libterminal" project
* Copyright (c) 2019-2020 Christian Parpart <christian@parpart.family>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
*
* 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 <terminal/MockTerm.h>
#include <terminal/Screen.h>
#include <crispy/App.h>
#include <cstdlib>
namespace terminal
{
MockTerm::MockTerm(PageSize _size, LineCount _hist): screen(_size, *this, false, false, _hist)
{
char const* logFilterString = getenv("LOG");
if (logFilterString)
{
logstore::configure(logFilterString);
crispy::App::customizeLogStoreOutput();
}
}
} // namespace terminal
| 28.527778 | 94 | 0.723466 |
2149bb38100acbec14d976cefb541cbbc261dddf | 3,832 | cpp | C++ | tests/iclBLAS/test_Icamin.cpp | intel/clGPU | bf099c547a17d12a81c23314a54fc7fe175a86a7 | [
"Apache-2.0"
] | 61 | 2018-02-20T06:01:50.000Z | 2021-09-08T05:55:44.000Z | tests/iclBLAS/test_Icamin.cpp | intel/clGPU | bf099c547a17d12a81c23314a54fc7fe175a86a7 | [
"Apache-2.0"
] | 2 | 2018-04-21T06:59:30.000Z | 2019-01-12T17:08:54.000Z | tests/iclBLAS/test_Icamin.cpp | intel/clGPU | bf099c547a17d12a81c23314a54fc7fe175a86a7 | [
"Apache-2.0"
] | 19 | 2018-02-19T17:18:04.000Z | 2021-02-25T02:00:53.000Z | // Copyright (c) 2017-2018 Intel Corporation
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#include <gtest/gtest.h>
#include <iclBLAS.h>
TEST(Icamin, naive)
{
const int n = 128;
const int incx = 1;
oclComplex_t x[n * incx];
for (int i = 0; i < n; ++i)
{
x[i] = { i + 100.f, i + 100.f };
}
x[55] = { -55.f, -55.f};
x[88] = { -55.f, -55.f};
x[99] = { -55.f, -55.f};
int result[1] = { 0 };
int ref = 55;
iclblasHandle_t handle;
iclblasStatus_t status = ICLBLAS_STATUS_SUCCESS;
status = iclblasCreate(&handle);
ASSERT_EQ(status, ICLBLAS_STATUS_SUCCESS);
status = iclblasIcamin(handle, n, x, incx, result);
ASSERT_EQ(status, ICLBLAS_STATUS_SUCCESS);
status = iclblasDestroy(handle);
ASSERT_EQ(status, ICLBLAS_STATUS_SUCCESS);
EXPECT_EQ(ref, *result);
}
TEST(Icamin, opt_simd16)
{
const int n = 4096;
const int incx = 1;
oclComplex_t x[n * incx];
for (int i = 0; i < n * incx; ++i)
{
x[i] = { i + 100.f, i + 100.f };
}
x[56] = { -55.f, -55.f};
x[88] = { -55.f, -55.f}; //Should omitt, lowest value but higher index
x[99] = { -55.f, -55.f}; //Should omitt this lowest value as incx is 2
int result[1] = { 0 };
int ref = 56 / incx;
iclblasHandle_t handle;
iclblasStatus_t status = ICLBLAS_STATUS_SUCCESS;
status = iclblasCreate(&handle);
ASSERT_EQ(status, ICLBLAS_STATUS_SUCCESS);
status = iclblasIcamin(handle, n, x, incx, result);
ASSERT_EQ(status, ICLBLAS_STATUS_SUCCESS);
status = iclblasDestroy(handle);
ASSERT_EQ(status, ICLBLAS_STATUS_SUCCESS);
EXPECT_EQ(ref, *result);
}
TEST(Icamin, opt_simd16_incx)
{
const int n = 4096;
const int incx = 2;
oclComplex_t x[n * incx];
for (int i = 0; i < n * incx; ++i)
{
x[i] = { i + 100.f, i + 100.f };
}
x[55] = { -25.f, -25.f }; //Should omitt this lowest value as incx is 2
x[56] = { -55.f, -55.f };
x[88] = { -55.f, -55.f }; //Should omitt, lowest value but higher index
x[99] = { -55.f, -55.f }; //Should omitt this lowest value as incx is 2
int result[1] = { 0 };
int ref = 56 / incx;
iclblasHandle_t handle;
iclblasStatus_t status = ICLBLAS_STATUS_SUCCESS;
status = iclblasCreate(&handle);
ASSERT_EQ(status, ICLBLAS_STATUS_SUCCESS);
status = iclblasIcamin(handle, n, x, incx, result);
ASSERT_EQ(status, ICLBLAS_STATUS_SUCCESS);
status = iclblasDestroy(handle);
ASSERT_EQ(status, ICLBLAS_STATUS_SUCCESS);
EXPECT_EQ(ref, *result);
}
TEST(Icamin, opt_simd16_2stage)
{
const int n = 80000;
const int incx = 1;
oclComplex_t x[n * incx];
for (int i = 0; i < n * incx; ++i)
{
x[i] = { i + 100.f, i + 100.f };
}
x[555] = {-20.f, -20.f};
x[1111] = {-20.f, -20.f};
x[79999] = {-20.f, -20.f};
int result[1] = { 0 };
int ref = 555;
iclblasHandle_t handle;
iclblasStatus_t status = ICLBLAS_STATUS_SUCCESS;
status = iclblasCreate(&handle);
ASSERT_EQ(status, ICLBLAS_STATUS_SUCCESS);
status = iclblasIcamin(handle, n, x, incx, result);
ASSERT_EQ(status, ICLBLAS_STATUS_SUCCESS);
status = iclblasDestroy(handle);
ASSERT_EQ(status, ICLBLAS_STATUS_SUCCESS);
EXPECT_EQ(ref, *result);
}
| 23.084337 | 75 | 0.615605 |
214b8ca98d0ead4be58052703f42634928e0f03d | 876 | cpp | C++ | android-31/javax/crypto/spec/GCMParameterSpec.cpp | YJBeetle/QtAndroidAPI | 1468b5dc6eafaf7709f0b00ba1a6ec2b70684266 | [
"Apache-2.0"
] | 12 | 2020-03-26T02:38:56.000Z | 2022-03-14T08:17:26.000Z | android-31/javax/crypto/spec/GCMParameterSpec.cpp | YJBeetle/QtAndroidAPI | 1468b5dc6eafaf7709f0b00ba1a6ec2b70684266 | [
"Apache-2.0"
] | 1 | 2021-01-27T06:07:45.000Z | 2021-11-13T19:19:43.000Z | android-29/javax/crypto/spec/GCMParameterSpec.cpp | YJBeetle/QtAndroidAPI | 1468b5dc6eafaf7709f0b00ba1a6ec2b70684266 | [
"Apache-2.0"
] | 3 | 2021-02-02T12:34:55.000Z | 2022-03-08T07:45:57.000Z | #include "../../../JByteArray.hpp"
#include "./GCMParameterSpec.hpp"
namespace javax::crypto::spec
{
// Fields
// QJniObject forward
GCMParameterSpec::GCMParameterSpec(QJniObject obj) : JObject(obj) {}
// Constructors
GCMParameterSpec::GCMParameterSpec(jint arg0, JByteArray arg1)
: JObject(
"javax.crypto.spec.GCMParameterSpec",
"(I[B)V",
arg0,
arg1.object<jbyteArray>()
) {}
GCMParameterSpec::GCMParameterSpec(jint arg0, JByteArray arg1, jint arg2, jint arg3)
: JObject(
"javax.crypto.spec.GCMParameterSpec",
"(I[BII)V",
arg0,
arg1.object<jbyteArray>(),
arg2,
arg3
) {}
// Methods
JByteArray GCMParameterSpec::getIV() const
{
return callObjectMethod(
"getIV",
"()[B"
);
}
jint GCMParameterSpec::getTLen() const
{
return callMethod<jint>(
"getTLen",
"()I"
);
}
} // namespace javax::crypto::spec
| 19.043478 | 85 | 0.660959 |
214e9f5ce6327bebe9d5b15be003ba8b0ab70867 | 565 | cpp | C++ | 2019-06/5 - Range generators.cpp | st-louis-cpp-meetup/Presentations | 2e3a31a6285aabf295a9bf494bf7470844196857 | [
"CC-BY-4.0"
] | 2 | 2019-06-20T13:22:30.000Z | 2020-03-05T01:19:19.000Z | 2019-06/5 - Range generators.cpp | st-louis-cpp-meetup/Presentations | 2e3a31a6285aabf295a9bf494bf7470844196857 | [
"CC-BY-4.0"
] | null | null | null | 2019-06/5 - Range generators.cpp | st-louis-cpp-meetup/Presentations | 2e3a31a6285aabf295a9bf494bf7470844196857 | [
"CC-BY-4.0"
] | null | null | null | //-std=c++2a -I/opt/compiler-explorer/libs/cmcstl2/include -fconcepts
#include <iostream>
#include <experimental/ranges/ranges> // from cmcstl2
namespace ranges = std::experimental::ranges;
namespace view = std::experimental::ranges::view;
//range generators (range adaptors)
int main() {
auto count_to_10 = view::iota(1, 11);
auto one_int = view::single(37);
auto no_ints = view::empty<int>;
auto infinite_count = view::iota(1);
auto only1234 = view::counted(infinite_count.begin(), 4);
for (int x: count_to_10) {
std::cout << x << " ";
}
}
| 28.25 | 69 | 0.684956 |
2152b04ecd089a71683f2dc143d9592c6998b5ec | 24,300 | cpp | C++ | plugins/protein/src/ToonRendererDeferred.cpp | reinago/megamol | 0438e26e5134a0050a00c6d8d747175a08f85fd9 | [
"BSD-3-Clause"
] | null | null | null | plugins/protein/src/ToonRendererDeferred.cpp | reinago/megamol | 0438e26e5134a0050a00c6d8d747175a08f85fd9 | [
"BSD-3-Clause"
] | null | null | null | plugins/protein/src/ToonRendererDeferred.cpp | reinago/megamol | 0438e26e5134a0050a00c6d8d747175a08f85fd9 | [
"BSD-3-Clause"
] | null | null | null | /*
* ToonRendererDeferred.cpp
*
* Copyright (C) 2011 by Universitaet Stuttgart (VISUS).
* All rights reserved.
*/
#include "stdafx.h"
#include "mmcore/param/EnumParam.h"
#include "mmcore/param/BoolParam.h"
#include "mmcore/param/IntParam.h"
#include "mmcore/param/FloatParam.h"
#include "mmcore/view/CallRender3D.h"
#include "mmcore/view/CallRenderDeferred3D.h"
#include "mmcore/CoreInstance.h"
#include "vislib/graphics/gl/ShaderSource.h"
#include "mmcore/utility/log/Log.h"
#include "ToonRendererDeferred.h"
#include "vislib/graphics/gl/IncludeAllGL.h"
using namespace megamol::protein;
/*
* ToonRendererDeferred::ToonRendererDeferred
*/
ToonRendererDeferred::ToonRendererDeferred(void)
: megamol::core::view::AbstractRendererDeferred3D(),
threshFineLinesParam("linesFine", "Threshold for fine silhouette."),
threshCoarseLinesParam("linesCoarse", "Threshold for coarse silhouette."),
ssaoParam("toggleSSAO", "Toggle Screen Space Ambient Occlusion."),
ssaoRadiusParam("ssaoRadius", "Radius for SSAO samples."),
illuminationParam("illumination", "Change local lighting."),
colorParam("toggleColor", "Toggle coloring."),
widthFBO(-1), heightFBO(-1) {
// Threshold for fine lines
this->threshFineLinesParam << new megamol::core::param::FloatParam(9.5f, 0.0f, 9.95f);
this->MakeSlotAvailable(&this->threshFineLinesParam);
// Threshold for coarse lines
this->threshCoarseLinesParam << new megamol::core::param::FloatParam(7.9f, 0.0f, 9.95f);
this->MakeSlotAvailable(&this->threshCoarseLinesParam);
// Toggle SSAO
this->ssaoParam << new megamol::core::param::BoolParam(false);
this->MakeSlotAvailable(&this->ssaoParam);
// Toggle local lighting
megamol::core::param::EnumParam *illuParam =
new megamol::core::param::EnumParam(0);
illuParam->SetTypePair(0, "None");
illuParam->SetTypePair(1, "Phong-Shading");
illuParam->SetTypePair(2, "Toon-Shading");
this->illuminationParam << illuParam;
this->MakeSlotAvailable(&illuminationParam);
// Toggle coloring
this->colorParam << new megamol::core::param::BoolParam(false);
this->MakeSlotAvailable(&this->colorParam);
// SSAO radius param
this->ssaoRadiusParam << new megamol::core::param::FloatParam(1.0, 0.0);
this->MakeSlotAvailable(&this->ssaoRadiusParam);
}
/*
* ToonRendererDeferred::create
*/
bool ToonRendererDeferred::create(void) {
vislib::graphics::gl::ShaderSource vertSrc;
vislib::graphics::gl::ShaderSource fragSrc;
// Init random number generator
srand((unsigned)time(0));
// Create 4x4-texture with random rotation vectors
if(!this->createRandomRotSampler()) {
return false;
}
// Create sampling kernel
if(!this->createRandomKernel(16)) {
return false;
}
megamol::core::CoreInstance *ci = this->GetCoreInstance();
if(!ci) {
return false;
}
if(!areExtsAvailable("GL_EXT_framebuffer_object GL_ARB_draw_buffers")) {
return false;
}
if(!vislib::graphics::gl::GLSLShader::InitialiseExtensions()) {
return false;
}
if(!isExtAvailable("GL_ARB_texture_non_power_of_two")) return false;
// Try to load the gradient shader
if(!ci->ShaderSourceFactory().MakeShaderSource("proteinDeferred::sobel::vertex", vertSrc)) {
megamol::core::utility::log::Log::DefaultLog.WriteMsg(megamol::core::utility::log::Log::LEVEL_ERROR,
"%s: Unable to load gradient vertex shader source", this->ClassName() );
return false;
}
if(!ci->ShaderSourceFactory().MakeShaderSource("proteinDeferred::sobel::fragment", fragSrc)) {
megamol::core::utility::log::Log::DefaultLog.WriteMsg(megamol::core::utility::log::Log::LEVEL_ERROR,
"%s: Unable to load gradient fragment shader source", this->ClassName() );
return false;
}
try {
if(!this->sobelShader.Create(vertSrc.Code(), vertSrc.Count(), fragSrc.Code(), fragSrc.Count()))
throw vislib::Exception("Generic creation failure", __FILE__, __LINE__);
}
catch(vislib::Exception &e){
megamol::core::utility::log::Log::DefaultLog.WriteMsg(megamol::core::utility::log::Log::LEVEL_ERROR,
"%s: Unable to create shader: %s\n", this->ClassName(), e.GetMsgA());
return false;
}
// Try to load the ssao shader
if(!ci->ShaderSourceFactory().MakeShaderSource("proteinDeferred::ssao::vertex", vertSrc)) {
megamol::core::utility::log::Log::DefaultLog.WriteMsg(megamol::core::utility::log::Log::LEVEL_ERROR,
"%s: Unable to load gradient vertex shader source", this->ClassName() );
return false;
}
if(!ci->ShaderSourceFactory().MakeShaderSource("proteinDeferred::ssao::fragment", fragSrc)) {
megamol::core::utility::log::Log::DefaultLog.WriteMsg(megamol::core::utility::log::Log::LEVEL_ERROR,
"%s: Unable to load gradient fragment shader source", this->ClassName() );
return false;
}
try {
if(!this->ssaoShader.Create(vertSrc.Code(), vertSrc.Count(), fragSrc.Code(), fragSrc.Count()))
throw vislib::Exception("Generic creation failure", __FILE__, __LINE__);
}
catch(vislib::Exception &e){
megamol::core::utility::log::Log::DefaultLog.WriteMsg(megamol::core::utility::log::Log::LEVEL_ERROR,
"%s: Unable to create shader: %s\n", this->ClassName(), e.GetMsgA());
return false;
}
// Try to load the toon shader
if(!ci->ShaderSourceFactory().MakeShaderSource("proteinDeferred::toon::vertex", vertSrc)) {
megamol::core::utility::log::Log::DefaultLog.WriteMsg(megamol::core::utility::log::Log::LEVEL_ERROR,
"%s: Unable to load toon vertex shader source", this->ClassName() );
return false;
}
if(!ci->ShaderSourceFactory().MakeShaderSource("proteinDeferred::toon::fragment", fragSrc)) {
megamol::core::utility::log::Log::DefaultLog.WriteMsg(megamol::core::utility::log::Log::LEVEL_ERROR,
"%s: Unable to load toon fragment shader source", this->ClassName() );
return false;
}
try {
if(!this->toonShader.Create(vertSrc.Code(), vertSrc.Count(), fragSrc.Code(), fragSrc.Count()))
throw vislib::Exception("Generic creation failure", __FILE__, __LINE__);
}
catch(vislib::Exception &e){
megamol::core::utility::log::Log::DefaultLog.WriteMsg(megamol::core::utility::log::Log::LEVEL_ERROR,
"%s: Unable to create shader: %s\n", this->ClassName(), e.GetMsgA());
return false;
}
return true;
}
/*
* ToonRendererDeferred::release
*/
void ToonRendererDeferred::release(void) {
this->toonShader.Release();
this->sobelShader.Release();
this->ssaoShader.Release();
glDeleteTextures(1, &this->colorBuffer);
glDeleteTextures(1, &this->normalBuffer);
glDeleteTextures(1, &this->gradientBuffer);
glDeleteTextures(1, &this->depthBuffer);
glDeleteTextures(1, &this->ssaoBuffer);
glDeleteTextures(1, &this->randomKernel);
glDeleteTextures(1, &this->rotationSampler);
glDeleteFramebuffers(1, &this->fbo);
}
/*
* ToonRendererDeferred::~ToonRendererDeferred
*/
ToonRendererDeferred::~ToonRendererDeferred(void) {
this->Release();
}
/*
* ToonRendererDeferred::GetExtents
*/
bool ToonRendererDeferred::GetExtents(megamol::core::Call& call) {
megamol::core::view::CallRender3D *crIn =
dynamic_cast< megamol::core::view::CallRender3D*>(&call);
if(crIn == NULL) return false;
megamol::core::view:: CallRenderDeferred3D *crOut =
this->rendererSlot.CallAs< megamol::core::view::CallRenderDeferred3D>();
if(crOut == NULL) return false;
// Call for getExtends
if(!(*crOut)(core::view::AbstractCallRender::FnGetExtents)) return false;
// Set extends of for incoming render call
crIn->AccessBoundingBoxes() = crOut->GetBoundingBoxes();
crIn->SetLastFrameTime(crOut->LastFrameTime());
crIn->SetTimeFramesCount(crOut->TimeFramesCount());
return true;
}
/*
* ToonRendererDeferred::Render
*/
bool ToonRendererDeferred::Render(megamol::core::Call& call) {
if(!updateParams()) return false;
megamol::core::view::CallRender3D *crIn =
dynamic_cast< megamol::core::view::CallRender3D*>(&call);
if(crIn == NULL) return false;
megamol::core::view::CallRenderDeferred3D *crOut =
this->rendererSlot.CallAs< megamol::core::view::CallRenderDeferred3D>();
if(crOut == NULL) return false;
crOut->SetCameraParameters(crIn->GetCameraParameters());
// Set call time
crOut->SetTime(crIn->Time());
float curVP[4];
glGetFloatv(GL_VIEWPORT, curVP);
vislib::math::Vector<float, 3> ray(0, 0,-1);
vislib::math::Vector<float, 3> up(0, 1, 0);
vislib::math::Vector<float, 3> right(1, 0, 0);
up *= sinf(crIn->GetCameraParameters()->HalfApertureAngle());
right *= sinf(crIn->GetCameraParameters()->HalfApertureAngle())
* curVP[2] / curVP[3];
// Recreate FBO if necessary
if((curVP[2] != this->widthFBO) || (curVP[3] != this->heightFBO)) {
if(!this->createFBO(static_cast<UINT>(curVP[2]), static_cast<UINT>(curVP[3]))) {
return false;
}
this->widthFBO = (int)curVP[2];
this->heightFBO = (int)curVP[3];
}
/// 1. Offscreen rendering ///
// Enable rendering to FBO
glBindFramebufferEXT(GL_FRAMEBUFFER, this->fbo);
// Enable rendering to color attachents 0 and 1
GLenum mrt[] = {GL_COLOR_ATTACHMENT0, GL_COLOR_ATTACHMENT1};
glDrawBuffers(2, mrt);
glFramebufferTexture2DEXT(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D, this->colorBuffer, 0);
glFramebufferTexture2DEXT(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT1, GL_TEXTURE_2D, this->normalBuffer, 0);
glFramebufferTexture2DEXT(GL_FRAMEBUFFER, GL_DEPTH_ATTACHMENT, GL_TEXTURE_2D, this->depthBuffer, 0);
glClearColor(0.0f, 0.0f, 0.0f, 0.0f);
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
// Call for render
(*crOut)(core::view::AbstractCallRender::FnRender);
// Detach texture that are not needed anymore
glFramebufferTexture2DEXT(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D, 0, 0);
glFramebufferTexture2DEXT(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT1, GL_TEXTURE_2D, 0, 0);
glFramebufferTexture2DEXT(GL_FRAMEBUFFER, GL_DEPTH_ATTACHMENT, GL_TEXTURE_2D, 0, 0);
// Prepare rendering screen quad
glMatrixMode(GL_MODELVIEW);
glPushMatrix();
glLoadIdentity();
glMatrixMode(GL_PROJECTION);
glPushMatrix();
glLoadIdentity();
glEnable(GL_TEXTURE_2D);
glDisable(GL_DEPTH_TEST);
/// 2. Calculate gradient using the sobel operator ///
GLenum mrt2[] = {GL_COLOR_ATTACHMENT0};
glDrawBuffers(1, mrt2);
glDepthMask(GL_FALSE); // Disable writing to depth buffer
// Attach gradient texture
glFramebufferTexture2DEXT(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D, this->gradientBuffer, 0);
this->sobelShader.Enable();
glUniform1i(this->sobelShader.ParameterLocation("depthBuffer"), 0);
// Bind depth texture
glActiveTexture(GL_TEXTURE0);
glBindTexture(GL_TEXTURE_2D, this->depthBuffer); // Depth buffer
// Draw
glBegin(GL_QUADS);
glTexCoord2f(0, 0); glVertex2f(-1.0f, -1.0f);
glTexCoord2f(1, 0); glVertex2f(1.0f, -1.0f);
glTexCoord2f(1, 1); glVertex2f(1.0f, 1.0f);
glTexCoord2f(0, 1); glVertex2f(-1.0f, 1.0f);
glEnd();
this->sobelShader.Disable();
glBindTexture(GL_TEXTURE_2D, 0);
/// 3. Calculate ssao value if needed ///
if(this->ssaoParam.Param<core::param::BoolParam>()->Value()) {
// Attach ssao buffer
glFramebufferTexture2DEXT(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D, this->ssaoBuffer, 0);
this->ssaoShader.Enable();
glUniform4f(this->ssaoShader.ParameterLocation("clip"),
crIn->GetCameraParameters()->NearClip(), // Near
crIn->GetCameraParameters()->FarClip(), // Far
tan(crIn->GetCameraParameters()->HalfApertureAngle()) * crIn->GetCameraParameters()->NearClip(), // Top
tan(crIn->GetCameraParameters()->HalfApertureAngle()) * crIn->GetCameraParameters()->NearClip() * curVP[2] / curVP[3]); // Right
glUniform2f(this->ssaoShader.ParameterLocation("winSize"), curVP[2], curVP[3]);
glUniform1i(this->ssaoShader.ParameterLocation("depthBuff"), 0);
glUniform1i(this->ssaoShader.ParameterLocation("rotSampler"), 1);
glUniform1i(this->ssaoShader.ParameterLocation("normalBuff"), 2);
glUniform1f(this->ssaoShader.ParameterLocation("ssaoRadius"),
this->ssaoRadiusParam.Param<core::param::FloatParam>()->Value());
// Bind depth texture
glActiveTexture(GL_TEXTURE1);
glBindTexture(GL_TEXTURE_2D, this->rotationSampler);
glActiveTexture(GL_TEXTURE2);
glBindTexture(GL_TEXTURE_2D, this->normalBuffer);
glActiveTexture(GL_TEXTURE0);
glBindTexture(GL_TEXTURE_2D, this->depthBuffer);
// Draw
glBegin(GL_QUADS);
glNormal3fv((ray - right - up).PeekComponents());
glTexCoord2f(0, 0); glVertex2f(-1.0f, -1.0f);
glNormal3fv((ray + right - up).PeekComponents());
glTexCoord2f(1, 0); glVertex2f(1.0f, -1.0f);
glNormal3fv((ray + right + up).PeekComponents());
glTexCoord2f(1, 1); glVertex2f(1.0f, 1.0f);
glNormal3fv((ray - right + up).PeekComponents());
glTexCoord2f(0, 1); glVertex2f(-1.0f, 1.0f);
glEnd();
this->ssaoShader.Disable();
glBindTexture(GL_TEXTURE_2D, 0);
}
// Disable rendering to framebuffer
glBindFramebufferEXT(GL_FRAMEBUFFER, 0);
/// 4. Deferred shading ///
glDepthMask(GL_TRUE); // Enable writing to depth buffer
// Preserve the current framebuffer content (e.g. back of the bounding box)
glEnable(GL_BLEND);
glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
this->toonShader.Enable();
glUniform2f(this->toonShader.ParameterLocation("clip"),
crIn->GetCameraParameters()->NearClip(),
crIn->GetCameraParameters()->FarClip());
glUniform2f(this->toonShader.ParameterLocation("winSize"),
curVP[2], curVP[3]);
glUniform1i(this->toonShader.ParameterLocation("depthBuffer"), 0);
glUniform1i(this->toonShader.ParameterLocation("colorBuffer"), 1);
glUniform1i(this->toonShader.ParameterLocation("normalBuffer"), 2);
glUniform1i(this->toonShader.ParameterLocation("gradientBuffer"), 3);
glUniform1i(this->toonShader.ParameterLocation("ssaoBuffer"), 4);
glUniform1f(this->toonShader.ParameterLocation("threshFine"),
(10.0f - this->threshFineLinesParam.Param<core::param::FloatParam>()->Value())*0.1f);
glUniform1f(this->toonShader.ParameterLocation("threshCoarse"),
(10.0f - this->threshCoarseLinesParam.Param<core::param::FloatParam>()->Value())*0.1f);
glUniform1i(this->toonShader.ParameterLocation("ssao"),
this->ssaoParam.Param<core::param::BoolParam>()->Value());
glUniform1i(this->toonShader.ParameterLocation("lighting"),
this->illuminationParam.Param<core::param::EnumParam>()->Value());
glUniform1i(this->toonShader.ParameterLocation("withColor"),
this->colorParam.Param<core::param::BoolParam>()->Value());
// Bind textures
glActiveTexture(GL_TEXTURE1);
glBindTexture(GL_TEXTURE_2D, this->colorBuffer); // Color buffer
glActiveTexture(GL_TEXTURE2);
glBindTexture(GL_TEXTURE_2D, this->normalBuffer); // Normal buffer
glActiveTexture(GL_TEXTURE3);
glBindTexture(GL_TEXTURE_2D, this->gradientBuffer); // Gradient buffer
glActiveTexture(GL_TEXTURE4);
glBindTexture(GL_TEXTURE_2D, this->ssaoBuffer); // SSAO buffer
glGenerateMipmapEXT(GL_TEXTURE_2D); // Generate mip map levels for ssao texture
glActiveTexture(GL_TEXTURE0);
glBindTexture(GL_TEXTURE_2D, this->depthBuffer); // Depth buffer
// Draw quad
glBegin(GL_QUADS);
glNormal3fv((ray - right - up).PeekComponents());
glTexCoord2f(0, 0); glVertex2f(-1.0f, -1.0f);
glNormal3fv((ray + right - up).PeekComponents());
glTexCoord2f(1, 0); glVertex2f(1.0f, -1.0f);
glNormal3fv((ray + right + up).PeekComponents());
glTexCoord2f(1, 1); glVertex2f(1.0f, 1.0f);
glNormal3fv((ray - right + up).PeekComponents());
glTexCoord2f(0, 1); glVertex2f(-1.0f, 1.0f);
glEnd();
this->toonShader.Disable();
glBindTexture(GL_TEXTURE_2D, 0);
glDisable(GL_TEXTURE_2D);
glEnable(GL_DEPTH_TEST);
glDisable(GL_BLEND);
glMatrixMode(GL_PROJECTION);
glPopMatrix();
glMatrixMode(GL_MODELVIEW);
glPopMatrix();
return true;
}
/*
* ToonRendererDeferred::createFBO
*/
bool ToonRendererDeferred::createFBO(UINT width, UINT height) {
// Delete textures + fbo if necessary
if(glIsFramebufferEXT(this->fbo)) {
glDeleteTextures(1, &this->colorBuffer);
glDeleteTextures(1, &this->normalBuffer);
glDeleteTextures(1, &this->gradientBuffer);
glDeleteTextures(1, &this->depthBuffer);
glDeleteTextures(1, &this->ssaoBuffer);
glDeleteFramebuffersEXT(1, &this->fbo);
}
glEnable(GL_TEXTURE_2D);
glGenTextures(1, &this->colorBuffer);
glBindTexture(GL_TEXTURE_2D, this->colorBuffer);
glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA32F, width, height, 0, GL_RGBA, GL_UNSIGNED_BYTE, 0);
glTexParameterf( GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
glTexParameterf( GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
glBindTexture(GL_TEXTURE_2D, 0);
// Normal buffer
glGenTextures(1, &this->normalBuffer);
glBindTexture(GL_TEXTURE_2D, this->normalBuffer);
glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA32F, width, height, 0, GL_RGBA, GL_UNSIGNED_BYTE, 0);
glTexParameterf( GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
glTexParameterf( GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
glBindTexture(GL_TEXTURE_2D, 0);
// Gradient buffer
// TODO Texture format
glGenTextures(1, &this->gradientBuffer);
glBindTexture(GL_TEXTURE_2D, this->gradientBuffer);
glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA32F, width, height, 0, GL_RGBA, GL_UNSIGNED_BYTE, 0);
glTexParameterf( GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
glTexParameterf( GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
glBindTexture(GL_TEXTURE_2D, 0);
// SSAO buffer
// TODO Texture format
glGenTextures(1, &this->ssaoBuffer);
glBindTexture(GL_TEXTURE_2D, this->ssaoBuffer);
glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA32F, width, height, 0, GL_RGBA, GL_UNSIGNED_BYTE, 0);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR_MIPMAP_LINEAR);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
glBindTexture(GL_TEXTURE_2D, 0);
// Depth buffer
glGenTextures(1, &this->depthBuffer);
glBindTexture(GL_TEXTURE_2D, this->depthBuffer);
glTexImage2D(GL_TEXTURE_2D, 0, GL_DEPTH_COMPONENT16, width, height, 0, GL_DEPTH_COMPONENT, GL_UNSIGNED_BYTE, 0);
glTexParameterf( GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
glTexParameterf( GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
glBindTexture(GL_TEXTURE_2D, 0);
// Generate framebuffer
glGenFramebuffersEXT(1, &this->fbo);
GLenum status = glCheckFramebufferStatusEXT(GL_FRAMEBUFFER);
if(status != GL_FRAMEBUFFER_COMPLETE) {
megamol::core::utility::log::Log::DefaultLog.WriteMsg(megamol::core::utility::log::Log::LEVEL_ERROR, "Could not create FBO");
return false;
}
// Detach all textures
glBindFramebufferEXT(GL_FRAMEBUFFER, 0);
return true;
}
/*
* ToonRendererDeferred::updateParams
*/
bool ToonRendererDeferred::updateParams() {
return true;
}
/*
* ToonRendererDeferred::createRandomRotSampler
*/
bool ToonRendererDeferred::createRandomRotSampler() {
float data [4][4][3];
for(unsigned int s = 0; s < 4; s++) {
for(unsigned int t = 0; t < 4; t++) {
data[s][t][0] = getRandomFloat(-1.0, 1.0, 3);
data[s][t][1] = getRandomFloat(-1.0, 1.0, 3);
data[s][t][2] = 0.0;
// Compute magnitude
float mag = sqrt(data[s][t][0]*data[s][t][0] +
data[s][t][1]*data[s][t][1] +
data[s][t][2]*data[s][t][2]);
// Normalize
data[s][t][0] /= mag;
data[s][t][1] /= mag;
data[s][t][2] /= mag;
// Map to range 0 ... 1
data[s][t][0] += 1.0; data[s][t][0] /= 2.0;
data[s][t][1] += 1.0; data[s][t][1] /= 2.0;
data[s][t][2] += 1.0; data[s][t][2] /= 2.0;
}
}
glGenTextures(1, &this->rotationSampler);
glBindTexture(GL_TEXTURE_2D, this->rotationSampler);
glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA32F, 4, 4, 0, GL_RGB, GL_FLOAT, data);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
glTexParameterf( GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT);
glTexParameterf( GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT);
glBindTexture(GL_TEXTURE_2D, 0);
if(glGetError() != GL_NO_ERROR)
return false;
return true;
}
/*
* ToonRendererDeferred::getRandomFloat
*/
float ToonRendererDeferred::getRandomFloat(float min, float max, unsigned int prec) {
// Note: RAND_MAX is only guaranteed to be at least 32767, so prec should not be more than 4
float base = 10.0;
float precision = pow(base, (int)prec);
int range = (int)(max*precision - min*precision + 1);
return static_cast<float>(rand()%range + min*precision) / precision;
}
/*
* ToonRendererDeferred::::createRandomKernel
*/
// TODO enforce lower boundary to prevent numerical problems leading to artifacts
bool ToonRendererDeferred::createRandomKernel(UINT size) {
float *kernel;
kernel = new float[size*3];
for(unsigned int s = 0; s < size; s++) {
float scale = float(s) / float(size);
scale *= scale;
scale = 0.1f*(1.0f - scale) + scale; // Interpolate between 0.1 ... 1.0
kernel[s*3 + 0] = getRandomFloat(-1.0, 1.0, 3);
kernel[s*3 + 1] = getRandomFloat(-1.0, 1.0, 3);
kernel[s*3 + 2] = getRandomFloat( 0.0, 1.0, 3);
// Compute magnitude
float mag = sqrt(kernel[s*3 + 0]*kernel[s*3 + 0] +
kernel[s*3 + 1]*kernel[s*3 + 1] +
kernel[s*3 + 2]*kernel[s*3 + 2]);
// Normalize
kernel[s*3 + 0] /= mag;
kernel[s*3 + 1] /= mag;
kernel[s*3 + 2] /= mag;
// Scale values
kernel[s*3 + 0] *= scale;
kernel[s*3 + 1] *= scale;
kernel[s*3 + 2] *= scale;
// Map values to range 0 ... 1
kernel[s*3 + 0] += 1.0; kernel[s*3 + 0] /= 2.0;
kernel[s*3 + 1] += 1.0; kernel[s*3 + 1] /= 2.0;
kernel[s*3 + 2] += 1.0; kernel[s*3 + 2] /= 2.0;
}
glGenTextures(1, &this->randomKernel);
glBindTexture(GL_TEXTURE_2D, this->randomKernel);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA32F, size, 1, 0, GL_RGB, GL_FLOAT, kernel);
glBindTexture(GL_TEXTURE_2D, 0);
delete[] kernel;
if(glGetError() != GL_NO_ERROR)
return false;
return true;
}
| 37.732919 | 144 | 0.672675 |
215435cad45bb8acd7b8cd20bc77538694699099 | 1,134 | cpp | C++ | luogu/p1067.cpp | ajidow/Answers_of_OJ | 70e0c02d9367c3a154b83a277edbf158f32484a3 | [
"MIT"
] | null | null | null | luogu/p1067.cpp | ajidow/Answers_of_OJ | 70e0c02d9367c3a154b83a277edbf158f32484a3 | [
"MIT"
] | null | null | null | luogu/p1067.cpp | ajidow/Answers_of_OJ | 70e0c02d9367c3a154b83a277edbf158f32484a3 | [
"MIT"
] | null | null | null | #include <iostream>
using namespace std;
int main(int argc, char const *argv[])
{
int power;
cin >> power;
int num[power+1];
//
int i;
for (i = 0; i < power+1; ++i)
{
cin >> num[i];
}
//
int sub = power;
if (num[0] == 1){
cout << "x" << "^" << sub;
}else if (num[0] == -1)
{
cout << "-x^" << sub;
}else{
cout << num[0] << "x" << "^" << sub;
}
sub--;
for (i = 1; i < power-1; ++i)
{
if ( num[i] != 1 && num[i] != -1 ){
if (num[i] > 0)
{
cout << "+" << num[i] << "x" << "^" << sub;
}else if (num[i] < 0)
{
cout << num[i] << "x" << "^" << sub;
}
}else if (num[i] == 1)
{
cout << "+" << "x" << "^" << sub;
}else if (num[i] == -1)
{
cout << "-" << "x" << "^" << sub;
}
sub--;
}
if (num[power-1] != 1 && num[power-1] != -1)\
{
if (num[power-1] < 0)
{
cout << num[power-1] << "x";
}else if (num[power-1] > 0)
{
cout << "+" << num[power-1] << "x";
}
}else if (num[power-1] == 1)
{
cout << "+x";
}else{
cout << "-x";
}
if (num[power] > 0)
{
cout << "+" << num[power];
}else if (num[power] < 0)
{
cout << num[power];
}
return 0;
}
| 15.324324 | 47 | 0.395062 |
21552ab246534cf24cf1ad5f67ad7ee779c09346 | 20,590 | hpp | C++ | libs/boost_1_72_0/boost/locale/message.hpp | henrywarhurst/matrix | 317a2a7c35c1c7e3730986668ad2270dc19809ef | [
"BSD-3-Clause"
] | null | null | null | libs/boost_1_72_0/boost/locale/message.hpp | henrywarhurst/matrix | 317a2a7c35c1c7e3730986668ad2270dc19809ef | [
"BSD-3-Clause"
] | null | null | null | libs/boost_1_72_0/boost/locale/message.hpp | henrywarhurst/matrix | 317a2a7c35c1c7e3730986668ad2270dc19809ef | [
"BSD-3-Clause"
] | null | null | null | //
// Copyright (c) 2009-2011 Artyom Beilis (Tonkikh)
//
// 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_LOCALE_MESSAGE_HPP_INCLUDED
#define BOOST_LOCALE_MESSAGE_HPP_INCLUDED
#include <boost/locale/config.hpp>
#ifdef BOOST_MSVC
#pragma warning(push)
#pragma warning(disable : 4275 4251 4231 4660)
#endif
#include <boost/locale/formatting.hpp>
#include <locale>
#include <memory>
#include <set>
#include <string>
#include <vector>
// glibc < 2.3.4 declares those as macros if compiled with optimization turned
// on
#ifdef gettext
#undef gettext
#undef ngettext
#undef dgettext
#undef dngettext
#endif
namespace boost {
namespace locale {
///
/// \defgroup message Message Formatting (translation)
///
/// This module provides message translation functionality, i.e. allow your
/// application to speak native language
///
/// @{
///
/// \cond INTERNAL
template <typename CharType>
struct base_message_format : public std::locale::facet {};
/// \endcond
///
/// \brief This facet provides message formatting abilities
///
template <typename CharType>
class message_format : public base_message_format<CharType> {
public:
///
/// Character type
///
typedef CharType char_type;
///
/// String type
///
typedef std::basic_string<CharType> string_type;
///
/// Default constructor
///
message_format(size_t refs = 0) : base_message_format<CharType>(refs) {}
///
/// This function returns a pointer to the string for a message defined by a
/// \a context and identification string \a id. Both create a single key for
/// message lookup in a domain defined by \a domain_id.
///
/// If \a context is NULL it is not considered to be a part of the key
///
/// If a translated string is found, it is returned, otherwise NULL is
/// returned
///
///
virtual char_type const *get(int domain_id, char_type const *context,
char_type const *id) const = 0;
///
/// This function returns a pointer to the string for a plural message defined
/// by a \a context and identification string \a single_id.
///
/// If \a context is NULL it is not considered to be a part of the key
///
/// Both create a single key for message lookup in
/// a domain defined \a domain_id. \a n is used to pick the correct
/// translation string for a specific number.
///
/// If a translated string is found, it is returned, otherwise NULL is
/// returned
///
///
virtual char_type const *get(int domain_id, char_type const *context,
char_type const *single_id, int n) const = 0;
///
/// Convert a string that defines \a domain to the integer id used by \a get
/// functions
///
virtual int domain(std::string const &domain) const = 0;
///
/// Convert the string \a msg to target locale's encoding. If \a msg is
/// already in target encoding it would be returned otherwise the converted
/// string is stored in temporary \a buffer and buffer.c_str() is returned.
///
/// Note: for char_type that is char16_t, char32_t and wchar_t it is no-op,
/// returns msg
///
virtual char_type const *convert(char_type const *msg,
string_type &buffer) const = 0;
#if defined(__SUNPRO_CC) && defined(_RWSTD_VER)
std::locale::id &__get_id(void) const { return id; }
#endif
protected:
virtual ~message_format() {}
};
/// \cond INTERNAL
namespace details {
inline bool is_us_ascii_char(char c) {
// works for null terminated strings regardless char "signness"
return 0 < c && c < 0x7F;
}
inline bool is_us_ascii_string(char const *msg) {
while (*msg) {
if (!is_us_ascii_char(*msg++))
return false;
}
return true;
}
template <typename CharType> struct string_cast_traits {
static CharType const *cast(CharType const *msg,
std::basic_string<CharType> & /*unused*/) {
return msg;
}
};
template <> struct string_cast_traits<char> {
static char const *cast(char const *msg, std::string &buffer) {
if (is_us_ascii_string(msg))
return msg;
buffer.reserve(strlen(msg));
char c;
while ((c = *msg++) != 0) {
if (is_us_ascii_char(c))
buffer += c;
}
return buffer.c_str();
}
};
} // namespace details
/// \endcond
///
/// \brief This class represents a message that can be converted to a specific
/// locale message
///
/// It holds the original ASCII string that is queried in the dictionary when
/// converting to the output string. The created string may be UTF-8, UTF-16,
/// UTF-32 or other 8-bit encoded string according to the target character type
/// and locale encoding.
///
template <typename CharType> class basic_message {
public:
typedef CharType
char_type; ///< The character this message object is used with
typedef std::basic_string<char_type>
string_type; ///< The string type this object can be used with
typedef message_format<char_type>
facet_type; ///< The type of the facet the messages are fetched with
///
/// Create default empty message
///
basic_message() : n_(0), c_id_(0), c_context_(0), c_plural_(0) {}
///
/// Create a simple message from 0 terminated string. The string should exist
/// until the message is destroyed. Generally useful with static constant
/// strings
///
explicit basic_message(char_type const *id)
: n_(0), c_id_(id), c_context_(0), c_plural_(0) {}
///
/// Create a simple plural form message from 0 terminated strings. The strings
/// should exist until the message is destroyed. Generally useful with static
/// constant strings.
///
/// \a n is the number, \a single and \a plural are singular and plural forms
/// of the message
///
explicit basic_message(char_type const *single, char_type const *plural,
int n)
: n_(n), c_id_(single), c_context_(0), c_plural_(plural) {}
///
/// Create a simple message from 0 terminated strings, with context
/// information. The string should exist
/// until the message is destroyed. Generally useful with static constant
/// strings
///
explicit basic_message(char_type const *context, char_type const *id)
: n_(0), c_id_(id), c_context_(context), c_plural_(0) {}
///
/// Create a simple plural form message from 0 terminated strings, with
/// context. The strings should exist until the message is destroyed.
/// Generally useful with static constant strings.
///
/// \a n is the number, \a single and \a plural are singular and plural forms
/// of the message
///
explicit basic_message(char_type const *context, char_type const *single,
char_type const *plural, int n)
: n_(n), c_id_(single), c_context_(context), c_plural_(plural) {}
///
/// Create a simple message from a string.
///
explicit basic_message(string_type const &id)
: n_(0), c_id_(0), c_context_(0), c_plural_(0), id_(id) {}
///
/// Create a simple plural form message from strings.
///
/// \a n is the number, \a single and \a plural are single and plural forms of
/// the message
///
explicit basic_message(string_type const &single, string_type const &plural,
int number)
: n_(number), c_id_(0), c_context_(0), c_plural_(0), id_(single),
plural_(plural) {}
///
/// Create a simple message from a string with context.
///
explicit basic_message(string_type const &context, string_type const &id)
: n_(0), c_id_(0), c_context_(0), c_plural_(0), id_(id),
context_(context) {}
///
/// Create a simple plural form message from strings.
///
/// \a n is the number, \a single and \a plural are single and plural forms of
/// the message
///
explicit basic_message(string_type const &context, string_type const &single,
string_type const &plural, int number)
: n_(number), c_id_(0), c_context_(0), c_plural_(0), id_(single),
context_(context), plural_(plural) {}
///
/// Copy an object
///
basic_message(basic_message const &other)
: n_(other.n_), c_id_(other.c_id_), c_context_(other.c_context_),
c_plural_(other.c_plural_), id_(other.id_), context_(other.context_),
plural_(other.plural_) {}
///
/// Assign other message object to this one
///
basic_message const &operator=(basic_message const &other) {
if (this == &other) {
return *this;
}
basic_message tmp(other);
swap(tmp);
return *this;
}
///
/// Swap two message objects
///
void swap(basic_message &other) {
std::swap(n_, other.n_);
std::swap(c_id_, other.c_id_);
std::swap(c_context_, other.c_context_);
std::swap(c_plural_, other.c_plural_);
id_.swap(other.id_);
context_.swap(other.context_);
plural_.swap(other.plural_);
}
///
/// Message class can be explicitly converted to string class
///
operator string_type() const { return str(); }
///
/// Translate message to a string in the default global locale, using default
/// domain
///
string_type str() const {
std::locale loc;
return str(loc, 0);
}
///
/// Translate message to a string in the locale \a locale, using default
/// domain
///
string_type str(std::locale const &locale) const { return str(locale, 0); }
///
/// Translate message to a string using locale \a locale and message domain \a
/// domain_id
///
string_type str(std::locale const &locale,
std::string const &domain_id) const {
int id = 0;
if (std::has_facet<facet_type>(locale))
id = std::use_facet<facet_type>(locale).domain(domain_id);
return str(locale, id);
}
///
/// Translate message to a string using the default locale and message domain
/// \a domain_id
///
string_type str(std::string const &domain_id) const {
int id = 0;
std::locale loc;
if (std::has_facet<facet_type>(loc))
id = std::use_facet<facet_type>(loc).domain(domain_id);
return str(loc, id);
}
///
/// Translate message to a string using locale \a loc and message domain index
/// \a id
///
string_type str(std::locale const &loc, int id) const {
string_type buffer;
char_type const *ptr = write(loc, id, buffer);
if (ptr == buffer.c_str())
return buffer;
else
buffer = ptr;
return buffer;
}
///
/// Translate message and write to stream \a out, using imbued locale and
/// domain set to the stream
///
void write(std::basic_ostream<char_type> &out) const {
std::locale const &loc = out.getloc();
int id = ios_info::get(out).domain_id();
string_type buffer;
out << write(loc, id, buffer);
}
private:
char_type const *plural() const {
if (c_plural_)
return c_plural_;
if (plural_.empty())
return 0;
return plural_.c_str();
}
char_type const *context() const {
if (c_context_)
return c_context_;
if (context_.empty())
return 0;
return context_.c_str();
}
char_type const *id() const { return c_id_ ? c_id_ : id_.c_str(); }
char_type const *write(std::locale const &loc, int domain_id,
string_type &buffer) const {
char_type const *translated = 0;
static const char_type empty_string[1] = {0};
char_type const *id = this->id();
char_type const *context = this->context();
char_type const *plural = this->plural();
if (*id == 0)
return empty_string;
facet_type const *facet = 0;
if (std::has_facet<facet_type>(loc))
facet = &std::use_facet<facet_type>(loc);
if (facet) {
if (!plural) {
translated = facet->get(domain_id, context, id);
} else {
translated = facet->get(domain_id, context, id, n_);
}
}
if (!translated) {
char_type const *msg = plural ? (n_ == 1 ? id : plural) : id;
if (facet) {
translated = facet->convert(msg, buffer);
} else {
translated = details::string_cast_traits<char_type>::cast(msg, buffer);
}
}
return translated;
}
/// members
int n_;
char_type const *c_id_;
char_type const *c_context_;
char_type const *c_plural_;
string_type id_;
string_type context_;
string_type plural_;
};
///
/// Convenience typedef for char
///
typedef basic_message<char> message;
///
/// Convenience typedef for wchar_t
///
typedef basic_message<wchar_t> wmessage;
#ifdef BOOST_LOCALE_ENABLE_CHAR16_T
///
/// Convenience typedef for char16_t
///
typedef basic_message<char16_t> u16message;
#endif
#ifdef BOOST_LOCALE_ENABLE_CHAR32_T
///
/// Convenience typedef for char32_t
///
typedef basic_message<char32_t> u32message;
#endif
///
/// Translate message \a msg and write it to stream
///
template <typename CharType>
std::basic_ostream<CharType> &operator<<(std::basic_ostream<CharType> &out,
basic_message<CharType> const &msg) {
msg.write(out);
return out;
}
///
/// \anchor boost_locale_translate_family \name Indirect message translation
/// function family
/// @{
///
/// \brief Translate a message, \a msg is not copied
///
template <typename CharType>
inline basic_message<CharType> translate(CharType const *msg) {
return basic_message<CharType>(msg);
}
///
/// \brief Translate a message in context, \a msg and \a context are not copied
///
template <typename CharType>
inline basic_message<CharType> translate(CharType const *context,
CharType const *msg) {
return basic_message<CharType>(context, msg);
}
///
/// \brief Translate a plural message form, \a single and \a plural are not
/// copied
///
template <typename CharType>
inline basic_message<CharType> translate(CharType const *single,
CharType const *plural, int n) {
return basic_message<CharType>(single, plural, n);
}
///
/// \brief Translate a plural message from in constext, \a context, \a single
/// and \a plural are not copied
///
template <typename CharType>
inline basic_message<CharType> translate(CharType const *context,
CharType const *single,
CharType const *plural, int n) {
return basic_message<CharType>(context, single, plural, n);
}
///
/// \brief Translate a message, \a msg is copied
///
template <typename CharType>
inline basic_message<CharType>
translate(std::basic_string<CharType> const &msg) {
return basic_message<CharType>(msg);
}
///
/// \brief Translate a message in context,\a context and \a msg is copied
///
template <typename CharType>
inline basic_message<CharType>
translate(std::basic_string<CharType> const &context,
std::basic_string<CharType> const &msg) {
return basic_message<CharType>(context, msg);
}
///
/// \brief Translate a plural message form in constext, \a context, \a single
/// and \a plural are copied
///
template <typename CharType>
inline basic_message<CharType>
translate(std::basic_string<CharType> const &context,
std::basic_string<CharType> const &single,
std::basic_string<CharType> const &plural, int n) {
return basic_message<CharType>(context, single, plural, n);
}
///
/// \brief Translate a plural message form, \a single and \a plural are copied
///
template <typename CharType>
inline basic_message<CharType>
translate(std::basic_string<CharType> const &single,
std::basic_string<CharType> const &plural, int n) {
return basic_message<CharType>(single, plural, n);
}
/// @}
///
/// \anchor boost_locale_gettext_family \name Direct message translation
/// functions family
///
///
/// Translate message \a id according to locale \a loc
///
template <typename CharType>
std::basic_string<CharType> gettext(CharType const *id,
std::locale const &loc = std::locale()) {
return basic_message<CharType>(id).str(loc);
}
///
/// Translate plural form according to locale \a loc
///
template <typename CharType>
std::basic_string<CharType> ngettext(CharType const *s, CharType const *p,
int n,
std::locale const &loc = std::locale()) {
return basic_message<CharType>(s, p, n).str(loc);
}
///
/// Translate message \a id according to locale \a loc in domain \a domain
///
template <typename CharType>
std::basic_string<CharType> dgettext(char const *domain, CharType const *id,
std::locale const &loc = std::locale()) {
return basic_message<CharType>(id).str(loc, domain);
}
///
/// Translate plural form according to locale \a loc in domain \a domain
///
template <typename CharType>
std::basic_string<CharType> dngettext(char const *domain, CharType const *s,
CharType const *p, int n,
std::locale const &loc = std::locale()) {
return basic_message<CharType>(s, p, n).str(loc, domain);
}
///
/// Translate message \a id according to locale \a loc in context \a context
///
template <typename CharType>
std::basic_string<CharType> pgettext(CharType const *context,
CharType const *id,
std::locale const &loc = std::locale()) {
return basic_message<CharType>(context, id).str(loc);
}
///
/// Translate plural form according to locale \a loc in context \a context
///
template <typename CharType>
std::basic_string<CharType>
npgettext(CharType const *context, CharType const *s, CharType const *p, int n,
std::locale const &loc = std::locale()) {
return basic_message<CharType>(context, s, p, n).str(loc);
}
///
/// Translate message \a id according to locale \a loc in domain \a domain in
/// context \a context
///
template <typename CharType>
std::basic_string<CharType>
dpgettext(char const *domain, CharType const *context, CharType const *id,
std::locale const &loc = std::locale()) {
return basic_message<CharType>(context, id).str(loc, domain);
}
///
/// Translate plural form according to locale \a loc in domain \a domain in
/// context \a context
///
template <typename CharType>
std::basic_string<CharType>
dnpgettext(char const *domain, CharType const *context, CharType const *s,
CharType const *p, int n, std::locale const &loc = std::locale()) {
return basic_message<CharType>(context, s, p, n).str(loc, domain);
}
///
/// \cond INTERNAL
///
template <>
struct BOOST_LOCALE_DECL base_message_format<char> : public std::locale::facet {
base_message_format(size_t refs = 0) : std::locale::facet(refs) {}
static std::locale::id id;
};
template <>
struct BOOST_LOCALE_DECL base_message_format<wchar_t>
: public std::locale::facet {
base_message_format(size_t refs = 0) : std::locale::facet(refs) {}
static std::locale::id id;
};
#ifdef BOOST_LOCALE_ENABLE_CHAR16_T
template <>
struct BOOST_LOCALE_DECL base_message_format<char16_t>
: public std::locale::facet {
base_message_format(size_t refs = 0) : std::locale::facet(refs) {}
static std::locale::id id;
};
#endif
#ifdef BOOST_LOCALE_ENABLE_CHAR32_T
template <>
struct BOOST_LOCALE_DECL base_message_format<char32_t>
: public std::locale::facet {
base_message_format(size_t refs = 0) : std::locale::facet(refs) {}
static std::locale::id id;
};
#endif
/// \endcond
///
/// @}
///
namespace as {
/// \cond INTERNAL
namespace details {
struct set_domain {
std::string domain_id;
};
template <typename CharType>
std::basic_ostream<CharType> &operator<<(std::basic_ostream<CharType> &out,
set_domain const &dom) {
int id = std::use_facet<message_format<CharType>>(out.getloc())
.domain(dom.domain_id);
ios_info::get(out).domain_id(id);
return out;
}
} // namespace details
/// \endcond
///
/// \addtogroup manipulators
///
/// @{
///
/// Manipulator for switching message domain in ostream,
///
/// \note The returned object throws std::bad_cast if the I/O stream does not
/// have \ref message_format facet installed
///
inline
#ifdef BOOST_LOCALE_DOXYGEN
unspecified_type
#else
details::set_domain
#endif
domain(std::string const &id) {
details::set_domain tmp = {id};
return tmp;
}
/// @}
} // namespace as
} // namespace locale
} // namespace boost
#ifdef BOOST_MSVC
#pragma warning(pop)
#endif
#endif
// vim: tabstop=4 expandtab shiftwidth=4 softtabstop=4
| 28.636996 | 80 | 0.657067 |
215e2ba19080e1f82bcc2a2e33d9b5e21c576525 | 1,538 | cc | C++ | fhiclcpp/test/types/searchAllowedConfiguration_t.cc | art-framework-suite/fhicl-cpp | 302a8ca52dba4b922812ead406599cd535676252 | [
"BSD-3-Clause"
] | null | null | null | fhiclcpp/test/types/searchAllowedConfiguration_t.cc | art-framework-suite/fhicl-cpp | 302a8ca52dba4b922812ead406599cd535676252 | [
"BSD-3-Clause"
] | 2 | 2021-12-10T14:54:24.000Z | 2022-03-25T16:33:23.000Z | fhiclcpp/test/types/searchAllowedConfiguration_t.cc | art-framework-suite/fhicl-cpp | 302a8ca52dba4b922812ead406599cd535676252 | [
"BSD-3-Clause"
] | null | null | null | #define BOOST_TEST_MODULE (search allowed configuration test)
#include "boost/test/unit_test.hpp"
#include "fhiclcpp/types/Atom.h"
#include "fhiclcpp/types/Sequence.h"
#include "fhiclcpp/types/Table.h"
#include "fhiclcpp/types/Tuple.h"
#include "fhiclcpp/types/detail/SearchAllowedConfiguration.h"
#include <string>
using namespace fhicl;
using namespace fhicl::detail;
using namespace std;
auto supports_key = SearchAllowedConfiguration::supports_key;
namespace {
struct S {
Atom<int> test{Name{"atom"}};
Sequence<int, 2> seq{Name{"sequence"}};
Tuple<int, double, bool> tuple{Name{"tuple"}};
struct U {
Atom<int> test{Name{"nested_atom"}};
};
Tuple<Sequence<int, 2>, bool> tuple2{Name{"tuple2"}};
Table<U> table2{Name{"table2"}};
};
}
BOOST_AUTO_TEST_SUITE(searchAllowedConfiguration_test)
BOOST_AUTO_TEST_CASE(table_t)
{
Table<S> t{Name{"table"}};
BOOST_TEST(supports_key(t, "atom"));
BOOST_TEST(!supports_key(t, "table.atom"));
BOOST_TEST(!supports_key(t, "table.sequence"));
BOOST_TEST(supports_key(t, "sequence"));
BOOST_TEST(supports_key(t, "sequence[0]"));
BOOST_TEST(!supports_key(t, "[0]"));
BOOST_TEST(supports_key(t, "table2"));
BOOST_TEST(supports_key(t, "tuple2[0][1]"));
BOOST_TEST(supports_key(t, "tuple2[1]"));
}
BOOST_AUTO_TEST_CASE(seqInSeq_t)
{
Sequence<Sequence<int, 2>> s{Name{"nestedSequence"}};
BOOST_TEST(supports_key(s, "[0]"));
BOOST_TEST(supports_key(s, "[0][0]"));
BOOST_TEST(supports_key(s, "[0][1]"));
}
BOOST_AUTO_TEST_SUITE_END()
| 26.982456 | 61 | 0.708062 |
216191eae850363824975047adbcbd028eb99cc8 | 13,627 | hpp | C++ | engine/common/ShadersGL.hpp | ColinGilbert/noobwerkz-engine | f5670e98ca0dada8865be9ab82d25d3acf549ebe | [
"Apache-2.0"
] | 23 | 2015-03-02T10:56:40.000Z | 2021-01-27T03:32:49.000Z | engine/common/ShadersGL.hpp | ColinGilbert/noobwerkz-engine-borked | f5670e98ca0dada8865be9ab82d25d3acf549ebe | [
"Apache-2.0"
] | 73 | 2015-04-14T09:39:05.000Z | 2020-11-11T21:49:10.000Z | engine/common/ShadersGL.hpp | ColinGilbert/noobwerkz-engine-borked | f5670e98ca0dada8865be9ab82d25d3acf549ebe | [
"Apache-2.0"
] | 3 | 2016-02-22T01:29:32.000Z | 2018-01-02T06:07:12.000Z | #pragma once
namespace noob
{
namespace glsl
{
////////////////////////////////////////////////////////////
// Extremely useful for getting rid of shader conditionals
////////////////////////////////////////////////////////////
// http://theorangeduck.com/page/avoiding-shader-conditionals
static const std::string shader_conditionals(
"vec4 noob_when_eq(vec4 x, vec4 y) \n"
"{ \n"
" return 1.0 - abs(sign(x - y)); \n"
"} \n"
"vec4 noob_when_neq(vec4 x, vec4 y) \n"
"{ \n"
" return abs(sign(x - y)); \n"
"} \n"
"vec4 noob_when_gt(vec4 x, vec4 y) \n"
"{ \n"
" return max(sign(x - y), 0.0); \n"
"} \n"
"vec4 noob_when_lt(vec4 x, vec4 y) \n"
"{ \n"
" return min(1.0 - sign(x - y), 1.0); \n"
"} \n"
"vec4 noob_when_ge(vec4 x, vec4 y) \n"
"{ \n"
" return 1.0 - noob_when_lt(x, y); \n"
"} \n"
"vec4 noob_when_le(vec4 x, vec4 y) \n"
"{ \n"
" return 1.0 - noob_when_gt(x, y); \n"
"} \n"
"vec4 noob_and(vec4 a, vec4 b) \n"
"{ \n"
" return a * b; \n"
"} \n"
"vec4 noob_or(vec4 a, vec4 b) \n"
"{ \n"
" return min(a + b, 1.0); \n"
"} \n"
//"vec4 xor(vec4 a, vec4 b) \n"
//"{ \n"
//" return (a + b) % 2.0; \n"
//"} \n"
"vec4 noob_not(vec4 a) \n"
"{ \n"
" return 1.0 - a; \n"
"} \n"
"float noob_when_eq(float x, float y) \n"
"{ \n"
" return 1.0 - abs(sign(x - y)); \n"
"} \n"
"float noob_when_neq(float x, float y) \n"
"{ \n"
" return abs(sign(x - y)); \n"
"} \n"
"float noob_when_gt(float x, float y) \n"
"{ \n"
" return max(sign(x - y), 0.0); \n"
"} \n"
"float noob_when_lt(float x, float y) \n"
"{ \n"
" return min(1.0 - sign(x - y), 1.0); \n"
"} \n"
"float noob_when_ge(float x, float y) \n"
"{ \n"
" return 1.0 - noob_when_lt(x, y); \n"
"} \n"
"float noob_when_le(float x, float y) \n"
"{ \n"
" return 1.0 - noob_when_gt(x, y); \n"
"} \n");
//////////////////////////////////
// Goes before every shader
//////////////////////////////////
static const std::string shader_prefix(
"#version 300 es \n"
"precision mediump float; \n");
//////////////////////////
// Vertex shaders
//////////////////////////
static const std::string vs_instancing_src = noob::concat(shader_prefix, std::string(
"layout(location = 0) in vec4 a_pos; \n"
"layout(location = 1) in vec4 a_normal; \n"
"layout(location = 2) in vec4 a_vert_colour; \n"
"layout(location = 3) in vec4 a_instance_colour; \n"
"layout(location = 4) in mat4 a_model_mat; \n"
"uniform mat4 view_matrix; \n"
"uniform mat4 projection_matrix; \n"
"out vec4 v_world_pos; \n"
"out vec4 v_world_normal; \n"
"out vec4 v_vert_colour; \n"
"void main() \n"
"{ \n"
" v_world_pos = a_model_mat * a_pos; \n"
" mat4 modelview_mat = view_matrix * a_model_mat; \n"
" v_world_normal = a_model_mat * vec4(a_normal.xyz, 0); \n"
" v_vert_colour = a_vert_colour * a_instance_colour; \n"
" mat4 mvp_mat = projection_matrix * modelview_mat; \n"
" gl_Position = mvp_mat * a_pos; \n"
"} \n"));
static const std::string vs_terrain_src = noob::concat(shader_prefix, std::string(
"layout(location = 0) in vec4 a_pos; \n"
"layout(location = 1) in vec4 a_normal; \n"
"layout(location = 2) in vec4 a_vert_colour; \n"
"out vec4 v_world_pos; \n"
"out vec4 v_world_normal; \n"
"out vec4 v_vert_colour; \n"
"uniform mat4 mvp; \n" "uniform mat4 view_matrix; \n"
"void main() \n"
"{ \n"
" v_world_pos = a_pos; \n"
" v_world_normal = vec4(a_normal.xyz, 0); \n"
" v_vert_colour = a_vert_colour; \n"
" gl_Position = mvp * a_pos; \n"
"} \n"));
static const std::string vs_billboard_src = noob::concat(shader_prefix, std::string(
"layout(location = 0) in vec4 a_pos_uv; \n"
"layout(location = 1) in vec4 a_colour; \n"
"out vec2 v_uv; \n"
"out vec4 v_colour; \n"
"void main() \n"
"{ \n"
" v_uv = vec2(a_pos_uv[2], a_pos_uv[3]); \n"
" v_colour = a_colour; \n"
" gl_Position = vec4(a_pos_uv[0], a_pos_uv[1], 0.0, 1.0); \n"
"} \n"));
//////////////////////////
// Fragment shaders
//////////////////////////
static const std::string lambert_diffuse(
"float lambert_diffuse(vec3 light_direction, vec3 surface_normal) \n"
"{ \n"
" return max(0.0, dot(light_direction, surface_normal)); \n"
"} \n");
static const std::string blinn_phong_specular(
"float blinn_phong_specular(vec3 light_direction, vec3 view_direction, vec3 surface_normal, float shininess) \n"
"{ \n"
" vec3 H = normalize(view_direction + light_direction); \n"
" return pow(max(0.0, dot(surface_normal, H)), shininess); \n"
"} \n");
static const std::string fs_instancing_src = noob::concat(shader_prefix, lambert_diffuse, blinn_phong_specular, std::string(
"in vec4 v_world_pos; \n" "in vec4 v_world_normal; \n"
"in vec4 v_vert_colour; \n"
"layout (location = 0) out vec4 out_colour; \n"
"uniform vec3 eye_pos; \n"
"uniform vec3 directional_light; \n"
"void main() \n"
"{ \n"
" vec3 view_direction = normalize(eye_pos - v_world_pos.xyz); \n"
" float diffuse = lambert_diffuse(-directional_light, v_world_normal.xyz); \n"
" float specular = blinn_phong_specular(-directional_light, -view_direction, v_world_normal.xyz, 10.0); \n"
" float light = 0.1 + diffuse + specular; \n"
" out_colour = vec4(clamp(v_vert_colour.xyz * light, 0.0, 1.0), 1.0); \n"
"} \n"));
static const std::string fs_terrain_src = noob::concat(shader_prefix, lambert_diffuse, blinn_phong_specular, shader_conditionals, std::string(
"in vec4 v_world_pos; \n"
"in vec4 v_world_normal; \n"
"in vec4 v_vert_colour; \n"
"layout(location = 0) out vec4 out_colour; \n"
"uniform sampler2D texture_0; \n"
"uniform vec4 colour_0; \n"
"uniform vec4 colour_1; \n"
"uniform vec4 colour_2; \n"
"uniform vec4 colour_3; \n"
"uniform vec3 blend_0; \n"
"uniform vec2 blend_1; \n"
"uniform vec3 tex_scales; \n"
"uniform vec3 eye_pos; \n"
"uniform vec3 directional_light; \n"
"void main() \n"
"{ \n"
" vec3 normal_blend = normalize(max(abs(v_world_normal.xyz), 0.0001)); \n"
" float b = normal_blend.x + normal_blend.y + normal_blend.z; \n"
" normal_blend /= b; \n"
// "RGB-only. Try it out for great wisdom!
// "vec4 xaxis = vec4(1.0, 0.0, 0.0, 1.0); \n"
// "vec4 yaxis = vec4(0.0, 1.0, 0.0, 1.0); \n"
// "vec4 zaxis = vec4(0.0, 0.0, 1.0, 1.0); \n"
" vec4 xaxis = vec4(texture(texture_0, v_world_pos.yz * tex_scales.x).rgb, 1.0); \n"
" vec4 yaxis = vec4(texture(texture_0, v_world_pos.xz * tex_scales.y).rgb, 1.0); \n"
" vec4 zaxis = vec4(texture(texture_0, v_world_pos.xy * tex_scales.z).rgb, 1.0); \n"
" vec4 tex = xaxis * normal_blend.x + yaxis * normal_blend.y + zaxis * normal_blend.z; \n"
" float tex_r = blend_0.x * tex.r; \n"
" float tex_g = blend_0.y * tex.g; \n"
" float tex_b = blend_0.z * tex.b; \n"
" vec4 tex_weighted = vec4(tex_r, tex_g, tex_b, 1.0); \n"
" float tex_falloff = (tex_r + tex_g + tex_b) * 0.3333; \n"
" float ratio_0_to_1 = noob_when_le(tex_falloff, blend_1.x) * ((tex_falloff + blend_1.x) * 0.5); \n"
" float ratio_1_to_2 = noob_when_le(tex_falloff, blend_1.y) * noob_when_gt(tex_falloff, blend_1.x) * ((tex_falloff + blend_1.y) * 0.5); \n"
" float ratio_2_to_3 = noob_when_ge(tex_falloff, blend_1.y) * ((tex_falloff + 1.0) * 0.5); \n"
" vec4 tex_final = ((colour_0 + colour_1) * ratio_0_to_1) + ((colour_1 + colour_2) * ratio_1_to_2) + ((colour_2 + colour_3) * ratio_2_to_3); \n"
" vec3 view_direction = normalize(eye_pos - v_world_pos.xyz); \n"
" float diffuse = lambert_diffuse(-directional_light, v_world_normal.xyz); \n"
" float specular = blinn_phong_specular(-directional_light, -view_direction, v_world_normal.xyz, 10.0); \n"
" float light = 0.1 + diffuse + specular; \n"
" out_colour = vec4(clamp(tex_final.xyz * light, 0.0, 1.0), 1.0); \n"
"} \n"));
static const std::string fs_text_src = noob::concat(shader_prefix, std::string(
"in vec2 v_uv; \n"
"in vec4 v_colour; \n"
"layout(location = 0) out vec4 out_colour; \n"
"uniform sampler2D texture_0; \n"
"void main() \n"
"{ \n"
" float f = texture(texture_0, v_uv).x; \n"
" out_colour = vec4(v_colour.rgb, v_colour.a * f); \n"
"} \n"));
/*
static std::string get_light(
"vec3 get_light(vec3 world_pos, vec3 world_normal, vec3 eye_pos, vec3 light_pos, vec3 light_rgb) \n"
"{ \n"
" // vec3 normal = normalize(world_normal); \n"
" vec3 view_direction = normalize(eye_pos - world_pos); \n"
" vec3 light_direction = normalize(light_pos - world_pos); \n"
" float light_distance = length(light_pos - world_pos); \n"
" float falloff = attenuation_reid(light_pos, light_rgb, light_distance); \n"
" // Uncomment to use orenNayar, cookTorrance, etc \n"
" // float falloff = attenuation_madams(u_light_pos_r[ii].w, 0.5, light_distance); \n"
" // float roughness = u_rough_albedo_fresnel.x; \n"
" // float albedo = u_rough_albedo_fresnel.y; \n"
" // float fresnel = u_rough_albedo_fresnel.z; \n"
" float diffuse_coeff = lambert_diffuse(light_direction, world_normal); \n"
" // float diffuse_coeff = oren+nayar_diffuse(light_direction, view_direction, world_normal, roughness, albedo); \n"
" float diffuse = (diffuse_coeff * falloff); \n"
" // float specular = 0.0; \n"
" float specular = blinn_phong_specular(light_direction, view_direction, world_normal, u_shine); \n"
" // float specular = cook_torrance_specular(light_direction, view_direction, world_normal, roughness, fresnel); \n"
" vec3 light_colour = (diffuse + specular) * light_rgb; \n"
" return light_colour; \n"
"} \n");
static std::string vs_texture_2d_src(
"#version 300 es \n"
"layout(location = 0) in vec4 a_position; \n"
"layout(location = 1) in vec2 a_texCoord; \n"
"out vec2 v_texCoord; \n"
"void main() \n"
"{ \n"
" gl_Position = a_position; \n"
" v_texCoord = a_texCoord; \n"
"} \n");
static std::string fs_texture_2d_src(
"#version 300 es \n"
"precision mediump float; \n"
"in vec2 v_texCoord; \n"
"layout(location = 0) out vec4 outColor; \n"
"uniform sampler2D s_texture; \n"
"void main() \n"
"{ \n"
" outColor = texture( s_texture, v_texCoord ); \n"
"} \n");
static std::string vs_cubemap_src(
"#version 300 es \n"
"layout(location = 0) in vec4 a_position; \n"
"layout(location = 1) in vec3 a_normal; \n"
"out vec3 v_normal; \n"
"void main() \n"
"{ \n"
" gl_Position = a_position; \n"
" v_normal = a_normal; \n"
"} \n");
static std::string fs_cubemap_src(
"#version 300 es \n"
"precision mediump float; \n"
"in vec3 v_normal; \n"
"layout(location = 0) out vec4 outColor; \n"
"uniform samplerCube s_texture; \n"
"void main() \n"
"{ \n"
" outColor = texture(s_texture, v_normal); \n"
"} \n");
*/
}
}
| 44.825658 | 149 | 0.488736 |
2167af865b1236cabbe027af392640cc9abe4441 | 981 | cpp | C++ | ch15/test15_5.cpp | imshenzhuo/CppPrimer | 87c74c0a36223e86571c2aedd9da428c06b04f4d | [
"CC0-1.0"
] | 3 | 2019-09-21T13:03:57.000Z | 2020-04-05T02:42:53.000Z | ch15/test15_5.cpp | imshenzhuo/CppPrimer | 87c74c0a36223e86571c2aedd9da428c06b04f4d | [
"CC0-1.0"
] | null | null | null | ch15/test15_5.cpp | imshenzhuo/CppPrimer | 87c74c0a36223e86571c2aedd9da428c06b04f4d | [
"CC0-1.0"
] | null | null | null | /*************************************************************************
> File Name: test15_5.cpp
> Author: shenzhuo
> Mail: im.shenzhuo@gmail.com
> Created Time: 2019年09月19日 星期四 09时59分30秒
************************************************************************/
#include<iostream>
using namespace std;
class Base{
public:
int base_public;
protected:
int base_protected;
private:
int base_private;
};
class Pub_De : public Base {
public:
void f() {
cout << base_protected << endl;
}
};
class Pri_De : private Base
{
public:
void f() {
cout << base_public << endl;
cout << base_protected << endl;
// cout << base_private << endl;
}
};
int main(int argc, char const *argv[])
{
Pub_De pd;
pd.base_public = 100;
// error
// pd.base_protected = 100;
pd.f();
Pri_De ppd;
// ppd.base_protected = 100;
// ppd.base_public = 100;
ppd.f();
return 0;
}
| 17.210526 | 74 | 0.490316 |
2169d87f42c3bb36d5124a27fe42b92ffddc9bcf | 9,994 | cpp | C++ | deepracer_follow_the_leader_ws/build/deepracer_interfaces_pkg/rosidl_typesupport_c/deepracer_interfaces_pkg/srv/nav_throttle_srv__type_support.cpp | amitjain-3/working_add | ddd3b10d854477e86bf7a8558b3d447ec03a8a5f | [
"Apache-2.0"
] | 1 | 2022-03-11T20:15:27.000Z | 2022-03-11T20:15:27.000Z | deepracer_follow_the_leader_ws/build/deepracer_interfaces_pkg/rosidl_typesupport_c/deepracer_interfaces_pkg/srv/nav_throttle_srv__type_support.cpp | amitjain-3/working_add | ddd3b10d854477e86bf7a8558b3d447ec03a8a5f | [
"Apache-2.0"
] | null | null | null | deepracer_follow_the_leader_ws/build/deepracer_interfaces_pkg/rosidl_typesupport_c/deepracer_interfaces_pkg/srv/nav_throttle_srv__type_support.cpp | amitjain-3/working_add | ddd3b10d854477e86bf7a8558b3d447ec03a8a5f | [
"Apache-2.0"
] | null | null | null | // generated from rosidl_typesupport_c/resource/idl__type_support.cpp.em
// with input from deepracer_interfaces_pkg:srv/NavThrottleSrv.idl
// generated code does not contain a copyright notice
#include "cstddef"
#include "rosidl_runtime_c/message_type_support_struct.h"
#include "deepracer_interfaces_pkg/msg/rosidl_typesupport_c__visibility_control.h"
#include "deepracer_interfaces_pkg/srv/detail/nav_throttle_srv__struct.h"
#include "rosidl_typesupport_c/identifier.h"
#include "rosidl_typesupport_c/message_type_support_dispatch.h"
#include "rosidl_typesupport_c/type_support_map.h"
#include "rosidl_typesupport_c/visibility_control.h"
#include "rosidl_typesupport_interface/macros.h"
namespace deepracer_interfaces_pkg
{
namespace srv
{
namespace rosidl_typesupport_c
{
typedef struct _NavThrottleSrv_Request_type_support_ids_t
{
const char * typesupport_identifier[2];
} _NavThrottleSrv_Request_type_support_ids_t;
static const _NavThrottleSrv_Request_type_support_ids_t _NavThrottleSrv_Request_message_typesupport_ids = {
{
"rosidl_typesupport_fastrtps_c", // ::rosidl_typesupport_fastrtps_c::typesupport_identifier,
"rosidl_typesupport_introspection_c", // ::rosidl_typesupport_introspection_c::typesupport_identifier,
}
};
typedef struct _NavThrottleSrv_Request_type_support_symbol_names_t
{
const char * symbol_name[2];
} _NavThrottleSrv_Request_type_support_symbol_names_t;
#define STRINGIFY_(s) #s
#define STRINGIFY(s) STRINGIFY_(s)
static const _NavThrottleSrv_Request_type_support_symbol_names_t _NavThrottleSrv_Request_message_typesupport_symbol_names = {
{
STRINGIFY(ROSIDL_TYPESUPPORT_INTERFACE__MESSAGE_SYMBOL_NAME(rosidl_typesupport_fastrtps_c, deepracer_interfaces_pkg, srv, NavThrottleSrv_Request)),
STRINGIFY(ROSIDL_TYPESUPPORT_INTERFACE__MESSAGE_SYMBOL_NAME(rosidl_typesupport_introspection_c, deepracer_interfaces_pkg, srv, NavThrottleSrv_Request)),
}
};
typedef struct _NavThrottleSrv_Request_type_support_data_t
{
void * data[2];
} _NavThrottleSrv_Request_type_support_data_t;
static _NavThrottleSrv_Request_type_support_data_t _NavThrottleSrv_Request_message_typesupport_data = {
{
0, // will store the shared library later
0, // will store the shared library later
}
};
static const type_support_map_t _NavThrottleSrv_Request_message_typesupport_map = {
2,
"deepracer_interfaces_pkg",
&_NavThrottleSrv_Request_message_typesupport_ids.typesupport_identifier[0],
&_NavThrottleSrv_Request_message_typesupport_symbol_names.symbol_name[0],
&_NavThrottleSrv_Request_message_typesupport_data.data[0],
};
static const rosidl_message_type_support_t NavThrottleSrv_Request_message_type_support_handle = {
rosidl_typesupport_c__typesupport_identifier,
reinterpret_cast<const type_support_map_t *>(&_NavThrottleSrv_Request_message_typesupport_map),
rosidl_typesupport_c__get_message_typesupport_handle_function,
};
} // namespace rosidl_typesupport_c
} // namespace srv
} // namespace deepracer_interfaces_pkg
#ifdef __cplusplus
extern "C"
{
#endif
ROSIDL_TYPESUPPORT_C_EXPORT_deepracer_interfaces_pkg
const rosidl_message_type_support_t *
ROSIDL_TYPESUPPORT_INTERFACE__MESSAGE_SYMBOL_NAME(rosidl_typesupport_c, deepracer_interfaces_pkg, srv, NavThrottleSrv_Request)() {
return &::deepracer_interfaces_pkg::srv::rosidl_typesupport_c::NavThrottleSrv_Request_message_type_support_handle;
}
#ifdef __cplusplus
}
#endif
// already included above
// #include "cstddef"
// already included above
// #include "rosidl_runtime_c/message_type_support_struct.h"
// already included above
// #include "deepracer_interfaces_pkg/msg/rosidl_typesupport_c__visibility_control.h"
// already included above
// #include "deepracer_interfaces_pkg/srv/detail/nav_throttle_srv__struct.h"
// already included above
// #include "rosidl_typesupport_c/identifier.h"
// already included above
// #include "rosidl_typesupport_c/message_type_support_dispatch.h"
// already included above
// #include "rosidl_typesupport_c/type_support_map.h"
// already included above
// #include "rosidl_typesupport_c/visibility_control.h"
// already included above
// #include "rosidl_typesupport_interface/macros.h"
namespace deepracer_interfaces_pkg
{
namespace srv
{
namespace rosidl_typesupport_c
{
typedef struct _NavThrottleSrv_Response_type_support_ids_t
{
const char * typesupport_identifier[2];
} _NavThrottleSrv_Response_type_support_ids_t;
static const _NavThrottleSrv_Response_type_support_ids_t _NavThrottleSrv_Response_message_typesupport_ids = {
{
"rosidl_typesupport_fastrtps_c", // ::rosidl_typesupport_fastrtps_c::typesupport_identifier,
"rosidl_typesupport_introspection_c", // ::rosidl_typesupport_introspection_c::typesupport_identifier,
}
};
typedef struct _NavThrottleSrv_Response_type_support_symbol_names_t
{
const char * symbol_name[2];
} _NavThrottleSrv_Response_type_support_symbol_names_t;
#define STRINGIFY_(s) #s
#define STRINGIFY(s) STRINGIFY_(s)
static const _NavThrottleSrv_Response_type_support_symbol_names_t _NavThrottleSrv_Response_message_typesupport_symbol_names = {
{
STRINGIFY(ROSIDL_TYPESUPPORT_INTERFACE__MESSAGE_SYMBOL_NAME(rosidl_typesupport_fastrtps_c, deepracer_interfaces_pkg, srv, NavThrottleSrv_Response)),
STRINGIFY(ROSIDL_TYPESUPPORT_INTERFACE__MESSAGE_SYMBOL_NAME(rosidl_typesupport_introspection_c, deepracer_interfaces_pkg, srv, NavThrottleSrv_Response)),
}
};
typedef struct _NavThrottleSrv_Response_type_support_data_t
{
void * data[2];
} _NavThrottleSrv_Response_type_support_data_t;
static _NavThrottleSrv_Response_type_support_data_t _NavThrottleSrv_Response_message_typesupport_data = {
{
0, // will store the shared library later
0, // will store the shared library later
}
};
static const type_support_map_t _NavThrottleSrv_Response_message_typesupport_map = {
2,
"deepracer_interfaces_pkg",
&_NavThrottleSrv_Response_message_typesupport_ids.typesupport_identifier[0],
&_NavThrottleSrv_Response_message_typesupport_symbol_names.symbol_name[0],
&_NavThrottleSrv_Response_message_typesupport_data.data[0],
};
static const rosidl_message_type_support_t NavThrottleSrv_Response_message_type_support_handle = {
rosidl_typesupport_c__typesupport_identifier,
reinterpret_cast<const type_support_map_t *>(&_NavThrottleSrv_Response_message_typesupport_map),
rosidl_typesupport_c__get_message_typesupport_handle_function,
};
} // namespace rosidl_typesupport_c
} // namespace srv
} // namespace deepracer_interfaces_pkg
#ifdef __cplusplus
extern "C"
{
#endif
ROSIDL_TYPESUPPORT_C_EXPORT_deepracer_interfaces_pkg
const rosidl_message_type_support_t *
ROSIDL_TYPESUPPORT_INTERFACE__MESSAGE_SYMBOL_NAME(rosidl_typesupport_c, deepracer_interfaces_pkg, srv, NavThrottleSrv_Response)() {
return &::deepracer_interfaces_pkg::srv::rosidl_typesupport_c::NavThrottleSrv_Response_message_type_support_handle;
}
#ifdef __cplusplus
}
#endif
// already included above
// #include "cstddef"
#include "rosidl_runtime_c/service_type_support_struct.h"
// already included above
// #include "deepracer_interfaces_pkg/msg/rosidl_typesupport_c__visibility_control.h"
// already included above
// #include "rosidl_typesupport_c/identifier.h"
#include "rosidl_typesupport_c/service_type_support_dispatch.h"
// already included above
// #include "rosidl_typesupport_c/type_support_map.h"
// already included above
// #include "rosidl_typesupport_interface/macros.h"
namespace deepracer_interfaces_pkg
{
namespace srv
{
namespace rosidl_typesupport_c
{
typedef struct _NavThrottleSrv_type_support_ids_t
{
const char * typesupport_identifier[2];
} _NavThrottleSrv_type_support_ids_t;
static const _NavThrottleSrv_type_support_ids_t _NavThrottleSrv_service_typesupport_ids = {
{
"rosidl_typesupport_fastrtps_c", // ::rosidl_typesupport_fastrtps_c::typesupport_identifier,
"rosidl_typesupport_introspection_c", // ::rosidl_typesupport_introspection_c::typesupport_identifier,
}
};
typedef struct _NavThrottleSrv_type_support_symbol_names_t
{
const char * symbol_name[2];
} _NavThrottleSrv_type_support_symbol_names_t;
#define STRINGIFY_(s) #s
#define STRINGIFY(s) STRINGIFY_(s)
static const _NavThrottleSrv_type_support_symbol_names_t _NavThrottleSrv_service_typesupport_symbol_names = {
{
STRINGIFY(ROSIDL_TYPESUPPORT_INTERFACE__SERVICE_SYMBOL_NAME(rosidl_typesupport_fastrtps_c, deepracer_interfaces_pkg, srv, NavThrottleSrv)),
STRINGIFY(ROSIDL_TYPESUPPORT_INTERFACE__SERVICE_SYMBOL_NAME(rosidl_typesupport_introspection_c, deepracer_interfaces_pkg, srv, NavThrottleSrv)),
}
};
typedef struct _NavThrottleSrv_type_support_data_t
{
void * data[2];
} _NavThrottleSrv_type_support_data_t;
static _NavThrottleSrv_type_support_data_t _NavThrottleSrv_service_typesupport_data = {
{
0, // will store the shared library later
0, // will store the shared library later
}
};
static const type_support_map_t _NavThrottleSrv_service_typesupport_map = {
2,
"deepracer_interfaces_pkg",
&_NavThrottleSrv_service_typesupport_ids.typesupport_identifier[0],
&_NavThrottleSrv_service_typesupport_symbol_names.symbol_name[0],
&_NavThrottleSrv_service_typesupport_data.data[0],
};
static const rosidl_service_type_support_t NavThrottleSrv_service_type_support_handle = {
rosidl_typesupport_c__typesupport_identifier,
reinterpret_cast<const type_support_map_t *>(&_NavThrottleSrv_service_typesupport_map),
rosidl_typesupport_c__get_service_typesupport_handle_function,
};
} // namespace rosidl_typesupport_c
} // namespace srv
} // namespace deepracer_interfaces_pkg
#ifdef __cplusplus
extern "C"
{
#endif
ROSIDL_TYPESUPPORT_C_EXPORT_deepracer_interfaces_pkg
const rosidl_service_type_support_t *
ROSIDL_TYPESUPPORT_INTERFACE__SERVICE_SYMBOL_NAME(rosidl_typesupport_c, deepracer_interfaces_pkg, srv, NavThrottleSrv)() {
return &::deepracer_interfaces_pkg::srv::rosidl_typesupport_c::NavThrottleSrv_service_type_support_handle;
}
#ifdef __cplusplus
}
#endif
| 33.877966 | 157 | 0.843606 |
216aa3a32caa8ada6f2adda842ffc176e2b4676a | 1,491 | cpp | C++ | libnd4j/include/helpers/impl/ProviderRNG.cpp | KolyaIvankov/deeplearning4j | 61c02d31fa950259d7458a021de7db167a3410ae | [
"Apache-2.0"
] | null | null | null | libnd4j/include/helpers/impl/ProviderRNG.cpp | KolyaIvankov/deeplearning4j | 61c02d31fa950259d7458a021de7db167a3410ae | [
"Apache-2.0"
] | null | null | null | libnd4j/include/helpers/impl/ProviderRNG.cpp | KolyaIvankov/deeplearning4j | 61c02d31fa950259d7458a021de7db167a3410ae | [
"Apache-2.0"
] | null | null | null | /*******************************************************************************
* Copyright (c) 2015-2018 Skymind, Inc.
*
* This program and the accompanying materials are made available under the
* terms of the Apache License, Version 2.0 which is available at
* https://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.
*
* SPDX-License-Identifier: Apache-2.0
******************************************************************************/
//
// Created by Yurii Shyrma on 27.01.2018
//
#include <helpers/ProviderRNG.h>
#include <NativeOps.h>
namespace nd4j {
ProviderRNG::ProviderRNG() {
Nd4jLong *buffer = new Nd4jLong[100000];
std::lock_guard<std::mutex> lock(_mutex);
#ifndef __CUDABLAS__
// at this moment we don't have streams etc, so let's just skip this for now
_rng = (nd4j::random::RandomBuffer *) initRandom(nullptr, 123, 100000, (Nd4jPointer) buffer);
#endif
// if(_rng != nullptr)
}
ProviderRNG& ProviderRNG::getInstance() {
static ProviderRNG instance;
return instance;
}
random::RandomBuffer* ProviderRNG::getRNG() const {
return _rng;
}
std::mutex ProviderRNG::_mutex;
}
| 28.673077 | 101 | 0.625755 |
216b4c5019c4577b7d7b6eca4f3fa3c53b0ab716 | 345 | cpp | C++ | controller_benchmark/src/controller_benchmark_node.cpp | altshuler/mavros_controllers | cbcd9bb5f39923a1633f07c946662859148b84ad | [
"BSD-3-Clause"
] | 1 | 2022-03-25T13:54:02.000Z | 2022-03-25T13:54:02.000Z | controller_benchmark/src/controller_benchmark_node.cpp | altshuler/mavros_controllers | cbcd9bb5f39923a1633f07c946662859148b84ad | [
"BSD-3-Clause"
] | null | null | null | controller_benchmark/src/controller_benchmark_node.cpp | altshuler/mavros_controllers | cbcd9bb5f39923a1633f07c946662859148b84ad | [
"BSD-3-Clause"
] | 1 | 2021-10-21T07:17:17.000Z | 2021-10-21T07:17:17.000Z | // July/2018, ETHZ, Jaeyoung Lim, jalim@student.ethz.ch
#include "controller_benchmark/controller_benchmark.h"
int main(int argc, char** argv) {
ros::init(argc,argv,"geometric_controller");
ros::NodeHandle nh("");
ros::NodeHandle nh_private("~");
ControllerEvaluator geometricController(nh, nh_private);
ros::spin();
return 0;
}
| 24.642857 | 58 | 0.718841 |
2173d652f61867037b50442277f36bca9603f213 | 2,651 | cpp | C++ | libs/lfd/src/resource_file.cpp | tiaanl/red5 | ea7593b38f61f64f8aeb7d58854106bd58c05736 | [
"MIT"
] | 1 | 2020-11-24T13:26:11.000Z | 2020-11-24T13:26:11.000Z | libs/lfd/src/resource_file.cpp | tiaanl/red5 | ea7593b38f61f64f8aeb7d58854106bd58c05736 | [
"MIT"
] | null | null | null | libs/lfd/src/resource_file.cpp | tiaanl/red5 | ea7593b38f61f64f8aeb7d58854106bd58c05736 | [
"MIT"
] | null | null | null | #include "lfd/resource_file.h"
#include <base/streams/file_input_stream.h>
#include <base/streams/file_output_stream.h>
std::vector<ResourceEntry> ResourceFile::loadEntries() const {
if (!std::filesystem::exists(m_path)) {
spdlog::error("Resource file not found: {}", m_path.string());
return {};
}
spdlog::info("Loading entries from resource file: {}", m_path.string());
base::FileInputStream stream{m_path};
// TODO: Check if the file was opened successfully.
// Read ResourceMap header.
auto type = static_cast<ResourceType>(stream.readU32());
if (type != ResourceType::ResourceMap) {
spdlog::error("Invalid LFD file. ({})", m_path.string());
return {};
}
U8 name[9] = {};
stream.read(name, 8);
U32 size = stream.readU32();
#if 0
spdlog::info("ResourceMap :: type: {}, name: {}, size: {}", resourceTypeToString(type), name, size);
#endif // 0
// Skip the header block and get the details from the individual resource headers.
stream.advance(size);
std::vector<ResourceEntry> entries;
for (MemSize i = 0; i < size / 16; ++i) {
auto resource = readResourceEntry(&stream);
if (resource.has_value()) {
#if 0
spdlog::info("entry: ({}) {}", resourceTypeToString(resource.value().type()),
resource.value().name());
#endif // 0
entries.emplace_back(std::move(resource.value()));
}
}
return entries;
}
// static
std::optional<ResourceEntry> ResourceFile::readResourceEntry(base::InputStream* stream) {
ResourceType type = static_cast<ResourceType>(stream->readU32());
char name[9] = {};
stream->read(name, 8);
U32 size = stream->readU32();
std::vector<U8> data;
data.resize(size);
stream->read(data.data(), size);
return ResourceEntry{type, name, std::move(data)};
}
void writeHeader(base::OutputStream* stream, ResourceType resourceType, std::string_view name,
MemSize size) {
stream->writeU32(static_cast<U32>(resourceType));
U8 nameBuf[8] = {};
std::memcpy(nameBuf, name.data(), std::min(name.length(), sizeof(nameBuf)));
stream->write(nameBuf, sizeof(nameBuf));
stream->writeU32(static_cast<U32>(size));
}
void ResourceFile::saveEntries(const std::vector<ResourceEntry>& entries) {
base::FileOutputStream stream{m_path};
writeHeader(&stream, ResourceType::ResourceMap, "resource", entries.size() * 16);
for (auto& entry : entries) {
writeHeader(&stream, entry.type(), entry.name(), entry.data().size());
}
for (auto& entry : entries) {
writeHeader(&stream, entry.type(), entry.name(), entry.data().size());
stream.write(entry.data().data(), entry.data().size());
}
}
| 29.786517 | 102 | 0.6639 |
217423409a00425bb13f67bf7542aa5cbea05f18 | 6,524 | cpp | C++ | src/Mesh.cpp | henriquetmaia/NitroFluid | b4262e7d2b7a49b942466b9a4123322950c52da8 | [
"BSD-4-Clause"
] | 1 | 2017-07-31T03:24:42.000Z | 2017-07-31T03:24:42.000Z | src/Mesh.cpp | henriquetmaia/NitroFluid | b4262e7d2b7a49b942466b9a4123322950c52da8 | [
"BSD-4-Clause"
] | null | null | null | src/Mesh.cpp | henriquetmaia/NitroFluid | b4262e7d2b7a49b942466b9a4123322950c52da8 | [
"BSD-4-Clause"
] | 1 | 2019-06-06T14:59:04.000Z | 2019-06-06T14:59:04.000Z | #include <map>
#include <fstream>
#include "Mesh.h"
#include "MeshIO.h"
using namespace std;
namespace DDG
{
Mesh :: Mesh( void )
{}
Mesh :: Mesh( const Mesh& mesh )
{
*this = mesh;
}
class HalfEdgeIterCompare { public: bool operator()( const HalfEdgeIter& i, const HalfEdgeIter& j ) const { return &*i < &*j; } };
class HalfEdgeCIterCompare { public: bool operator()( const HalfEdgeCIter& i, const HalfEdgeCIter& j ) const { return &*i < &*j; } };
class VertexIterCompare { public: bool operator()( const VertexIter& i, const VertexIter& j ) const { return &*i < &*j; } };
class VertexCIterCompare { public: bool operator()( const VertexCIter& i, const VertexCIter& j ) const { return &*i < &*j; } };
class FaceIterCompare { public: bool operator()( const FaceIter& i, const FaceIter& j ) const { return &*i < &*j; } };
class FaceCIterCompare { public: bool operator()( const FaceCIter& i, const FaceCIter& j ) const { return &*i < &*j; } };
class EdgeIterCompare { public: bool operator()( const EdgeIter& i, const EdgeIter& j ) const { return &*i < &*j; } };
class EdgeCIterCompare { public: bool operator()( const EdgeCIter& i, const EdgeCIter& j ) const { return &*i < &*j; } };
const Mesh& Mesh :: operator=( const Mesh& mesh )
{
map< HalfEdgeCIter, HalfEdgeIter, HalfEdgeCIterCompare > halfedgeOldToNew;
map< VertexCIter, VertexIter, VertexCIterCompare > vertexOldToNew;
map< EdgeCIter, EdgeIter, EdgeCIterCompare > edgeOldToNew;
map< FaceCIter, FaceIter, FaceCIterCompare > faceOldToNew;
// copy geometry from the original mesh and create a
// map from pointers in the original mesh to
// those in the new mesh
halfedges.clear(); for( HalfEdgeCIter he = mesh.halfedges.begin(); he != mesh.halfedges.end(); he++ ) halfedgeOldToNew[ he ] = halfedges.insert( halfedges.end(), *he );
vertices.clear(); for( VertexCIter v = mesh.vertices.begin(); v != mesh.vertices.end(); v++ ) vertexOldToNew[ v ] = vertices.insert( vertices.end(), *v );
edges.clear(); for( EdgeCIter e = mesh.edges.begin(); e != mesh.edges.end(); e++ ) edgeOldToNew[ e ] = edges.insert( edges.end(), *e );
faces.clear(); for( FaceCIter f = mesh.faces.begin(); f != mesh.faces.end(); f++ ) faceOldToNew[ f ] = faces.insert( faces.end(), *f );
// "search and replace" old pointers with new ones
for( HalfEdgeIter he = halfedges.begin(); he != halfedges.end(); he++ )
{
he->next = halfedgeOldToNew[ he->next ];
he->flip = halfedgeOldToNew[ he->flip ];
he->vertex = vertexOldToNew[ he->vertex ];
he->edge = edgeOldToNew[ he->edge ];
he->face = faceOldToNew[ he->face ];
}
for( VertexIter v = vertices.begin(); v != vertices.end(); v++ ) v->he = halfedgeOldToNew[ v->he ];
for( EdgeIter e = edges.begin(); e != edges.end(); e++ ) e->he = halfedgeOldToNew[ e->he ];
for( FaceIter f = faces.begin(); f != faces.end(); f++ ) f->he = halfedgeOldToNew[ f->he ];
return *this;
}
int Mesh::read( const string& filename )
{
inputFilename = filename;
ifstream in( filename.c_str() );
if( !in.is_open() )
{
cerr << "Error reading from mesh file " << filename << endl;
return 1;
}
int rval;
if( !( rval = MeshIO::read( in, *this )))
{
normalize();
indexVertices();
indexEdges();
indexFaces();
}
return rval;
}
int Mesh::write( const string& filename ) const
// reads a mesh from a Wavefront OBJ file; return value is nonzero
// only if there was an error
{
ofstream out( filename.c_str() );
if( !out.is_open() )
{
cerr << "Error writing to mesh file " << filename << endl;
return 1;
}
MeshIO::write( out, *this );
return 0;
}
bool Mesh::reload( void )
{
return read( inputFilename );
}
void Mesh::normalize( void )
{
// compute center of mass
Vector c( 0., 0., 0. );
for( VertexCIter v = vertices.begin(); v != vertices.end(); v++ )
{
c += v->position;
}
c /= (double) vertices.size();
// translate to origin
for( VertexIter v = vertices.begin(); v != vertices.end(); v++ )
{
v->position -= c;
}
// rescale such that the mesh sits inside the unit ball
double rMax = 0.;
for( VertexCIter v = vertices.begin(); v != vertices.end(); v++ )
{
rMax = max( rMax, v->position.norm() );
}
for( VertexIter v = vertices.begin(); v != vertices.end(); v++ )
{
v->position /= rMax;
}
}
void Mesh::indexVertices( void )
{
unsigned count = 0;
for( VertexIter v = vertices.begin(); v != vertices.end(); ++v )
{
v->setID( count );
++count;
}
assert( count == vertices.size() );
}
void Mesh::indexEdges( void )
{
unsigned count = 0;
for( EdgeIter e = edges.begin(); e != edges.end(); ++e )
{
e->setID( count );
++count;
}
assert( count == edges.size() );
}
void Mesh::indexFaces( void )
{
unsigned count = 0;
for( FaceIter f = faces.begin(); f != faces.end(); ++f )
{
f->setID( count );
++count;
}
assert( count == faces.size() );
}
void Mesh::buildLaplacian( )
{
laplacian.resize( vertices.size(), vertices.size() );
for( VertexCIter v = vertices.begin(); v != vertices.end(); v++ )
{
int u_id = v->getID();
HalfEdgeCIter h = v->he;
do
{
double weight = 0.5 * ( h->cotan() + h->flip->cotan() );
int j_id = h->next->vertex->getID();
laplacian( u_id, j_id ) -= weight;
laplacian( u_id, u_id ) += weight;
h = h->flip->next;
}
while( h != v->he );
}
}
// void Mesh::solveScalarPoissonProblem( void )
// {
// }
}
| 34.157068 | 175 | 0.516708 |
2175d53d0705dd963399a9aa73bb84b81a9ecb1c | 1,056 | cpp | C++ | source/System/ThreadPool/ThreadPool.cpp | Fabrice-Praxinos/ULIS | 232ad5c0804da1202d8231fda67ff4aea70f57ef | [
"RSA-MD"
] | 30 | 2020-09-16T17:39:36.000Z | 2022-02-17T08:32:53.000Z | source/System/ThreadPool/ThreadPool.cpp | Fabrice-Praxinos/ULIS | 232ad5c0804da1202d8231fda67ff4aea70f57ef | [
"RSA-MD"
] | 7 | 2020-11-23T14:37:15.000Z | 2022-01-17T11:35:32.000Z | source/System/ThreadPool/ThreadPool.cpp | Fabrice-Praxinos/ULIS | 232ad5c0804da1202d8231fda67ff4aea70f57ef | [
"RSA-MD"
] | 5 | 2020-09-17T00:39:14.000Z | 2021-08-30T16:14:07.000Z | // IDDN FR.001.250001.004.S.X.2019.000.00000
// ULIS is subject to copyright laws and is the legal and intellectual property of Praxinos,Inc
/*
* ULIS
*__________________
* @file ThreadPool.cpp
* @author Clement Berthaud
* @brief This file provides the definition for the FThreadPool class.
* @copyright Copyright 2018-2021 Praxinos, Inc. All Rights Reserved.
* @license Please refer to LICENSE.md
*/
#include "System/ThreadPool/ThreadPool.h"
#include "System/ThreadPool/ThreadPool_Private.h"
ULIS_NAMESPACE_BEGIN
FThreadPool::~FThreadPool()
{
delete d;
}
FThreadPool::FThreadPool( uint32 iNumWorkers )
: d( new FThreadPool_Private( iNumWorkers ) )
{
}
void
FThreadPool::WaitForCompletion()
{
d->WaitForCompletion();
}
void
FThreadPool::SetNumWorkers( uint32 iNumWorkers )
{
d->SetNumWorkers( iNumWorkers );
}
uint32
FThreadPool::GetNumWorkers() const
{
return d->GetNumWorkers();
}
//static
uint32
FThreadPool::MaxWorkers()
{
return FThreadPool_Private::MaxWorkers();
}
ULIS_NAMESPACE_END
| 19.924528 | 95 | 0.726326 |
2176fc5c1440deffd1d7d730d1a7a59bbbaadeda | 15,840 | cpp | C++ | src/mame/drivers/mjsister.cpp | Robbbert/messui | 49b756e2140d8831bc81335298ee8c5471045e79 | [
"BSD-3-Clause"
] | 26 | 2015-03-31T06:25:51.000Z | 2021-12-14T09:29:04.000Z | src/mame/drivers/mjsister.cpp | Robbbert/messui | 49b756e2140d8831bc81335298ee8c5471045e79 | [
"BSD-3-Clause"
] | null | null | null | src/mame/drivers/mjsister.cpp | Robbbert/messui | 49b756e2140d8831bc81335298ee8c5471045e79 | [
"BSD-3-Clause"
] | 10 | 2015-03-27T05:45:51.000Z | 2022-02-04T06:57:36.000Z | // license:BSD-3-Clause
// copyright-holders:Uki
/*****************************************************************************
Mahjong Sisters (c) 1986 Toa Plan
Driver by Uki
*****************************************************************************/
#include "emu.h"
#include "cpu/z80/z80.h"
#include "machine/74259.h"
#include "video/mc6845.h"
#include "sound/ay8910.h"
#include "sound/dac.h"
#include "emupal.h"
#include "screen.h"
#include "speaker.h"
#define MCLK 12000000
class mjsister_state : public driver_device
{
public:
mjsister_state(const machine_config &mconfig, device_type type, const char *tag) :
driver_device(mconfig, type, tag),
m_maincpu(*this, "maincpu"),
m_mainlatch(*this, "mainlatch%u", 1),
m_palette(*this, "palette"),
m_crtc(*this, "crtc"),
m_dac(*this, "dac"),
m_rombank(*this, "rombank"),
m_vrambank(*this, "vrambank")
{ }
void mjsister(machine_config &config);
protected:
virtual void machine_start() override;
virtual void machine_reset() override;
virtual void device_timer(emu_timer &timer, device_timer_id id, int param, void *ptr) override;
private:
enum
{
TIMER_DAC
};
/* video-related */
bool m_video_enable;
int m_colorbank;
/* misc */
int m_input_sel1;
int m_input_sel2;
bool m_irq_enable;
uint32_t m_dac_adr;
uint32_t m_dac_bank;
uint32_t m_dac_adr_s;
uint32_t m_dac_adr_e;
uint32_t m_dac_busy;
/* devices */
required_device<cpu_device> m_maincpu;
required_device_array<ls259_device, 2> m_mainlatch;
required_device<palette_device> m_palette;
required_device<hd6845s_device> m_crtc;
required_device<dac_byte_interface> m_dac;
/* memory */
required_memory_bank m_rombank;
required_memory_bank m_vrambank;
std::unique_ptr<uint8_t[]> m_vram;
void dac_adr_s_w(uint8_t data);
void dac_adr_e_w(uint8_t data);
DECLARE_WRITE_LINE_MEMBER(rombank_w);
DECLARE_WRITE_LINE_MEMBER(flip_screen_w);
DECLARE_WRITE_LINE_MEMBER(colorbank_w);
DECLARE_WRITE_LINE_MEMBER(video_enable_w);
DECLARE_WRITE_LINE_MEMBER(irq_enable_w);
DECLARE_WRITE_LINE_MEMBER(vrambank_w);
DECLARE_WRITE_LINE_MEMBER(dac_bank_w);
DECLARE_WRITE_LINE_MEMBER(coin_counter_w);
void input_sel1_w(uint8_t data);
void input_sel2_w(uint8_t data);
uint8_t keys_r();
TIMER_CALLBACK_MEMBER(dac_callback);
INTERRUPT_GEN_MEMBER(interrupt);
uint32_t screen_update(screen_device &screen, bitmap_rgb32 &bitmap, const rectangle &cliprect);
void mjsister_io_map(address_map &map);
void mjsister_map(address_map &map);
emu_timer *m_dac_timer;
MC6845_UPDATE_ROW(crtc_update_row);
};
/*************************************
*
* Video emulation
*
*************************************/
uint32_t mjsister_state::screen_update(screen_device &screen, bitmap_rgb32 &bitmap, const rectangle &cliprect)
{
if (m_video_enable)
m_crtc->screen_update(screen, bitmap, cliprect);
else
bitmap.fill(m_palette->black_pen(), cliprect);
return 0;
}
MC6845_UPDATE_ROW( mjsister_state::crtc_update_row )
{
const pen_t *pen = m_palette->pens();
if (flip_screen())
y = 240 - y;
for (int i = 0; i < x_count; i++)
{
uint8_t x1 = i * 2 + 0;
uint8_t x2 = i * 2 + 1;
if (flip_screen())
{
x1 = 256 - x1;
x2 = 256 - x2;
}
// background layer
uint8_t data_bg = m_vram[0x400 + ((ma << 3) | (ra << 7) | i)];
bitmap.pix(y, x1) = pen[m_colorbank << 5 | ((data_bg & 0x0f) >> 0)];
bitmap.pix(y, x2) = pen[m_colorbank << 5 | ((data_bg & 0xf0) >> 4)];
// foreground layer
uint8_t data_fg = m_vram[0x8000 | (0x400 + ((ma << 3) | (ra << 7) | i))];
uint8_t c1 = ((data_fg & 0x0f) >> 0);
uint8_t c2 = ((data_fg & 0xf0) >> 4);
// 0 is transparent
if (c1) bitmap.pix(y, x1) = pen[m_colorbank << 5 | 0x10 | c1];
if (c2) bitmap.pix(y, x2) = pen[m_colorbank << 5 | 0x10 | c2];
}
}
/*************************************
*
* Memory handlers
*
*************************************/
void mjsister_state::device_timer(emu_timer &timer, device_timer_id id, int param, void *ptr)
{
switch(id)
{
case TIMER_DAC:
dac_callback(ptr, param);
break;
default:
throw emu_fatalerror("Unknown id in mjsister_state::device_timer");
}
}
TIMER_CALLBACK_MEMBER(mjsister_state::dac_callback)
{
uint8_t *DACROM = memregion("samples")->base();
m_dac->write(DACROM[(m_dac_bank * 0x10000 + m_dac_adr++) & 0x1ffff]);
if (((m_dac_adr & 0xff00 ) >> 8) != m_dac_adr_e)
m_dac_timer->adjust(attotime::from_hz(MCLK) * 1024);
else
m_dac_busy = 0;
}
void mjsister_state::dac_adr_s_w(uint8_t data)
{
m_dac_adr_s = data;
}
void mjsister_state::dac_adr_e_w(uint8_t data)
{
m_dac_adr_e = data;
m_dac_adr = m_dac_adr_s << 8;
if (m_dac_busy == 0)
synchronize(TIMER_DAC);
m_dac_busy = 1;
}
WRITE_LINE_MEMBER(mjsister_state::rombank_w)
{
m_rombank->set_entry((m_mainlatch[0]->q0_r() << 1) | m_mainlatch[1]->q6_r());
}
WRITE_LINE_MEMBER(mjsister_state::flip_screen_w)
{
flip_screen_set(state);
}
WRITE_LINE_MEMBER(mjsister_state::colorbank_w)
{
m_colorbank = (m_mainlatch[0]->output_state() >> 2) & 7;
}
WRITE_LINE_MEMBER(mjsister_state::video_enable_w)
{
m_video_enable = state;
}
WRITE_LINE_MEMBER(mjsister_state::irq_enable_w)
{
m_irq_enable = state;
if (!m_irq_enable)
m_maincpu->set_input_line(0, CLEAR_LINE);
}
WRITE_LINE_MEMBER(mjsister_state::vrambank_w)
{
m_vrambank->set_entry(state);
}
WRITE_LINE_MEMBER(mjsister_state::dac_bank_w)
{
m_dac_bank = state;
}
WRITE_LINE_MEMBER(mjsister_state::coin_counter_w)
{
machine().bookkeeping().coin_counter_w(0, state);
}
void mjsister_state::input_sel1_w(uint8_t data)
{
m_input_sel1 = data;
}
void mjsister_state::input_sel2_w(uint8_t data)
{
m_input_sel2 = data;
}
uint8_t mjsister_state::keys_r()
{
int p, i, ret = 0;
static const char *const keynames[] = { "KEY0", "KEY1", "KEY2", "KEY3", "KEY4", "KEY5" };
p = m_input_sel1 & 0x3f;
// p |= ((m_input_sel2 & 8) << 4) | ((m_input_sel2 & 0x20) << 1);
for (i = 0; i < 6; i++)
{
if (BIT(p, i))
ret |= ioport(keynames[i])->read();
}
return ret;
}
/*************************************
*
* Address maps
*
*************************************/
void mjsister_state::mjsister_map(address_map &map)
{
map(0x0000, 0x77ff).rom();
map(0x7800, 0x7fff).ram();
map(0x8000, 0xffff).bankr("rombank").bankw("vrambank");
}
void mjsister_state::mjsister_io_map(address_map &map)
{
map.global_mask(0xff);
map(0x00, 0x00).w(m_crtc, FUNC(hd6845s_device::address_w));
map(0x01, 0x01).rw(m_crtc, FUNC(hd6845s_device::register_r), FUNC(hd6845s_device::register_w));
map(0x10, 0x10).w("aysnd", FUNC(ay8910_device::address_w));
map(0x11, 0x11).r("aysnd", FUNC(ay8910_device::data_r));
map(0x12, 0x12).w("aysnd", FUNC(ay8910_device::data_w));
map(0x20, 0x20).r(FUNC(mjsister_state::keys_r));
map(0x21, 0x21).portr("IN0");
map(0x30, 0x30).w("mainlatch1", FUNC(ls259_device::write_nibble_d0));
map(0x31, 0x31).w("mainlatch2", FUNC(ls259_device::write_nibble_d0));
map(0x32, 0x32).w(FUNC(mjsister_state::input_sel1_w));
map(0x33, 0x33).w(FUNC(mjsister_state::input_sel2_w));
map(0x34, 0x34).w(FUNC(mjsister_state::dac_adr_s_w));
map(0x35, 0x35).w(FUNC(mjsister_state::dac_adr_e_w));
// map(0x36, 0x36) // writes 0xf8 here once
}
/*************************************
*
* Input ports
*
*************************************/
static INPUT_PORTS_START( mjsister )
PORT_START("DSW1")
PORT_DIPNAME( 0x07, 0x07, DEF_STR( Coinage ) ) PORT_DIPLOCATION("DSW1:8,7,6")
PORT_DIPSETTING( 0x03, DEF_STR( 5C_1C ) )
PORT_DIPSETTING( 0x00, DEF_STR( 4C_1C ) )
PORT_DIPSETTING( 0x01, DEF_STR( 3C_1C ) )
PORT_DIPSETTING( 0x02, DEF_STR( 2C_1C ) )
PORT_DIPSETTING( 0x07, DEF_STR( 1C_1C ) )
PORT_DIPSETTING( 0x06, DEF_STR( 1C_2C ) )
PORT_DIPSETTING( 0x05, DEF_STR( 1C_3C ) )
PORT_DIPSETTING( 0x04, DEF_STR( 1C_4C ) )
PORT_DIPUNUSED_DIPLOC( 0x08, 0x08, "DSW1:5")
PORT_DIPNAME( 0x30, 0x30, DEF_STR( Difficulty ) ) PORT_DIPLOCATION("DSW1:4,3") // see code at $141C
PORT_DIPSETTING( 0x30, "0" )
PORT_DIPSETTING( 0x20, "1" )
PORT_DIPSETTING( 0x10, "2" )
PORT_DIPSETTING( 0x00, "3" )
PORT_DIPNAME( 0x40, 0x40, DEF_STR( Test ) ) PORT_DIPLOCATION("DSW1:2")
PORT_DIPSETTING( 0x40, DEF_STR( Off ) )
PORT_DIPSETTING( 0x00, DEF_STR( On ) )
PORT_DIPNAME( 0x80, 0x80, DEF_STR( Flip_Screen ) ) PORT_DIPLOCATION("DSW1:1")
PORT_DIPSETTING( 0x80, DEF_STR( Off ) )
PORT_DIPSETTING( 0x00, DEF_STR( On ) )
PORT_START("DSW2") /* not on PCB */
PORT_BIT( 0xff, IP_ACTIVE_LOW, IPT_UNUSED )
PORT_START("IN0")
PORT_BIT( 0x01, IP_ACTIVE_HIGH, IPT_COIN2 )
PORT_BIT( 0x02, IP_ACTIVE_HIGH, IPT_SERVICE3 ) PORT_OPTIONAL PORT_NAME("Memory Reset 1") // only tested in service mode?
PORT_BIT( 0x04, IP_ACTIVE_HIGH, IPT_GAMBLE_BOOK ) PORT_OPTIONAL PORT_NAME("Analyzer") // only tested in service mode?
PORT_BIT( 0x08, IP_ACTIVE_HIGH, IPT_SERVICE ) PORT_TOGGLE
PORT_BIT( 0x10, IP_ACTIVE_HIGH, IPT_SERVICE4 ) PORT_OPTIONAL PORT_NAME("Memory Reset 2") // only tested in service mode?
PORT_BIT( 0x20, IP_ACTIVE_HIGH, IPT_GAMBLE_PAYOUT ) PORT_OPTIONAL // only tested in service mode?
PORT_BIT( 0x40, IP_ACTIVE_HIGH, IPT_COIN1 )
PORT_BIT( 0x80, IP_ACTIVE_HIGH, IPT_OTHER ) PORT_NAME("Hopper") PORT_CODE(KEYCODE_8) // only tested in service mode?
PORT_START("KEY0")
PORT_BIT( 0x01, IP_ACTIVE_HIGH, IPT_MAHJONG_A )
PORT_BIT( 0x02, IP_ACTIVE_HIGH, IPT_MAHJONG_B )
PORT_BIT( 0x04, IP_ACTIVE_HIGH, IPT_MAHJONG_C )
PORT_BIT( 0x08, IP_ACTIVE_HIGH, IPT_MAHJONG_D )
PORT_BIT( 0x10, IP_ACTIVE_HIGH, IPT_MAHJONG_LAST_CHANCE )
PORT_BIT( 0xe0, IP_ACTIVE_HIGH, IPT_UNUSED )
PORT_START("KEY1")
PORT_BIT( 0x01, IP_ACTIVE_HIGH, IPT_MAHJONG_E )
PORT_BIT( 0x02, IP_ACTIVE_HIGH, IPT_MAHJONG_F )
PORT_BIT( 0x04, IP_ACTIVE_HIGH, IPT_MAHJONG_G )
PORT_BIT( 0x08, IP_ACTIVE_HIGH, IPT_MAHJONG_H )
PORT_BIT( 0x10, IP_ACTIVE_HIGH, IPT_MAHJONG_SCORE )
PORT_BIT( 0xe0, IP_ACTIVE_HIGH, IPT_UNUSED )
PORT_START("KEY2")
PORT_BIT( 0x01, IP_ACTIVE_HIGH, IPT_MAHJONG_I )
PORT_BIT( 0x02, IP_ACTIVE_HIGH, IPT_MAHJONG_J )
PORT_BIT( 0x04, IP_ACTIVE_HIGH, IPT_MAHJONG_K )
PORT_BIT( 0x08, IP_ACTIVE_HIGH, IPT_MAHJONG_L )
PORT_BIT( 0x10, IP_ACTIVE_HIGH, IPT_MAHJONG_DOUBLE_UP )
PORT_BIT( 0xe0, IP_ACTIVE_HIGH, IPT_UNUSED )
PORT_START("KEY3")
PORT_BIT( 0x01, IP_ACTIVE_HIGH, IPT_MAHJONG_M )
PORT_BIT( 0x02, IP_ACTIVE_HIGH, IPT_MAHJONG_N )
PORT_BIT( 0x04, IP_ACTIVE_HIGH, IPT_MAHJONG_CHI )
PORT_BIT( 0x08, IP_ACTIVE_HIGH, IPT_MAHJONG_PON )
PORT_BIT( 0x10, IP_ACTIVE_HIGH, IPT_MAHJONG_FLIP_FLOP )
PORT_BIT( 0xe0, IP_ACTIVE_HIGH, IPT_UNUSED )
PORT_START("KEY4")
PORT_BIT( 0x01, IP_ACTIVE_HIGH, IPT_MAHJONG_KAN )
PORT_BIT( 0x02, IP_ACTIVE_HIGH, IPT_MAHJONG_REACH )
PORT_BIT( 0x04, IP_ACTIVE_HIGH, IPT_MAHJONG_RON )
PORT_BIT( 0x08, IP_ACTIVE_HIGH, IPT_UNKNOWN )
PORT_BIT( 0x10, IP_ACTIVE_HIGH, IPT_MAHJONG_BIG )
PORT_BIT( 0xe0, IP_ACTIVE_HIGH, IPT_UNUSED )
PORT_START("KEY5")
PORT_BIT( 0x01, IP_ACTIVE_HIGH, IPT_START1 )
PORT_BIT( 0x02, IP_ACTIVE_HIGH, IPT_MAHJONG_BET )
PORT_BIT( 0x04, IP_ACTIVE_HIGH, IPT_UNKNOWN )
PORT_BIT( 0x08, IP_ACTIVE_HIGH, IPT_UNKNOWN )
PORT_BIT( 0x10, IP_ACTIVE_HIGH, IPT_MAHJONG_SMALL )
PORT_BIT( 0xe0, IP_ACTIVE_HIGH, IPT_UNUSED )
INPUT_PORTS_END
/*************************************
*
* Machine driver
*
*************************************/
void mjsister_state::machine_start()
{
uint8_t *ROM = memregion("maincpu")->base();
m_rombank->configure_entries(0, 4, &ROM[0x10000], 0x8000);
m_vram = make_unique_clear<uint8_t[]>(0x10000);
m_vrambank->configure_entries(0, 2, m_vram.get(), 0x8000);
m_dac_timer = timer_alloc(TIMER_DAC);
save_pointer(NAME(m_vram), 0x10000);
save_item(NAME(m_dac_busy));
save_item(NAME(m_video_enable));
save_item(NAME(m_colorbank));
save_item(NAME(m_input_sel1));
save_item(NAME(m_input_sel2));
save_item(NAME(m_irq_enable));
save_item(NAME(m_dac_adr));
save_item(NAME(m_dac_bank));
save_item(NAME(m_dac_adr_s));
save_item(NAME(m_dac_adr_e));
}
void mjsister_state::machine_reset()
{
m_dac_busy = 0;
m_video_enable = 0;
m_input_sel1 = 0;
m_input_sel2 = 0;
m_dac_adr = 0;
m_dac_bank = 0;
m_dac_adr_s = 0;
m_dac_adr_e = 0;
}
INTERRUPT_GEN_MEMBER(mjsister_state::interrupt)
{
if (m_irq_enable)
m_maincpu->set_input_line(0, ASSERT_LINE);
}
void mjsister_state::mjsister(machine_config &config)
{
/* basic machine hardware */
Z80(config, m_maincpu, MCLK/2); /* 6.000 MHz */
m_maincpu->set_addrmap(AS_PROGRAM, &mjsister_state::mjsister_map);
m_maincpu->set_addrmap(AS_IO, &mjsister_state::mjsister_io_map);
m_maincpu->set_periodic_int(FUNC(mjsister_state::interrupt), attotime::from_hz(2*60));
LS259(config, m_mainlatch[0]);
m_mainlatch[0]->q_out_cb<0>().set(FUNC(mjsister_state::rombank_w));
m_mainlatch[0]->q_out_cb<1>().set(FUNC(mjsister_state::flip_screen_w));
m_mainlatch[0]->q_out_cb<2>().set(FUNC(mjsister_state::colorbank_w));
m_mainlatch[0]->q_out_cb<3>().set(FUNC(mjsister_state::colorbank_w));
m_mainlatch[0]->q_out_cb<4>().set(FUNC(mjsister_state::colorbank_w));
m_mainlatch[0]->q_out_cb<5>().set(FUNC(mjsister_state::video_enable_w));
m_mainlatch[0]->q_out_cb<6>().set(FUNC(mjsister_state::irq_enable_w));
m_mainlatch[0]->q_out_cb<7>().set(FUNC(mjsister_state::vrambank_w));
LS259(config, m_mainlatch[1]);
m_mainlatch[1]->q_out_cb<2>().set(FUNC(mjsister_state::coin_counter_w));
m_mainlatch[1]->q_out_cb<5>().set(FUNC(mjsister_state::dac_bank_w));
m_mainlatch[1]->q_out_cb<6>().set(FUNC(mjsister_state::rombank_w));
/* video hardware */
screen_device &screen(SCREEN(config, "screen", SCREEN_TYPE_RASTER));
screen.set_raw(MCLK/2, 384, 0, 256, 268, 0, 240); // 6 MHz?
screen.set_screen_update(FUNC(mjsister_state::screen_update));
PALETTE(config, m_palette, palette_device::RGB_444_PROMS, "proms", 256);
HD6845S(config, m_crtc, MCLK/4); // 3 MHz?
m_crtc->set_screen("screen");
m_crtc->set_show_border_area(false);
m_crtc->set_char_width(2);
m_crtc->set_update_row_callback(FUNC(mjsister_state::crtc_update_row));
/* sound hardware */
SPEAKER(config, "speaker").front_center();
ay8910_device &aysnd(AY8910(config, "aysnd", MCLK/8));
aysnd.port_a_read_callback().set_ioport("DSW1");
aysnd.port_b_read_callback().set_ioport("DSW2");
aysnd.add_route(ALL_OUTPUTS, "speaker", 0.15);
DAC_8BIT_R2R(config, "dac", 0).add_route(ALL_OUTPUTS, "speaker", 0.5); // unknown DAC
}
/*************************************
*
* ROM definition(s)
*
*************************************/
ROM_START( mjsister )
ROM_REGION( 0x30000, "maincpu", 0 ) /* CPU */
ROM_LOAD( "ms00.bin", 0x00000, 0x08000, CRC(9468c33b) SHA1(63aecdcaa8493d58549dfd1d217743210cf953bc) )
ROM_LOAD( "ms01t.bin", 0x10000, 0x10000, CRC(a7b6e530) SHA1(fda9bea214968a8814d2c43226b3b32316581050) ) /* banked */
ROM_LOAD( "ms02t.bin", 0x20000, 0x10000, CRC(7752b5ba) SHA1(84dcf27a62eb290ba07c85af155897ec72f320a8) ) /* banked */
ROM_REGION( 0x20000, "samples", 0 ) /* samples */
ROM_LOAD( "ms03.bin", 0x00000, 0x10000, CRC(10a68e5e) SHA1(a0e2fa34c1c4f34642f65fbf17e9da9c2554a0c6) )
ROM_LOAD( "ms04.bin", 0x10000, 0x10000, CRC(641b09c1) SHA1(15cde906175bcb5190d36cc91cbef003ef91e425) )
ROM_REGION( 0x00400, "proms", 0 ) /* color PROMs */
ROM_LOAD( "ms05.bpr", 0x0000, 0x0100, CRC(dd231a5f) SHA1(be008593ac8ba8f5a1dd5b188dc7dc4c03016805) ) // R
ROM_LOAD( "ms06.bpr", 0x0100, 0x0100, CRC(df8e8852) SHA1(842a891440aef55a560d24c96f249618b9f4b97f) ) // G
ROM_LOAD( "ms07.bpr", 0x0200, 0x0100, CRC(6cb3a735) SHA1(468ae3d40552dc2ec24f5f2988850093d73948a6) ) // B
ROM_LOAD( "ms08.bpr", 0x0300, 0x0100, CRC(da2b3b38) SHA1(4de99c17b227653bc1b904f1309f447f5a0ab516) ) // ?
ROM_END
/*************************************
*
* Game driver(s)
*
*************************************/
GAME( 1986, mjsister, 0, mjsister, mjsister, mjsister_state, empty_init, ROT0, "Toaplan", "Mahjong Sisters (Japan)", MACHINE_SUPPORTS_SAVE )
| 30.286807 | 140 | 0.696843 |
217ba72be5dff268cda027470b84457415138e80 | 5,641 | hpp | C++ | rmf_traffic/include/rmf_traffic/schedule/Patch.hpp | methylDragon/rmf_core | 4099921bea576c2fde87c3dc852cc4d8f86a5d1a | [
"Apache-2.0"
] | 109 | 2019-10-31T02:02:50.000Z | 2022-03-30T04:42:19.000Z | rmf_traffic/include/rmf_traffic/schedule/Patch.hpp | methylDragon/rmf_core | 4099921bea576c2fde87c3dc852cc4d8f86a5d1a | [
"Apache-2.0"
] | 155 | 2019-11-15T04:43:31.000Z | 2021-04-22T09:45:32.000Z | rmf_traffic/include/rmf_traffic/schedule/Patch.hpp | methylDragon/rmf_core | 4099921bea576c2fde87c3dc852cc4d8f86a5d1a | [
"Apache-2.0"
] | 51 | 2019-10-31T11:30:34.000Z | 2022-01-27T03:07:01.000Z | /*
* Copyright (C) 2020 Open Source Robotics Foundation
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
#ifndef RMF_TRAFFIC__SCHEDULE__PATCH_HPP
#define RMF_TRAFFIC__SCHEDULE__PATCH_HPP
#include <rmf_traffic/schedule/Change.hpp>
#include <rmf_traffic/detail/bidirectional_iterator.hpp>
#include <rmf_utils/optional.hpp>
namespace rmf_traffic {
namespace schedule {
//==============================================================================
/// A container of Database changes
class Patch
{
public:
template<typename E, typename I, typename F>
using base_iterator = rmf_traffic::detail::bidirectional_iterator<E, I, F>;
class Participant
{
public:
/// Constructor
///
/// \param[in] id
/// The ID of the participant that is being changed
///
/// \param[in] erasures
/// The information about which routes to erase
///
/// \param[in] delays
/// The information about what delays have occurred
///
/// \param[in] additions
/// The information about which routes to add
Participant(
ParticipantId id,
Change::Erase erasures,
std::vector<Change::Delay> delays,
Change::Add additions);
/// The ID of the participant that this set of changes will patch.
ParticipantId participant_id() const;
/// The route erasures to perform.
///
/// These erasures should be performed before any other changes.
const Change::Erase& erasures() const;
/// The sequence of delays to apply.
///
/// These delays should be applied in sequential order after the erasures
/// are performed, and before any additions are performed.
const std::vector<Change::Delay>& delays() const;
/// The set of additions to perfom.
///
/// These additions should be applied after all other changes.
const Change::Add& additions() const;
class Implementation;
private:
rmf_utils::impl_ptr<Implementation> _pimpl;
};
class IterImpl;
using const_iterator = base_iterator<const Participant, IterImpl, Patch>;
/// Constructor. Mirrors should evaluate the fields of the Patch class in the
/// order of these constructor arguments.
///
/// \param[in] removed_participants
/// Information about which participants have been unregistered since the
/// last update.
///
/// \param[in] new_participants
/// Information about which participants have been registered since the last
/// update.
///
/// \param[in] changes
/// Information about how the participants have changed since the last
/// update.
///
/// \param[in] cull
/// Information about how the database has culled old data since the last
/// update.
///
/// \param[in] latest_version
/// The lastest version of the database that this Patch represents.
Patch(
std::vector<Change::UnregisterParticipant> removed_participants,
std::vector<Change::RegisterParticipant> new_participants,
std::vector<Participant> changes,
rmf_utils::optional<Change::Cull> cull,
Version latest_version);
// TODO(MXG): Consider using a persistent reliable topic to broadcast the
// active participant information instead of making it part of the patch.
// Ideally this information would not need to change frequently, so it doesn't
// necessarily need to be in the Patch scheme. The addition and loss of
// participants is significant enough that we should guarantee it's always
// transmitted correctly.
//
// The current scheme makes an assumption that remote mirrors will always
// either sync up before unregistered participant information is culled, or
// else they will perform a complete refresh. This might be a point of
// vulnerability if a remote mirror is not being managed correctly.
/// Get a list of which participants have been unregistered. This should be
/// evaluated first in the patch.
const std::vector<Change::UnregisterParticipant>& unregistered() const;
/// Get a list of new participants that have been registered. This should be
/// evaluated after the unregistered participants.
const std::vector<Change::RegisterParticipant>& registered() const;
/// Returns an iterator to the first element of the Patch.
const_iterator begin() const;
/// Returns an iterator to the element following the last element of the
/// Patch. This iterator acts as a placeholder; attempting to dereference it
/// results in undefined behavior.
const_iterator end() const;
/// Get the number of elements in this Patch.
std::size_t size() const;
/// Get the cull information for this patch if a cull has occurred.
const Change::Cull* cull() const;
/// Get the latest version of the Database that informed this Patch.
Version latest_version() const;
class Implementation;
private:
rmf_utils::impl_ptr<Implementation> _pimpl;
};
} // namespace schedule
namespace detail {
extern template class bidirectional_iterator<
const schedule::Patch::Participant,
schedule::Patch::IterImpl,
schedule::Patch
>;
}
} // namespace rmf_traffic
#endif // RMF_TRAFFIC__SCHEDULE__PATCH_HPP
| 32.41954 | 80 | 0.70413 |
217ce3bf4403f4609173fa5aab979476f2cc2c60 | 833 | cpp | C++ | CodeForces/Complete/800-899/878A-ShortProgram.cpp | Ashwanigupta9125/code-DS-ALGO | 49f6cf7d0c682da669db23619aef3f80697b352b | [
"MIT"
] | 36 | 2019-12-27T08:23:08.000Z | 2022-01-24T20:35:47.000Z | CodeForces/Complete/800-899/878A-ShortProgram.cpp | Ashwanigupta9125/code-DS-ALGO | 49f6cf7d0c682da669db23619aef3f80697b352b | [
"MIT"
] | 10 | 2019-11-13T02:55:18.000Z | 2021-10-13T23:28:09.000Z | CodeForces/Complete/800-899/878A-ShortProgram.cpp | Ashwanigupta9125/code-DS-ALGO | 49f6cf7d0c682da669db23619aef3f80697b352b | [
"MIT"
] | 53 | 2020-08-15T11:08:40.000Z | 2021-10-09T15:51:38.000Z | #include <cstdio>
int main(){
const int N = 10;
long n; scanf("%ld\n", &n);
int action[N]; for(int p = 0; p < N; p++){action[p] = -1;}
while(n--){
char x; int u; scanf("%c %d\n", &x, &u);
for(int p = 0; p < N; p++){
bool v = u & 1;
if(x == '&' && !v){action[p] = 0;}
else if(x == '|' && v){action[p] = 1;}
else if(x == '^' && v){action[p] = 1 - action[p];}
u /= 2;
}
}
int andint(0); for(int p = N - 1; p >= 0; p--){andint *= 2; andint += 1 - (action[p] == 0);}
int orint(0); for(int p = N - 1; p >= 0; p--){orint *= 2; orint += (action[p] == 1);}
int xorint(0); for(int p = N - 1; p >= 0; p--){xorint *= 2; xorint += (action[p] == 2);}
printf("3\n& %d\n| %d\n^ %d\n", andint, orint, xorint);
return 0;
}
| 32.038462 | 96 | 0.402161 |
217f4eea802c216218e09170d96722b90697c39b | 7,191 | cpp | C++ | test/state_machine_test.cpp | kariem2k/rive-cpp | f58c3b3d48ea03947a76971bce17e7f567cf0de0 | [
"MIT"
] | 139 | 2020-08-17T20:10:24.000Z | 2022-03-28T12:22:44.000Z | test/state_machine_test.cpp | kariem2k/rive-cpp | f58c3b3d48ea03947a76971bce17e7f567cf0de0 | [
"MIT"
] | 89 | 2020-08-28T16:41:01.000Z | 2022-03-28T19:10:49.000Z | test/state_machine_test.cpp | kariem2k/rive-cpp | f58c3b3d48ea03947a76971bce17e7f567cf0de0 | [
"MIT"
] | 19 | 2020-10-19T00:54:40.000Z | 2022-02-28T05:34:17.000Z | #include <rive/core/binary_reader.hpp>
#include <rive/file.hpp>
#include <rive/animation/state_machine_bool.hpp>
#include <rive/animation/state_machine_layer.hpp>
#include <rive/animation/animation_state.hpp>
#include <rive/animation/entry_state.hpp>
#include <rive/animation/state_transition.hpp>
#include <rive/animation/state_machine_instance.hpp>
#include <rive/animation/state_machine_input_instance.hpp>
#include <rive/animation/blend_state_1d.hpp>
#include <rive/animation/blend_animation_1d.hpp>
#include <rive/animation/blend_state_direct.hpp>
#include <rive/animation/blend_state_transition.hpp>
#include "catch.hpp"
#include <cstdio>
TEST_CASE("file with state machine be read", "[file]")
{
FILE* fp = fopen("../../test/assets/rocket.riv", "r");
REQUIRE(fp != nullptr);
fseek(fp, 0, SEEK_END);
auto length = ftell(fp);
fseek(fp, 0, SEEK_SET);
uint8_t* bytes = new uint8_t[length];
REQUIRE(fread(bytes, 1, length, fp) == length);
auto reader = rive::BinaryReader(bytes, length);
rive::File* file = nullptr;
auto result = rive::File::import(reader, &file);
REQUIRE(result == rive::ImportResult::success);
REQUIRE(file != nullptr);
auto artboard = file->artboard();
REQUIRE(artboard != nullptr);
REQUIRE(artboard->animationCount() == 3);
REQUIRE(artboard->stateMachineCount() == 1);
auto stateMachine = artboard->stateMachine("Button");
REQUIRE(stateMachine != nullptr);
REQUIRE(stateMachine->layerCount() == 1);
REQUIRE(stateMachine->inputCount() == 2);
auto hover = stateMachine->input("Hover");
REQUIRE(hover != nullptr);
REQUIRE(hover->is<rive::StateMachineBool>());
auto press = stateMachine->input("Press");
REQUIRE(press != nullptr);
REQUIRE(press->is<rive::StateMachineBool>());
auto layer = stateMachine->layer(0);
REQUIRE(layer->stateCount() == 6);
REQUIRE(layer->anyState() != nullptr);
REQUIRE(layer->entryState() != nullptr);
REQUIRE(layer->exitState() != nullptr);
int foundAnimationStates = 0;
for (int i = 0; i < layer->stateCount(); i++)
{
auto state = layer->state(i);
if (state->is<rive::AnimationState>())
{
foundAnimationStates++;
REQUIRE(state->as<rive::AnimationState>()->animation() != nullptr);
}
}
REQUIRE(foundAnimationStates == 3);
REQUIRE(layer->entryState()->transitionCount() == 1);
auto stateTo = layer->entryState()->transition(0)->stateTo();
REQUIRE(stateTo != nullptr);
REQUIRE(stateTo->is<rive::AnimationState>());
REQUIRE(stateTo->as<rive::AnimationState>()->animation() != nullptr);
REQUIRE(stateTo->as<rive::AnimationState>()->animation()->name() == "idle");
auto idleState = stateTo->as<rive::AnimationState>();
REQUIRE(idleState->transitionCount() == 2);
for (int i = 0; i < idleState->transitionCount(); i++)
{
auto transition = idleState->transition(i);
if (transition->stateTo()
->as<rive::AnimationState>()
->animation()
->name() == "Roll_over")
{
// Check the condition
REQUIRE(transition->conditionCount() == 1);
}
}
rive::StateMachineInstance smi(artboard->stateMachine("Button"));
REQUIRE(smi.getBool("Hover")->name() == "Hover");
REQUIRE(smi.getBool("Press")->name() == "Press");
REQUIRE(smi.getBool("Hover") != nullptr);
REQUIRE(smi.getBool("Press") != nullptr);
REQUIRE(smi.stateChangedCount() == 0);
REQUIRE(smi.currentAnimationCount() == 0);
delete file;
delete[] bytes;
}
TEST_CASE("file with blend states loads correctly", "[file]")
{
FILE* fp = fopen("../../test/assets/blend_test.riv", "r");
REQUIRE(fp != nullptr);
fseek(fp, 0, SEEK_END);
auto length = ftell(fp);
fseek(fp, 0, SEEK_SET);
uint8_t* bytes = new uint8_t[length];
REQUIRE(fread(bytes, 1, length, fp) == length);
auto reader = rive::BinaryReader(bytes, length);
rive::File* file = nullptr;
auto result = rive::File::import(reader, &file);
REQUIRE(result == rive::ImportResult::success);
REQUIRE(file != nullptr);
auto artboard = file->artboard();
REQUIRE(artboard != nullptr);
REQUIRE(artboard->animationCount() == 4);
REQUIRE(artboard->stateMachineCount() == 2);
auto stateMachine = artboard->stateMachine("blend");
REQUIRE(stateMachine != nullptr);
REQUIRE(stateMachine->layerCount() == 1);
auto layer = stateMachine->layer(0);
REQUIRE(layer->stateCount() == 5);
REQUIRE(layer->anyState() != nullptr);
REQUIRE(layer->entryState() != nullptr);
REQUIRE(layer->exitState() != nullptr);
REQUIRE(layer->state(1)->is<rive::BlendState1D>());
REQUIRE(layer->state(2)->is<rive::BlendState1D>());
auto blendStateA = layer->state(1)->as<rive::BlendState1D>();
auto blendStateB = layer->state(2)->as<rive::BlendState1D>();
REQUIRE(blendStateA->animationCount() == 3);
REQUIRE(blendStateB->animationCount() == 3);
auto animation = blendStateA->animation(0);
REQUIRE(animation->is<rive::BlendAnimation1D>());
auto animation1D = animation->as<rive::BlendAnimation1D>();
REQUIRE(animation1D->animation() != nullptr);
REQUIRE(animation1D->animation()->name() == "horizontal");
REQUIRE(animation1D->value() == 0.0f);
animation = blendStateA->animation(1);
REQUIRE(animation->is<rive::BlendAnimation1D>());
animation1D = animation->as<rive::BlendAnimation1D>();
REQUIRE(animation1D->animation() != nullptr);
REQUIRE(animation1D->animation()->name() == "vertical");
REQUIRE(animation1D->value() == 100.0f);
animation = blendStateA->animation(2);
REQUIRE(animation->is<rive::BlendAnimation1D>());
animation1D = animation->as<rive::BlendAnimation1D>();
REQUIRE(animation1D->animation() != nullptr);
REQUIRE(animation1D->animation()->name() == "rotate");
REQUIRE(animation1D->value() == 0.0f);
REQUIRE(blendStateA->transitionCount() == 1);
REQUIRE(blendStateA->transition(0)->is<rive::BlendStateTransition>());
REQUIRE(blendStateA->transition(0)
->as<rive::BlendStateTransition>()
->exitBlendAnimation() != nullptr);
delete file;
delete[] bytes;
}
TEST_CASE("animation state with no animation doesn't crash", "[file]")
{
FILE* fp = fopen("../../test/assets/multiple_state_machines.riv", "r");
REQUIRE(fp != nullptr);
fseek(fp, 0, SEEK_END);
auto length = ftell(fp);
fseek(fp, 0, SEEK_SET);
uint8_t* bytes = new uint8_t[length];
REQUIRE(fread(bytes, 1, length, fp) == length);
auto reader = rive::BinaryReader(bytes, length);
rive::File* file = nullptr;
auto result = rive::File::import(reader, &file);
REQUIRE(result == rive::ImportResult::success);
REQUIRE(file != nullptr);
auto artboard = file->artboard();
REQUIRE(artboard != nullptr);
REQUIRE(artboard->animationCount() == 1);
REQUIRE(artboard->stateMachineCount() == 4);
auto stateMachine = artboard->stateMachine("two");
REQUIRE(stateMachine != nullptr);
REQUIRE(stateMachine->layerCount() == 1);
auto layer = stateMachine->layer(0);
REQUIRE(layer->stateCount() == 4);
REQUIRE(layer->anyState() != nullptr);
REQUIRE(layer->entryState() != nullptr);
REQUIRE(layer->exitState() != nullptr);
REQUIRE(layer->state(3)->is<rive::AnimationState>());
auto animationState = layer->state(3)->as<rive::AnimationState>();
REQUIRE(animationState->animation() == nullptr);
rive::StateMachineInstance smi(stateMachine);
smi.advance(artboard, 0.0f);
delete file;
delete[] bytes;
} | 32.686364 | 77 | 0.695175 |
217f5897f31a0f6f3f653e816a6c592dc13fd832 | 13,022 | cpp | C++ | designer/src/gaugespeed.cpp | HangYongmao/quc | ce33d0e0bd36ec5b777ca312d0c88f27169bace1 | [
"MIT"
] | 19 | 2019-09-05T07:11:16.000Z | 2021-12-17T09:30:50.000Z | designer/src/gaugespeed.cpp | zhoujuan-ht17/quc | ce33d0e0bd36ec5b777ca312d0c88f27169bace1 | [
"MIT"
] | null | null | null | designer/src/gaugespeed.cpp | zhoujuan-ht17/quc | ce33d0e0bd36ec5b777ca312d0c88f27169bace1 | [
"MIT"
] | 22 | 2019-08-13T06:50:31.000Z | 2022-03-22T12:52:22.000Z | #pragma execution_character_set("utf-8")
#include "gaugespeed.h"
#include "qpainter.h"
#include "qmath.h"
#include "qtimer.h"
#include "qlcdnumber.h"
#include "qdebug.h"
GaugeSpeed::GaugeSpeed(QWidget *parent) : QWidget(parent)
{
minValue = 0;
maxValue = 100;
value = 0;
precision = 2;
scaleMajor = 8;
scaleMinor = 1;
startAngle = 50;
endAngle = 50;
animation = false;
animationStep = 0.5;
ringWidth = 10;
ringStartPercent = 25;
ringMidPercent = 50;
ringEndPercent = 25;
ringColorStart = QColor(2, 242, 177);
ringColorMid = QColor(45, 196, 248);
ringColorEnd = QColor(254, 68, 138);
pointerColor = QColor(178, 221, 253);
textColor = QColor(50, 50, 50);
reverse = false;
currentValue = 0;
timer = new QTimer(this);
timer->setInterval(10);
connect(timer, SIGNAL(timeout()), this, SLOT(updateValue()));
//显示数码管
lcd = new QLCDNumber(5, this);
lcd->setSegmentStyle(QLCDNumber::Flat);
lcd->setFrameShape(QFrame::NoFrame);
QPalette pal = lcd->palette();
pal.setColor(QPalette::Foreground, textColor);
lcd->setPalette(pal);
setFont(QFont("Arial", 7));
}
GaugeSpeed::~GaugeSpeed()
{
if (timer->isActive()) {
timer->stop();
}
}
void GaugeSpeed::resizeEvent(QResizeEvent *)
{
int width = this->width();
int height = this->height();
int lcdWidth = width / 4;
int lcdHeight = height / 9;
lcd->setGeometry((width - lcdWidth) / 2, height - (2.2 * lcdHeight), lcdWidth, lcdHeight);
}
void GaugeSpeed::paintEvent(QPaintEvent *)
{
int width = this->width();
int height = this->height();
int side = qMin(width, height);
//绘制准备工作,启用反锯齿,平移坐标轴中心,等比例缩放
QPainter painter(this);
painter.setRenderHints(QPainter::Antialiasing | QPainter::TextAntialiasing);
painter.translate(width / 2, height / 2);
painter.scale(side / 200.0, side / 200.0);
//绘制圆环
drawRing(&painter);
//绘制刻度线
drawScale(&painter);
//绘制刻度值
drawScaleNum(&painter);
//根据指示器形状绘制指示器
drawPointer(&painter);
//绘制当前值
drawText(&painter);
}
void GaugeSpeed::drawRing(QPainter *painter)
{
int radius = 100;
painter->save();
QPen pen = painter->pen();
pen.setCapStyle(Qt::FlatCap);
pen.setWidthF(ringWidth);
radius = radius - ringWidth;
QRectF rect = QRectF(-radius, -radius, radius * 2, radius * 2);
//计算总范围角度,根据占比例自动计算三色圆环范围角度
double angleAll = 360.0 - startAngle - endAngle;
double angleStart = angleAll * (double)ringStartPercent / 100;
double angleMid = angleAll * (double)ringMidPercent / 100;
double angleEnd = angleAll * (double)ringEndPercent / 100;
//绘制第一圆环
pen.setColor(ringColorStart);
painter->setPen(pen);
painter->drawArc(rect, (270 - startAngle - angleStart) * 16, angleStart * 16);
//绘制第二圆环
pen.setColor(ringColorMid);
painter->setPen(pen);
painter->drawArc(rect, (270 - startAngle - angleStart - angleMid) * 16, angleMid * 16);
//绘制第三圆环
pen.setColor(ringColorEnd);
painter->setPen(pen);
painter->drawArc(rect, (270 - startAngle - angleStart - angleMid - angleEnd) * 16, angleEnd * 16);
painter->restore();
}
void GaugeSpeed::drawScale(QPainter *painter)
{
int radius = 94;
painter->save();
QPen pen = painter->pen();
pen.setColor(textColor);
pen.setCapStyle(Qt::RoundCap);
painter->rotate(startAngle);
int steps = (scaleMajor * scaleMinor);
double angleStep = (360.0 - startAngle - endAngle) / steps;
//计算圆环对应大刻度范围索引
int indexStart = steps * (double)ringStartPercent / 100 + 1;
int indexMid = steps * (double)ringMidPercent / 100 - 1;
int indexEnd = steps * (double)ringEndPercent / 100 + 1;
int index = 0;
for (int i = 0; i <= steps; i++) {
if (i % scaleMinor == 0) {
//根据所在圆环范围切换颜色
if (index < indexStart) {
pen.setColor(ringColorStart);
} else if (index < (indexStart + indexMid)) {
pen.setColor(ringColorMid);
} else if (index < (indexStart + indexMid + indexEnd)) {
pen.setColor(ringColorEnd);
}
index++;
pen.setWidthF(1.5);
painter->setPen(pen);
painter->drawLine(0, radius - 13, 0, radius);
} else {
pen.setWidthF(0.5);
painter->setPen(pen);
painter->drawLine(0, radius - 5, 0, radius);
}
painter->rotate(angleStep);
}
painter->restore();
}
void GaugeSpeed::drawScaleNum(QPainter *painter)
{
int radius = 70;
painter->save();
painter->setPen(textColor);
double startRad = (360 - startAngle - 90) * (M_PI / 180);
double deltaRad = (360 - startAngle - endAngle) * (M_PI / 180) / scaleMajor;
for (int i = 0; i <= scaleMajor; i++) {
double sina = sin(startRad - i * deltaRad);
double cosa = cos(startRad - i * deltaRad);
double value = 1.0 * i * ((maxValue - minValue) / scaleMajor) + minValue;
QString strValue = QString("%1M").arg((double)value, 0, 'f', 0);
double textWidth = fontMetrics().width(strValue);
double textHeight = fontMetrics().height();
int x = radius * cosa - textWidth / 2;
int y = -radius * sina + textHeight / 4;
painter->drawText(x, y, strValue);
}
painter->restore();
}
void GaugeSpeed::drawPointer(QPainter *painter)
{
int radius = 62;
painter->save();
painter->setPen(Qt::NoPen);
painter->setBrush(pointerColor);
QPolygon pts;
pts.setPoints(4, -5, 0, 0, -8, 5, 0, 0, radius);
painter->rotate(startAngle);
double degRotate = (360.0 - startAngle - endAngle) / (maxValue - minValue) * (currentValue - minValue);
painter->rotate(degRotate);
painter->drawConvexPolygon(pts);
painter->restore();
}
void GaugeSpeed::drawText(QPainter *painter)
{
int radius = 100;
painter->save();
painter->setPen(textColor);
QRectF unitRect(-radius, radius / 3, radius * 2, radius / 4);
QString strUnit = QString("%1").arg("Mbps");
painter->setFont(QFont("Arial", 5));
painter->drawText(unitRect, Qt::AlignCenter, strUnit);
QRectF textRect(-radius, radius / 2.3, radius * 2, radius / 3);
QString strValue = QString("%1").arg((double)currentValue, 0, 'f', precision);
strValue = QString("%1").arg(strValue, 5, QLatin1Char('0'));
painter->setFont(QFont("Arial", 15));
#if 0
lcd->setVisible(false);
painter->drawText(textRect, Qt::AlignCenter, strValue);
#else
lcd->display(strValue);
#endif
painter->restore();
}
void GaugeSpeed::updateValue()
{
if (!reverse) {
if (currentValue >= value) {
timer->stop();
} else {
currentValue += animationStep;
}
} else {
if (currentValue <= value) {
timer->stop();
} else {
currentValue -= animationStep;
}
}
update();
}
double GaugeSpeed::getMinValue() const
{
return this->minValue;
}
double GaugeSpeed::getMaxValue() const
{
return this->maxValue;
}
double GaugeSpeed::getValue() const
{
return this->value;
}
int GaugeSpeed::getPrecision() const
{
return this->precision;
}
int GaugeSpeed::getScaleMajor() const
{
return this->scaleMajor;
}
int GaugeSpeed::getScaleMinor() const
{
return this->scaleMinor;
}
int GaugeSpeed::getStartAngle() const
{
return this->startAngle;
}
int GaugeSpeed::getEndAngle() const
{
return this->endAngle;
}
bool GaugeSpeed::getAnimation() const
{
return this->animation;
}
double GaugeSpeed::getAnimationStep() const
{
return this->animationStep;
}
int GaugeSpeed::getRingWidth() const
{
return this->ringWidth;
}
int GaugeSpeed::getRingStartPercent() const
{
return this->ringStartPercent;
}
int GaugeSpeed::getRingMidPercent() const
{
return this->ringMidPercent;
}
int GaugeSpeed::getRingEndPercent() const
{
return this->ringEndPercent;
}
QColor GaugeSpeed::getRingColorStart() const
{
return this->ringColorStart;
}
QColor GaugeSpeed::getRingColorMid() const
{
return this->ringColorMid;
}
QColor GaugeSpeed::getRingColorEnd() const
{
return this->ringColorEnd;
}
QColor GaugeSpeed::getPointerColor() const
{
return this->pointerColor;
}
QColor GaugeSpeed::getTextColor() const
{
return this->textColor;
}
QSize GaugeSpeed::sizeHint() const
{
return QSize(200, 200);
}
QSize GaugeSpeed::minimumSizeHint() const
{
return QSize(50, 50);
}
void GaugeSpeed::setRange(double minValue, double maxValue)
{
//如果最小值大于或者等于最大值则不设置
if (minValue >= maxValue) {
return;
}
this->minValue = minValue;
this->maxValue = maxValue;
//如果目标值不在范围值内,则重新设置目标值
if (value < minValue || value > maxValue) {
setValue(value);
}
update();
}
void GaugeSpeed::setRange(int minValue, int maxValue)
{
setRange((double)minValue, (double)maxValue);
}
void GaugeSpeed::setMinValue(double minValue)
{
setRange(minValue, maxValue);
}
void GaugeSpeed::setMaxValue(double maxValue)
{
setRange(minValue, maxValue);
}
void GaugeSpeed::setValue(double value)
{
//值小于最小值或者值大于最大值或者值和当前值一致则无需处理
if (value < minValue || value > maxValue || value == this->value) {
return;
}
if (value > this->value) {
reverse = false;
} else if (value < this->value) {
reverse = true;
}
this->value = value;
emit valueChanged(value);
if (!animation) {
currentValue = this->value;
update();
} else {
timer->start();
}
}
void GaugeSpeed::setValue(int value)
{
setValue((double)value);
}
void GaugeSpeed::setPrecision(int precision)
{
//最大精确度为 3
if (precision <= 3 && this->precision != precision) {
this->precision = precision;
update();
}
}
void GaugeSpeed::setScaleMajor(int scaleMajor)
{
if (this->scaleMajor != scaleMajor) {
this->scaleMajor = scaleMajor;
update();
}
}
void GaugeSpeed::setScaleMinor(int scaleMinor)
{
if (this->scaleMinor != scaleMinor) {
this->scaleMinor = scaleMinor;
update();
}
}
void GaugeSpeed::setStartAngle(int startAngle)
{
if (this->startAngle != startAngle) {
this->startAngle = startAngle;
update();
}
}
void GaugeSpeed::setEndAngle(int endAngle)
{
if (this->endAngle != endAngle) {
this->endAngle = endAngle;
update();
}
}
void GaugeSpeed::setAnimation(bool animation)
{
if (this->animation != animation) {
this->animation = animation;
update();
}
}
void GaugeSpeed::setAnimationStep(double animationStep)
{
if (this->animationStep != animationStep) {
this->animationStep = animationStep;
update();
}
}
void GaugeSpeed::setRingWidth(int ringWidth)
{
if (this->ringWidth != ringWidth) {
this->ringWidth = ringWidth;
update();
}
}
void GaugeSpeed::setRingStartPercent(int ringStartPercent)
{
//所占比例不能小于1 或者总比例不能大于100
if (ringStartPercent < 1 || (ringStartPercent + ringMidPercent + ringEndPercent) > 100) {
return;
}
if (this->ringStartPercent != ringStartPercent) {
this->ringStartPercent = ringStartPercent;
update();
}
}
void GaugeSpeed::setRingMidPercent(int ringMidPercent)
{
//所占比例不能小于1 或者总比例不能大于100
if (ringStartPercent < 1 || (ringStartPercent + ringMidPercent + ringEndPercent) > 100) {
return;
}
if (this->ringMidPercent != ringMidPercent) {
this->ringMidPercent = ringMidPercent;
update();
}
}
void GaugeSpeed::setRingEndPercent(int ringEndPercent)
{
//所占比例不能小于1 或者总比例不能大于100
if (ringStartPercent < 1 || (ringStartPercent + ringMidPercent + ringEndPercent) > 100) {
return;
}
if (this->ringEndPercent != ringEndPercent) {
this->ringEndPercent = ringEndPercent;
update();
}
}
void GaugeSpeed::setRingColorStart(const QColor &ringColorStart)
{
if (this->ringColorStart != ringColorStart) {
this->ringColorStart = ringColorStart;
update();
}
}
void GaugeSpeed::setRingColorMid(const QColor &ringColorMid)
{
if (this->ringColorMid != ringColorMid) {
this->ringColorMid = ringColorMid;
update();
}
}
void GaugeSpeed::setRingColorEnd(const QColor &ringColorEnd)
{
if (this->ringColorEnd != ringColorEnd) {
this->ringColorEnd = ringColorEnd;
update();
}
}
void GaugeSpeed::setPointerColor(const QColor &pointerColor)
{
if (this->pointerColor != pointerColor) {
this->pointerColor = pointerColor;
update();
}
}
void GaugeSpeed::setTextColor(const QColor &textColor)
{
if (this->textColor != textColor) {
QPalette pal = lcd->palette();
pal.setColor(QPalette::Foreground, textColor);
lcd->setPalette(pal);
this->textColor = textColor;
update();
}
}
| 22.37457 | 107 | 0.624712 |
2186f8dcb78f27fa11418cdb0781536905738bba | 1,408 | cpp | C++ | tcp_async_server.cpp | opensvn/boost_learning | 7f21551a7f3db38bea2c31d95d0c8b4e00f4537e | [
"BSL-1.0"
] | null | null | null | tcp_async_server.cpp | opensvn/boost_learning | 7f21551a7f3db38bea2c31d95d0c8b4e00f4537e | [
"BSL-1.0"
] | null | null | null | tcp_async_server.cpp | opensvn/boost_learning | 7f21551a7f3db38bea2c31d95d0c8b4e00f4537e | [
"BSL-1.0"
] | 1 | 2021-10-01T04:27:44.000Z | 2021-10-01T04:27:44.000Z | #include <iostream>
#include <boost/asio.hpp>
#include <boost/bind.hpp>
#include <boost/shared_ptr.hpp>
using namespace std;
using namespace boost::asio;
class server
{
private:
io_service &ios;
ip::tcp::acceptor acceptor;
typedef boost::shared_ptr<ip::tcp::socket> sock_pt;
public:
server(io_service& io):
ios(io), acceptor(ios, ip::tcp::endpoint(ip::tcp::v4(), 6688))
{
start();
}
void start()
{
sock_pt sock(new ip::tcp::socket(ios));
acceptor.async_accept(*sock,
boost::bind(&server::accept_handler, this,
placeholders::error, sock));
}
void accept_handler(const boost::system::error_code &ec, sock_pt sock)
{
if (ec)
return;
cout << "client:";
cout << sock->remote_endpoint().address() << endl;
sock->async_write_some(buffer("hello asio"),
boost::bind(&server::write_handler, this, placeholders::error));
start();
}
void write_handler(const boost::system::error_code&)
{
cout << "send msg complete." << endl;
}
};
int main()
{
try
{
cout << "server start." << endl;
io_service ios;
server s(ios);
ios.run();
}
catch (exception &e)
{
cout << e.what() << endl;
}
return 0;
}
| 22.349206 | 95 | 0.534801 |
218d6bab407dc672e26ebb0c57f15c812c5e9714 | 3,332 | cpp | C++ | test/dmtimerevent/main.cpp | brinkqiang/dmtimer | 3a8c18a3366ccc31e79d1e79df512769cb8b0633 | [
"MIT"
] | 18 | 2018-03-05T14:42:46.000Z | 2021-07-28T06:25:29.000Z | test/dmtimerevent/main.cpp | brinkqiang/dmtimer | 3a8c18a3366ccc31e79d1e79df512769cb8b0633 | [
"MIT"
] | null | null | null | test/dmtimerevent/main.cpp | brinkqiang/dmtimer | 3a8c18a3366ccc31e79d1e79df512769cb8b0633 | [
"MIT"
] | 5 | 2018-03-20T12:01:07.000Z | 2020-01-25T12:01:13.000Z |
#include "dmutil.h"
#include "dmtimermodule.h"
#include "dmsingleton.h"
#include "dmthread.h"
#include "dmconsole.h"
#include "dmtypes.h"
#include "dmtimereventnode.h"
class CPlayer : public CDMTimerNode
{
public:
virtual void OnTimer(uint64_t qwIDEvent);
};
class CMain : public IDMConsoleSink,
public IDMThread,
public CDMThreadCtrl,
public CDMTimerNode,
public TSingleton<CMain>,
public CDMTimerEventNode
{
friend class TSingleton<CMain>;
enum
{
eMAX_PLAYER = 100 * 1,
eMAX_PLAYER_EVENT = 10,
};
typedef enum
{
eTimerID_UUID = 0,
eTimerID_STOP,
} ETimerID;
typedef enum
{
eTimerTime_UUID = 1000,
eTimerTime_STOP = 20000,
} ETimerTime;
public:
virtual void ThrdProc()
{
std::cout << "test start" << std::endl;
SetTimer(eTimerID_UUID, eTimerTime_UUID, dm::any(std::string("hello world")));
SleepMs(300);
CDMTimerModule::Instance()->Run();
SetTimer(eTimerID_STOP, eTimerTime_STOP, eTimerTime_STOP);
AddEvent(ETimerEventType_EVERYDAY);
bool bBusy = false;
while (!m_bStop)
{
bBusy = false;
if (CDMTimerModule::Instance()->Run())
{
bBusy = true;
}
if (__Run())
{
bBusy = true;
}
if (!bBusy)
{
SleepMs(1);
}
}
std::cout << "test stop" << std::endl;
}
virtual void Terminate()
{
m_bStop = true;
}
virtual void OnCloseEvent()
{
Stop();
}
virtual void OnTimer(uint64_t qwIDEvent, dm::any& oAny)
{
switch (qwIDEvent)
{
case eTimerID_UUID:
{
std::cout << DMFormatDateTime() << " " << CMain::Instance()->GetOnTimerCount()
<< " " << dm::any_cast<std::string>(oAny) << std::endl;
}
break;
case eTimerID_STOP:
{
std::cout << DMFormatDateTime() << " test stopping..." << std::endl;
Stop();
}
break;
default:
break;
}
}
virtual void OnEvent(ETimerEventType eEvent)
{
switch (eEvent)
{
case ETimerEventType_EVERYDAY:
{
}
break;
default:
break;
}
}
void AddOnTimerCount()
{
++m_qwOnTimerCount;
}
uint64_t GetOnTimerCount()
{
return m_qwOnTimerCount;
}
private:
CMain()
: m_bStop(false), m_qwOnTimerCount(0)
{
HDMConsoleMgr::Instance()->SetHandlerHook(this);
}
virtual ~CMain()
{
}
private:
bool __Run()
{
return false;
}
private:
volatile bool m_bStop;
CPlayer m_oPlayers[eMAX_PLAYER];
uint64_t m_qwOnTimerCount;
};
void CPlayer::OnTimer(uint64_t qwIDEvent)
{
CMain::Instance()->AddOnTimerCount();
}
int main(int argc, char* argv[])
{
CMain::Instance()->Start(CMain::Instance());
CMain::Instance()->WaitFor();
return 0;
}
| 19.260116 | 91 | 0.498199 |
2193656d0b9f2642e5b595c56ccea59f64666e1c | 3,122 | cpp | C++ | PixelSortSDL2/application.cpp | ohookins/cpp_experiments | 3b7bba2a625ef72e20cc3b90191a7683bb85740f | [
"MIT"
] | 1 | 2018-03-31T06:41:37.000Z | 2018-03-31T06:41:37.000Z | PixelSortSDL2/application.cpp | ohookins/cpp_experiments | 3b7bba2a625ef72e20cc3b90191a7683bb85740f | [
"MIT"
] | null | null | null | PixelSortSDL2/application.cpp | ohookins/cpp_experiments | 3b7bba2a625ef72e20cc3b90191a7683bb85740f | [
"MIT"
] | null | null | null | #include "application.h"
#include "mypixel.h"
#include <iostream>
Application::Application() {
// Define size of pixel array
pixels = new MyPixel*[dimension];
for (int p = 0; p < dimension; p++) {
pixels[p] = new MyPixel[dimension];
}
}
Application::~Application() {
for (int p = 0; p < dimension; p++) {
delete pixels[p];
}
delete pixels;
}
void Application::DrawRandomColorAt(int x, int y) {
MyPixel pixel;
SDL_SetRenderDrawColor(renderer, pixel.r, pixel.g, pixel.b, pixel.a);
SDL_RenderDrawPoint(renderer, x, y);
pixels[y][x] = pixel;
Refresh();
}
void Application::Run() {
SDL_Init(SDL_INIT_VIDEO);
if (SDL_WasInit(SDL_INIT_VIDEO) != 0) {
std::cout << "SDL2 Video was initialised" << std::endl;
}
window = SDL_CreateWindow("PixelSort", SDL_WINDOWPOS_UNDEFINED, SDL_WINDOWPOS_UNDEFINED, dimension, dimension, SDL_WINDOW_OPENGL);
if (window == NULL) {
std::cout << "Could not create window: " << SDL_GetError() << std::endl;
return;
}
renderer = SDL_CreateRenderer(window, SDL_RENDERER_ACCELERATED, -1);
// Initialize the array and display with random colours
for (int y = 0; y < dimension; y++) {
for (int x = 0; x < dimension; x++) {
DrawRandomColorAt(x, y);
}
}
// Perform the sort, which draws the results as it progresses.
Quicksort(0, dimension*dimension-1);
// Leave the result on the screen for 10 seconds, then cleanup and quit.
SDL_Delay(10000);
SDL_DestroyRenderer(renderer);
SDL_DestroyWindow(window);
SDL_Quit();
}
void Application::Quicksort (int lo, int hi) {
if (lo < hi) {
int p = Partition(lo, hi);
Quicksort(lo, p - 1);
Quicksort(p + 1, hi);
}
}
int Application::Partition (int lo, int hi) {
//std::cout << "partitioning from " << lo << " to " << hi << std::endl;
//std::cout << "pivot is at x:" << hi%dimension << " y:" << hi/dimension << std::endl;
MyPixel pivot = pixels[hi/dimension][hi%dimension];
int i = lo - 1;
for (int j = lo; j < hi; j++) {
if (pixels[j/dimension][j%dimension].Hue() < pivot.Hue()) {
i++;
SwapAndDrawPixels(i, j);
}
}
SwapAndDrawPixels(hi, i+1);
return i + 1;
}
void Application::SwapAndDrawPixels(int a, int b) {
int ax = a%dimension;
int ay = a/dimension;
int bx = b%dimension;
int by = b/dimension;
// Swap pixels. Coordinate swapping needs fixing badly.
MyPixel temp = pixels[ay][ax];
pixels[ay][ax] = pixels[by][bx];
pixels[by][bx] = temp;
// Draw first pixel
SDL_SetRenderDrawColor(renderer, pixels[ay][ax].r, pixels[ay][ax].g, pixels[ay][ax].b, pixels[ay][ax].a);
SDL_RenderDrawPoint(renderer, ax, ay);
// Draw second pixel
SDL_SetRenderDrawColor(renderer, pixels[by][bx].r, pixels[by][bx].g, pixels[by][bx].b, pixels[by][bx].a);
SDL_RenderDrawPoint(renderer, bx, by);
Refresh();
}
void Application::Refresh() {
if (frameCount++ % speedUp == 0) {
SDL_RenderPresent(renderer);
}
} | 27.147826 | 134 | 0.60442 |
2195e9f70920cf15b460a1e62e81d31f933d994b | 379 | cpp | C++ | taichi/program/aot_module_builder.cpp | squarefk/test_actions | dd3b0305c49b577102786eb1c24c590ef160bc30 | [
"MIT"
] | 1 | 2022-01-29T11:59:50.000Z | 2022-01-29T11:59:50.000Z | taichi/program/aot_module_builder.cpp | squarefk/test_actions | dd3b0305c49b577102786eb1c24c590ef160bc30 | [
"MIT"
] | null | null | null | taichi/program/aot_module_builder.cpp | squarefk/test_actions | dd3b0305c49b577102786eb1c24c590ef160bc30 | [
"MIT"
] | 1 | 2021-08-09T15:47:24.000Z | 2021-08-09T15:47:24.000Z | #include "taichi/program/aot_module_builder.h"
#include "taichi/program/kernel.h"
namespace taichi {
namespace lang {
void AotModuleBuilder::add(const std::string &identifier, Kernel *kernel) {
if (!kernel->lowered() && Kernel::supports_lowering(kernel->arch)) {
kernel->lower();
}
add_per_backend(identifier, kernel);
}
} // namespace lang
} // namespace taichi
| 22.294118 | 75 | 0.71504 |
219c956c8719ced56b9a4b6d165247f51722f3f6 | 5,874 | hpp | C++ | include/El/core/imports/scalapack/pblas.hpp | justusc/Elemental | 145ccb28411f3f0c65ca30ecea776df33297e4ff | [
"BSD-3-Clause"
] | null | null | null | include/El/core/imports/scalapack/pblas.hpp | justusc/Elemental | 145ccb28411f3f0c65ca30ecea776df33297e4ff | [
"BSD-3-Clause"
] | null | null | null | include/El/core/imports/scalapack/pblas.hpp | justusc/Elemental | 145ccb28411f3f0c65ca30ecea776df33297e4ff | [
"BSD-3-Clause"
] | null | null | null | /*
Copyright (c) 2009-2015, Jack Poulson
All rights reserved.
This file is part of Elemental and is under the BSD 2-Clause License,
which can be found in the LICENSE file in the root directory, or at
http://opensource.org/licenses/BSD-2-Clause
*/
#pragma once
#ifndef EL_IMPORTS_SCALAPACK_PBLAS_HPP
#define EL_IMPORTS_SCALAPACK_PBLAS_HPP
#ifdef EL_HAVE_SCALAPACK
namespace El {
namespace pblas {
// Level 2
// =======
// Gemv
// ----
void Gemv
( char trans, int m, int n,
float alpha, const float* A, const int* descA,
const float* x, const int* descx, int incx,
float beta, float* y, const int* descy, int incy );
void Gemv
( char trans, int m, int n,
double alpha, const double* A, const int* descA,
const double* x, const int* descx, int incx,
double beta, double* y, const int* descy, int incy );
void Gemv
( char trans, int m, int n,
scomplex alpha, const scomplex* A, const int* descA,
const scomplex* x, const int* descx, int incx,
scomplex beta, scomplex* y, const int* descy, int incy );
void Gemv
( char trans, int m, int n,
dcomplex alpha, const dcomplex* A, const int* descA,
const dcomplex* x, const int* descx, int incx,
dcomplex beta, dcomplex* y, const int* descy, int incy );
// Hemv
// ----
void Hemv
( char uplo, int n,
scomplex alpha, const scomplex* A, const int* descA,
const scomplex* x, const int* descx, int incx,
scomplex beta, scomplex* y, const int* descy, int incy );
void Hemv
( char uplo, int n,
dcomplex alpha, const dcomplex* A, const int* descA,
const dcomplex* x, const int* descx, int incx,
dcomplex beta, dcomplex* y, const int* descy, int incy );
// Symv
// ----
void Symv
( char uplo, int n,
float alpha, const float* A, const int* descA,
const float* x, const int* descx, int incx,
float beta, float* y, const int* descy, int incy );
void Symv
( char uplo, int n,
double alpha, const double* A, const int* descA,
const double* x, const int* descx, int incx,
double beta, double* y, const int* descy, int incy );
// Trmv
// ----
void Trmv
( char uplo, char trans, char diag, int n,
const float* A, const int* descA,
float* x, const int* descx, int incx );
void Trmv
( char uplo, char trans, char diag, int n,
const double* A, const int* descA,
double* x, const int* descx, int incx );
void Trmv
( char uplo, char trans, char diag, int n,
const scomplex* A, const int* descA,
scomplex* x, const int* descx, int incx );
void Trmv
( char uplo, char trans, char diag, int n,
const dcomplex* A, const int* descA,
dcomplex* x, const int* descx, int incx );
// Trsv
// ----
void Trsv
( char uplo, char trans, char diag, int n,
const float* A, const int* descA,
float* x, const int* descx, int incx );
void Trsv
( char uplo, char trans, char diag, int n,
const double* A, const int* descA,
double* x, const int* descx, int incx );
void Trsv
( char uplo, char trans, char diag, int n,
const scomplex* A, const int* descA,
scomplex* x, const int* descx, int incx );
void Trsv
( char uplo, char trans, char diag, int n,
const dcomplex* A, const int* descA,
dcomplex* x, const int* descx, int incx );
// Level 3
// =======
// Gemm
// ----
void Gemm
( char transa, char transb, int m, int n, int k,
float alpha, const float* A, const int* descA,
const float* B, const int* descB,
float beta, float* C, const int* descC );
void Gemm
( char transa, char transb, int m, int n, int k,
double alpha, const double* A, const int* descA,
const double* B, const int* descB,
double beta, double* C, const int* descC );
void Gemm
( char transa, char transb, int m, int n, int k,
scomplex alpha, const scomplex* A, const int* descA,
const scomplex* B, const int* descB,
scomplex beta, scomplex* C, const int* descC );
void Gemm
( char transa, char transb, int m, int n, int k,
dcomplex alpha, const dcomplex* A, const int* descA,
const dcomplex* B, const int* descB,
dcomplex beta, dcomplex* C, const int* descC );
// Trmm
// ----
void Trmm
( char side, char uplo, char trans, char diag, int m, int n,
float alpha, const float* A, const int* descA,
float* B, const int* descB );
void Trmm
( char side, char uplo, char trans, char diag, int m, int n,
double alpha, const double* A, const int* descA,
double* B, const int* descB );
void Trmm
( char side, char uplo, char trans, char diag, int m, int n,
scomplex alpha, const scomplex* A, const int* descA,
scomplex* B, const int* descB );
void Trmm
( char side, char uplo, char trans, char diag, int m, int n,
dcomplex alpha, const dcomplex* A, const int* descA,
dcomplex* B, const int* descB );
// Trsm
// ----
void Trsm
( char side, char uplo, char trans, char diag, int m, int n,
float alpha, const float* A, const int* descA,
float* B, const int* descB );
void Trsm
( char side, char uplo, char trans, char diag, int m, int n,
double alpha, const double* A, const int* descA,
double* B, const int* descB );
void Trsm
( char side, char uplo, char trans, char diag, int m, int n,
scomplex alpha, const scomplex* A, const int* descA,
scomplex* B, const int* descB );
void Trsm
( char side, char uplo, char trans, char diag, int m, int n,
dcomplex alpha, const dcomplex* A, const int* descA,
dcomplex* B, const int* descB );
} // namespace pblas
} // namespace El
#endif // ifdef EL_HAVE_SCALAPACK
#endif // ifndef EL_IMPORTS_SCALAPACK_PBLAS_HPP
| 33 | 73 | 0.617297 |
219ce3d770cb1c2fc6349c0242f5d60a31f39091 | 129,544 | cc | C++ | SimFastTiming/FastTimingCommon/src/BTLPulseShape.cc | nistefan/cmssw | ea13af97f7f2117a4f590a5e654e06ecd9825a5b | [
"Apache-2.0"
] | null | null | null | SimFastTiming/FastTimingCommon/src/BTLPulseShape.cc | nistefan/cmssw | ea13af97f7f2117a4f590a5e654e06ecd9825a5b | [
"Apache-2.0"
] | null | null | null | SimFastTiming/FastTimingCommon/src/BTLPulseShape.cc | nistefan/cmssw | ea13af97f7f2117a4f590a5e654e06ecd9825a5b | [
"Apache-2.0"
] | null | null | null | #include "SimFastTiming/FastTimingCommon/interface/BTLPulseShape.h"
BTLPulseShape::~BTLPulseShape() { }
BTLPulseShape::BTLPulseShape() :
MTDShapeBase()
{
buildMe() ;
}
void BTLPulseShape::fillShape( MTDShapeBase::DVec& aVec ) const
{
// --- Pulse shape for a signal of 100 p.e.
aVec = { 1.0989088528e-08, // time = 0.00 ns
1.0991907162e-08, // time = 0.01 ns
1.0997329492e-08, // time = 0.02 ns
1.1003584377e-08, // time = 0.03 ns
1.1009992029e-08, // time = 0.04 ns
1.1012972201e-08, // time = 0.05 ns
1.1021256463e-08, // time = 0.06 ns
1.1026509483e-08, // time = 0.07 ns
1.1031466074e-08, // time = 0.08 ns
1.1036719205e-08, // time = 0.09 ns
1.1041674131e-08, // time = 0.10 ns
1.1047045612e-08, // time = 0.11 ns
1.1051815463e-08, // time = 0.12 ns
1.1054848370e-08, // time = 0.13 ns
1.1061600969e-08, // time = 0.14 ns
1.1068583716e-08, // time = 0.15 ns
1.1072180173e-08, // time = 0.16 ns
1.1079616224e-08, // time = 0.17 ns
1.1085058982e-08, // time = 0.18 ns
1.1088839624e-08, // time = 0.19 ns
1.1093972185e-08, // time = 0.20 ns
1.1097449848e-08, // time = 0.21 ns
1.1101024100e-08, // time = 0.22 ns
1.1101378705e-08, // time = 0.23 ns
1.1097040176e-08, // time = 0.24 ns
1.1084638429e-08, // time = 0.25 ns
1.1066582650e-08, // time = 0.26 ns
1.1029894220e-08, // time = 0.27 ns
1.0982672327e-08, // time = 0.28 ns
1.0898173142e-08, // time = 0.29 ns
1.0793557714e-08, // time = 0.30 ns
1.0620891611e-08, // time = 0.31 ns
1.0409881734e-08, // time = 0.32 ns
1.0082901958e-08, // time = 0.33 ns
9.0983337531e-09, // time = 0.34 ns
8.3805116180e-09, // time = 0.35 ns
7.3771350140e-09, // time = 0.36 ns
6.1367581017e-09, // time = 0.37 ns
4.4798341703e-09, // time = 0.38 ns
2.4086144190e-09, // time = 0.39 ns
-2.4227331252e-10, // time = 0.40 ns
-3.5583425095e-09, // time = 0.41 ns
-7.6733522869e-09, // time = 0.42 ns
-1.2741777300e-08, // time = 0.43 ns
-1.8940880864e-08, // time = 0.44 ns
-2.6472953385e-08, // time = 0.45 ns
-3.5567657153e-08, // time = 0.46 ns
-4.6484470717e-08, // time = 0.47 ns
-5.9515207540e-08, // time = 0.48 ns
-7.4986613807e-08, // time = 0.49 ns
-9.3263022860e-08, // time = 0.50 ns
-1.1474906514e-07, // time = 0.51 ns
-1.3989241809e-07, // time = 0.52 ns
-1.6918658396e-07, // time = 0.53 ns
-2.0317369820e-07, // time = 0.54 ns
-2.4244733021e-07, // time = 0.55 ns
-2.8765528814e-07, // time = 0.56 ns
-3.3950240930e-07, // time = 0.57 ns
-3.9875332170e-07, // time = 0.58 ns
-4.6623516570e-07, // time = 0.59 ns
-5.4284025963e-07, // time = 0.60 ns
-6.2952871471e-07, // time = 0.61 ns
-7.2733098444e-07, // time = 0.62 ns
-8.3735028311e-07, // time = 0.63 ns
-9.6076490319e-07, // time = 0.64 ns
-1.0988305380e-06, // time = 0.65 ns
-1.2528823705e-06, // time = 0.66 ns
-1.4243370704e-06, // time = 0.67 ns
-1.6146946558e-06, // time = 0.68 ns
-1.8255402069e-06, // time = 0.69 ns
-2.0585454268e-06, // time = 0.70 ns
-2.3154700360e-06, // time = 0.71 ns
-2.5981629969e-06, // time = 0.72 ns
-2.9085635581e-06, // time = 0.73 ns
-3.2487021228e-06, // time = 0.74 ns
-3.6207009125e-06, // time = 0.75 ns
-4.0267744512e-06, // time = 0.76 ns
-4.4692298292e-06, // time = 0.77 ns
-4.9504667756e-06, // time = 0.78 ns
-5.4729775211e-06, // time = 0.79 ns
-6.0393464427e-06, // time = 0.80 ns
-6.6522494926e-06, // time = 0.81 ns
-7.3144534150e-06, // time = 0.82 ns
-8.0288147384e-06, // time = 0.83 ns
-8.7982785562e-06, // time = 0.84 ns
-9.6258770734e-06, // time = 0.85 ns
-1.0514727944e-05, // time = 0.86 ns
-1.1468032388e-05, // time = 0.87 ns
-1.2489073082e-05, // time = 0.88 ns
-1.3581211839e-05, // time = 0.89 ns
-1.4747887069e-05, // time = 0.90 ns
-1.5992611032e-05, // time = 0.91 ns
-1.7318966874e-05, // time = 0.92 ns
-1.8730605462e-05, // time = 0.93 ns
-2.0231242013e-05, // time = 0.94 ns
-2.1824652529e-05, // time = 0.95 ns
-2.3514670035e-05, // time = 0.96 ns
-2.5305180625e-05, // time = 0.97 ns
-2.7200119336e-05, // time = 0.98 ns
-2.9203465828e-05, // time = 0.99 ns
-3.1319239909e-05, // time = 1.00 ns
-3.3551496885e-05, // time = 1.01 ns
-3.5904322755e-05, // time = 1.02 ns
-3.8381829254e-05, // time = 1.03 ns
-4.0988148755e-05, // time = 1.04 ns
-4.3727429032e-05, // time = 1.05 ns
-4.6603827889e-05, // time = 1.06 ns
-4.9621507686e-05, // time = 1.07 ns
-5.2784629731e-05, // time = 1.08 ns
-5.6097348584e-05, // time = 1.09 ns
-5.9563806262e-05, // time = 1.10 ns
-6.3188126349e-05, // time = 1.11 ns
-6.6974408037e-05, // time = 1.12 ns
-7.0926720924e-05, // time = 1.13 ns
-7.5049099141e-05, // time = 1.14 ns
-7.9345531193e-05, // time = 1.15 ns
-8.3819956734e-05, // time = 1.16 ns
-8.8476260003e-05, // time = 1.17 ns
-9.3318263438e-05, // time = 1.18 ns
-9.8349721632e-05, // time = 1.19 ns
-1.0357431515e-04, // time = 1.20 ns
-1.0899564437e-04, // time = 1.21 ns
-1.1461722328e-04, // time = 1.22 ns
-1.2044247342e-04, // time = 1.23 ns
-1.2647471763e-04, // time = 1.24 ns
-1.3271717411e-04, // time = 1.25 ns
-1.3917295025e-04, // time = 1.26 ns
-1.4584503675e-04, // time = 1.27 ns
-1.5273630162e-04, // time = 1.28 ns
-1.5984948437e-04, // time = 1.29 ns
-1.6718719027e-04, // time = 1.30 ns
-1.7475188462e-04, // time = 1.31 ns
-1.8254588721e-04, // time = 1.32 ns
-1.9057136684e-04, // time = 1.33 ns
-1.9883033599e-04, // time = 1.34 ns
-2.0732464557e-04, // time = 1.35 ns
-2.1605597986e-04, // time = 1.36 ns
-2.2502585153e-04, // time = 1.37 ns
-2.3423559683e-04, // time = 1.38 ns
-2.4368637096e-04, // time = 1.39 ns
-2.5337914358e-04, // time = 1.40 ns
-2.6331469448e-04, // time = 1.41 ns
-2.7349360942e-04, // time = 1.42 ns
-2.8391627619e-04, // time = 1.43 ns
-2.9458288078e-04, // time = 1.44 ns
-3.0549340385e-04, // time = 1.45 ns
-3.1664761726e-04, // time = 1.46 ns
-3.2804508092e-04, // time = 1.47 ns
-3.3968513979e-04, // time = 1.48 ns
-3.5156692107e-04, // time = 1.49 ns
-3.6368933162e-04, // time = 1.50 ns
-3.7605105565e-04, // time = 1.51 ns
-3.8865055252e-04, // time = 1.52 ns
-4.0148605485e-04, // time = 1.53 ns
-4.1455556680e-04, // time = 1.54 ns
-4.2785686263e-04, // time = 1.55 ns
-4.4138748543e-04, // time = 1.56 ns
-4.5514474611e-04, // time = 1.57 ns
-4.6912572260e-04, // time = 1.58 ns
-4.8332725934e-04, // time = 1.59 ns
-4.9774596689e-04, // time = 1.60 ns
-5.1237822188e-04, // time = 1.61 ns
-5.2722016714e-04, // time = 1.62 ns
-5.4226771206e-04, // time = 1.63 ns
-5.5751653319e-04, // time = 1.64 ns
-5.7296207508e-04, // time = 1.65 ns
-5.8859955132e-04, // time = 1.66 ns
-6.0442394582e-04, // time = 1.67 ns
-6.2043001434e-04, // time = 1.68 ns
-6.3661228620e-04, // time = 1.69 ns
-6.5296506622e-04, // time = 1.70 ns
-6.6948243690e-04, // time = 1.71 ns
-6.8615826080e-04, // time = 1.72 ns
-7.0298618312e-04, // time = 1.73 ns
-7.1995963450e-04, // time = 1.74 ns
-7.3707183401e-04, // time = 1.75 ns
-7.5431579238e-04, // time = 1.76 ns
-7.7168431535e-04, // time = 1.77 ns
-7.8917000729e-04, // time = 1.78 ns
-8.0676527497e-04, // time = 1.79 ns
-8.2446233149e-04, // time = 1.80 ns
-8.4225320045e-04, // time = 1.81 ns
-8.6012972022e-04, // time = 1.82 ns
-8.7808354870e-04, // time = 1.83 ns
-8.9610616512e-04, // time = 1.84 ns
-9.1418888139e-04, // time = 1.85 ns
-9.3232283629e-04, // time = 1.86 ns
-9.5049901013e-04, // time = 1.87 ns
-9.6870822595e-04, // time = 1.88 ns
-9.8694115563e-04, // time = 1.89 ns
-1.0051883255e-03, // time = 1.90 ns
-1.0234401218e-03, // time = 1.91 ns
-1.0416867967e-03, // time = 1.92 ns
-1.0599184739e-03, // time = 1.93 ns
-1.0781251549e-03, // time = 1.94 ns
-1.0962967247e-03, // time = 1.95 ns
-1.1144229579e-03, // time = 1.96 ns
-1.1324935253e-03, // time = 1.97 ns
-1.1504979999e-03, // time = 1.98 ns
-1.1684258631e-03, // time = 1.99 ns
-1.1862665113e-03, // time = 2.00 ns
-1.2040092622e-03, // time = 2.01 ns
-1.2216433615e-03, // time = 2.02 ns
-1.2391579888e-03, // time = 2.03 ns
-1.2565422649e-03, // time = 2.04 ns
-1.2737852580e-03, // time = 2.05 ns
-1.2908759901e-03, // time = 2.06 ns
-1.3078034437e-03, // time = 2.07 ns
-1.3245565688e-03, // time = 2.08 ns
-1.3411242886e-03, // time = 2.09 ns
-1.3574955070e-03, // time = 2.10 ns
-1.3736591146e-03, // time = 2.11 ns
-1.3896039953e-03, // time = 2.12 ns
-1.4053190331e-03, // time = 2.13 ns
-1.4207931181e-03, // time = 2.14 ns
-1.4360151533e-03, // time = 2.15 ns
-1.4509740610e-03, // time = 2.16 ns
-1.4656587888e-03, // time = 2.17 ns
-1.4800583162e-03, // time = 2.18 ns
-1.4941616608e-03, // time = 2.19 ns
-1.5079578842e-03, // time = 2.20 ns
-1.5214360984e-03, // time = 2.21 ns
-1.5345854715e-03, // time = 2.22 ns
-1.5473952339e-03, // time = 2.23 ns
-1.5598546839e-03, // time = 2.24 ns
-1.5719531936e-03, // time = 2.25 ns
-1.5836802143e-03, // time = 2.26 ns
-1.5950252824e-03, // time = 2.27 ns
-1.6059780247e-03, // time = 2.28 ns
-1.6165281633e-03, // time = 2.29 ns
-1.6266655216e-03, // time = 2.30 ns
-1.6363800289e-03, // time = 2.31 ns
-1.6456617252e-03, // time = 2.32 ns
-1.6545007667e-03, // time = 2.33 ns
-1.6628874298e-03, // time = 2.34 ns
-1.6708121163e-03, // time = 2.35 ns
-1.6782653573e-03, // time = 2.36 ns
-1.6852378175e-03, // time = 2.37 ns
-1.6917203012e-03, // time = 2.38 ns
-1.6977037542e-03, // time = 2.39 ns
-1.7031792681e-03, // time = 2.40 ns
-1.7081380846e-03, // time = 2.41 ns
-1.7125715987e-03, // time = 2.42 ns
-1.7164713625e-03, // time = 2.43 ns
-1.7198290885e-03, // time = 2.44 ns
-1.7226366526e-03, // time = 2.45 ns
-1.7248860974e-03, // time = 2.46 ns
-1.7265696347e-03, // time = 2.47 ns
-1.7276796487e-03, // time = 2.48 ns
-1.7282086985e-03, // time = 2.49 ns
-1.7281495201e-03, // time = 2.50 ns
-1.7274950291e-03, // time = 2.51 ns
-1.7262383228e-03, // time = 2.52 ns
-1.7243726818e-03, // time = 2.53 ns
-1.7218915725e-03, // time = 2.54 ns
-1.7187886480e-03, // time = 2.55 ns
-1.7150577502e-03, // time = 2.56 ns
-1.7106929109e-03, // time = 2.57 ns
-1.7056883528e-03, // time = 2.58 ns
-1.7000384913e-03, // time = 2.59 ns
-1.6937379346e-03, // time = 2.60 ns
-1.6867814849e-03, // time = 2.61 ns
-1.6791641390e-03, // time = 2.62 ns
-1.6708810885e-03, // time = 2.63 ns
-1.6619277206e-03, // time = 2.64 ns
-1.6522996178e-03, // time = 2.65 ns
-1.6419925584e-03, // time = 2.66 ns
-1.6310025160e-03, // time = 2.67 ns
-1.6193256595e-03, // time = 2.68 ns
-1.6069583529e-03, // time = 2.69 ns
-1.5938971545e-03, // time = 2.70 ns
-1.5801388166e-03, // time = 2.71 ns
-1.5656802850e-03, // time = 2.72 ns
-1.5505186975e-03, // time = 2.73 ns
-1.5346513840e-03, // time = 2.74 ns
-1.5180758648e-03, // time = 2.75 ns
-1.5007898494e-03, // time = 2.76 ns
-1.4827912360e-03, // time = 2.77 ns
-1.4640781092e-03, // time = 2.78 ns
-1.4446487391e-03, // time = 2.79 ns
-1.4245015792e-03, // time = 2.80 ns
-1.4036352652e-03, // time = 2.81 ns
-1.3820486123e-03, // time = 2.82 ns
-1.3597406141e-03, // time = 2.83 ns
-1.3367104399e-03, // time = 2.84 ns
-1.3129574327e-03, // time = 2.85 ns
-1.2884811073e-03, // time = 2.86 ns
-1.2632811475e-03, // time = 2.87 ns
-1.2373574043e-03, // time = 2.88 ns
-1.2107098932e-03, // time = 2.89 ns
-1.1833387916e-03, // time = 2.90 ns
-1.1552444364e-03, // time = 2.91 ns
-1.1264273217e-03, // time = 2.92 ns
-1.0968880957e-03, // time = 2.93 ns
-1.0666275581e-03, // time = 2.94 ns
-1.0356466577e-03, // time = 2.95 ns
-1.0039464889e-03, // time = 2.96 ns
-9.7152828955e-04, // time = 2.97 ns
-9.3839343764e-04, // time = 2.98 ns
-9.0454344845e-04, // time = 2.99 ns
-8.6997997154e-04, // time = 3.00 ns
-8.3470478776e-04, // time = 3.01 ns
-7.9871980617e-04, // time = 3.02 ns
-7.6202706096e-04, // time = 3.03 ns
-7.2462870834e-04, // time = 3.04 ns
-6.8652702340e-04, // time = 3.05 ns
-6.4772439695e-04, // time = 3.06 ns
-6.0822333237e-04, // time = 3.07 ns
-5.6802644240e-04, // time = 3.08 ns
-5.2713644594e-04, // time = 3.09 ns
-4.8555616488e-04, // time = 3.10 ns
-4.4328852086e-04, // time = 3.11 ns
-4.0033653207e-04, // time = 3.12 ns
-3.5670331004e-04, // time = 3.13 ns
-3.1239205647e-04, // time = 3.14 ns
-2.6740605998e-04, // time = 3.15 ns
-2.2174869298e-04, // time = 3.16 ns
-1.7542340844e-04, // time = 3.17 ns
-1.2843373679e-04, // time = 3.18 ns
-8.0783282762e-05, // time = 3.19 ns
-3.2475722243e-05, // time = 3.20 ns
1.6485200779e-05, // time = 3.21 ns
6.6095677302e-05, // time = 3.22 ns
1.1635183635e-04, // time = 3.23 ns
1.6724974797e-04, // time = 3.24 ns
2.1878542624e-04, // time = 3.25 ns
2.7095483219e-04, // time = 3.26 ns
3.2375387672e-04, // time = 3.27 ns
3.7717842347e-04, // time = 3.28 ns
4.3122429166e-04, // time = 3.29 ns
4.8588725888e-04, // time = 3.30 ns
5.4116306386e-04, // time = 3.31 ns
5.9704740916e-04, // time = 3.32 ns
6.5353596389e-04, // time = 3.33 ns
7.1062436634e-04, // time = 3.34 ns
7.6830822657e-04, // time = 3.35 ns
8.2658312899e-04, // time = 3.36 ns
8.8544463489e-04, // time = 3.37 ns
9.4488820643e-04, // time = 3.38 ns
1.0049094504e-03, // time = 3.39 ns
1.0655038807e-03, // time = 3.40 ns
1.1266669869e-03, // time = 3.41 ns
1.1883942488e-03, // time = 3.42 ns
1.2506811381e-03, // time = 3.43 ns
1.3135231205e-03, // time = 3.44 ns
1.3769156571e-03, // time = 3.45 ns
1.4408542068e-03, // time = 3.46 ns
1.5053342278e-03, // time = 3.47 ns
1.5703511797e-03, // time = 3.48 ns
1.6359005250e-03, // time = 3.49 ns
1.7019777312e-03, // time = 3.50 ns
1.7685782720e-03, // time = 3.51 ns
1.8356976293e-03, // time = 3.52 ns
1.9033312948e-03, // time = 3.53 ns
1.9714747707e-03, // time = 3.54 ns
2.0401235722e-03, // time = 3.55 ns
2.1092732279e-03, // time = 3.56 ns
2.1789192818e-03, // time = 3.57 ns
2.2490572943e-03, // time = 3.58 ns
2.3196828431e-03, // time = 3.59 ns
2.3907915249e-03, // time = 3.60 ns
2.4623789561e-03, // time = 3.61 ns
2.5344407742e-03, // time = 3.62 ns
2.6069726385e-03, // time = 3.63 ns
2.6799702312e-03, // time = 3.64 ns
2.7534292657e-03, // time = 3.65 ns
2.8273454612e-03, // time = 3.66 ns
2.9004936634e-03, // time = 3.67 ns
2.9753041809e-03, // time = 3.68 ns
3.0505592690e-03, // time = 3.69 ns
3.1262547713e-03, // time = 3.70 ns
3.2023865546e-03, // time = 3.71 ns
3.2789505127e-03, // time = 3.72 ns
3.3559425677e-03, // time = 3.73 ns
3.4333586712e-03, // time = 3.74 ns
3.5111948046e-03, // time = 3.75 ns
3.5894469797e-03, // time = 3.76 ns
3.6681112388e-03, // time = 3.77 ns
3.7471836550e-03, // time = 3.78 ns
3.8266603326e-03, // time = 3.79 ns
3.9065374069e-03, // time = 3.80 ns
3.9868110444e-03, // time = 3.81 ns
4.0674774430e-03, // time = 3.82 ns
4.1485328319e-03, // time = 3.83 ns
4.2299734716e-03, // time = 3.84 ns
4.3117956536e-03, // time = 3.85 ns
4.3939957008e-03, // time = 3.86 ns
4.4765699668e-03, // time = 3.87 ns
4.5595148362e-03, // time = 3.88 ns
4.6428267257e-03, // time = 3.89 ns
4.7167852365e-03, // time = 3.90 ns
4.8007790901e-03, // time = 3.91 ns
4.8602278847e-03, // time = 3.92 ns
4.9448283036e-03, // time = 3.93 ns
5.0297795076e-03, // time = 3.94 ns
5.1150781817e-03, // time = 3.95 ns
5.2007209700e-03, // time = 3.96 ns
5.2867045217e-03, // time = 3.97 ns
5.3730255059e-03, // time = 3.98 ns
5.4596806154e-03, // time = 3.99 ns
5.5466665690e-03, // time = 4.00 ns
5.6339801110e-03, // time = 4.01 ns
5.7216180108e-03, // time = 4.02 ns
5.8095770632e-03, // time = 4.03 ns
5.8978540871e-03, // time = 4.04 ns
5.9864459255e-03, // time = 4.05 ns
6.0753494447e-03, // time = 4.06 ns
6.1645615335e-03, // time = 4.07 ns
6.2540791032e-03, // time = 4.08 ns
6.3438990863e-03, // time = 4.09 ns
6.4340184360e-03, // time = 4.10 ns
6.5244341258e-03, // time = 4.11 ns
6.6151431482e-03, // time = 4.12 ns
6.7061425143e-03, // time = 4.13 ns
6.7974292525e-03, // time = 4.14 ns
6.8890004077e-03, // time = 4.15 ns
6.9808530397e-03, // time = 4.16 ns
7.0729842211e-03, // time = 4.17 ns
7.1653910353e-03, // time = 4.18 ns
7.2580705721e-03, // time = 4.19 ns
7.3440609829e-03, // time = 4.20 ns
7.4372574280e-03, // time = 4.21 ns
7.5073204958e-03, // time = 4.22 ns
7.6009774774e-03, // time = 4.23 ns
7.7647108412e-03, // time = 4.24 ns
7.8590715385e-03, // time = 4.25 ns
7.9484164301e-03, // time = 4.26 ns
8.0432639316e-03, // time = 4.27 ns
8.1138466413e-03, // time = 4.28 ns
8.2091218951e-03, // time = 4.29 ns
8.2682310074e-03, // time = 4.30 ns
8.3882494626e-03, // time = 4.31 ns
8.4485916243e-03, // time = 4.32 ns
8.6238415442e-03, // time = 4.33 ns
8.6992927207e-03, // time = 4.34 ns
8.7960008706e-03, // time = 4.35 ns
8.8872807764e-03, // time = 4.36 ns
9.0087432445e-03, // time = 4.37 ns
9.0330481367e-03, // time = 4.38 ns
9.1791618919e-03, // time = 4.39 ns
9.2393257128e-03, // time = 4.40 ns
9.3512527409e-03, // time = 4.41 ns
9.4301714377e-03, // time = 4.42 ns
9.5490812208e-03, // time = 4.43 ns
9.6185900085e-03, // time = 4.44 ns
9.7501114884e-03, // time = 4.45 ns
9.8311335529e-03, // time = 4.46 ns
9.9453750716e-03, // time = 4.47 ns
1.0032655612e-02, // time = 4.48 ns
1.0129949633e-02, // time = 4.49 ns
1.0233282313e-02, // time = 4.50 ns
1.0330049789e-02, // time = 4.51 ns
1.0428020767e-02, // time = 4.52 ns
1.0519332740e-02, // time = 4.53 ns
1.0663759777e-02, // time = 4.54 ns
1.0713409214e-02, // time = 4.55 ns
1.0821962628e-02, // time = 4.56 ns
1.0928230994e-02, // time = 4.57 ns
1.1043194443e-02, // time = 4.58 ns
1.1124551205e-02, // time = 4.59 ns
1.1240042896e-02, // time = 4.60 ns
1.1394909737e-02, // time = 4.61 ns
1.1441355211e-02, // time = 4.62 ns
1.1583062859e-02, // time = 4.63 ns
1.1668960709e-02, // time = 4.64 ns
1.1762635066e-02, // time = 4.65 ns
1.1897117463e-02, // time = 4.66 ns
1.1949376610e-02, // time = 4.67 ns
1.2065564472e-02, // time = 4.68 ns
1.2235715286e-02, // time = 4.69 ns
1.2314042756e-02, // time = 4.70 ns
1.2417100757e-02, // time = 4.71 ns
1.2520291356e-02, // time = 4.72 ns
1.2618292406e-02, // time = 4.73 ns
1.2721731609e-02, // time = 4.74 ns
1.2812262041e-02, // time = 4.75 ns
1.2915930238e-02, // time = 4.76 ns
1.3000112926e-02, // time = 4.77 ns
1.3103994632e-02, // time = 4.78 ns
1.3186315779e-02, // time = 4.79 ns
1.3290401753e-02, // time = 4.80 ns
1.3476565381e-02, // time = 4.81 ns
1.3558770823e-02, // time = 4.82 ns
1.3663242074e-02, // time = 4.83 ns
1.3746429521e-02, // time = 4.84 ns
1.3851081299e-02, // time = 4.85 ns
1.3936013604e-02, // time = 4.86 ns
1.4040837033e-02, // time = 4.87 ns
1.4128651587e-02, // time = 4.88 ns
1.4233637367e-02, // time = 4.89 ns
1.4325700198e-02, // time = 4.90 ns
1.4430838689e-02, // time = 4.91 ns
1.4634285904e-02, // time = 4.92 ns
1.4739635467e-02, // time = 4.93 ns
1.4845049260e-02, // time = 4.94 ns
1.4950523396e-02, // time = 4.95 ns
1.5056054031e-02, // time = 4.96 ns
1.5161637389e-02, // time = 4.97 ns
1.5267269775e-02, // time = 4.98 ns
1.5372947583e-02, // time = 4.99 ns
1.5478667303e-02, // time = 5.00 ns
1.5584425527e-02, // time = 5.01 ns
1.5690218947e-02, // time = 5.02 ns
1.5796044353e-02, // time = 5.03 ns
1.5901898634e-02, // time = 5.04 ns
1.6007778772e-02, // time = 5.05 ns
1.6113681836e-02, // time = 5.06 ns
1.6219604975e-02, // time = 5.07 ns
1.6325545415e-02, // time = 5.08 ns
1.6431500448e-02, // time = 5.09 ns
1.6537467426e-02, // time = 5.10 ns
1.6643443754e-02, // time = 5.11 ns
1.6749426882e-02, // time = 5.12 ns
1.6855414301e-02, // time = 5.13 ns
1.6961403529e-02, // time = 5.14 ns
1.7067392113e-02, // time = 5.15 ns
1.7173377618e-02, // time = 5.16 ns
1.7279357622e-02, // time = 5.17 ns
1.7385329714e-02, // time = 5.18 ns
1.7491291488e-02, // time = 5.19 ns
1.7597240536e-02, // time = 5.20 ns
1.7703174451e-02, // time = 5.21 ns
1.7809090822e-02, // time = 5.22 ns
1.7914987227e-02, // time = 5.23 ns
1.8020861240e-02, // time = 5.24 ns
1.8126710423e-02, // time = 5.25 ns
1.8232532328e-02, // time = 5.26 ns
1.8338324496e-02, // time = 5.27 ns
1.8444084459e-02, // time = 5.28 ns
1.8549809734e-02, // time = 5.29 ns
1.8655497834e-02, // time = 5.30 ns
1.8761146256e-02, // time = 5.31 ns
1.8866752493e-02, // time = 5.32 ns
1.8972314029e-02, // time = 5.33 ns
1.9077828342e-02, // time = 5.34 ns
1.9183292903e-02, // time = 5.35 ns
1.9288705183e-02, // time = 5.36 ns
1.9394062647e-02, // time = 5.37 ns
1.9499362761e-02, // time = 5.38 ns
1.9604602991e-02, // time = 5.39 ns
1.9709780805e-02, // time = 5.40 ns
1.9814893674e-02, // time = 5.41 ns
1.9919939073e-02, // time = 5.42 ns
2.0024914485e-02, // time = 5.43 ns
2.0129817397e-02, // time = 5.44 ns
2.0234645308e-02, // time = 5.45 ns
2.0339395722e-02, // time = 5.46 ns
2.0444066159e-02, // time = 5.47 ns
2.0548654146e-02, // time = 5.48 ns
2.0653157225e-02, // time = 5.49 ns
2.0757572950e-02, // time = 5.50 ns
2.0861898891e-02, // time = 5.51 ns
2.0966132631e-02, // time = 5.52 ns
2.1070271770e-02, // time = 5.53 ns
2.1174313924e-02, // time = 5.54 ns
2.1278256725e-02, // time = 5.55 ns
2.1382097823e-02, // time = 5.56 ns
2.1485834887e-02, // time = 5.57 ns
2.1589465602e-02, // time = 5.58 ns
2.1692987672e-02, // time = 5.59 ns
2.1796398820e-02, // time = 5.60 ns
2.1899696790e-02, // time = 5.61 ns
2.2002879342e-02, // time = 5.62 ns
2.2105944257e-02, // time = 5.63 ns
2.2208889335e-02, // time = 5.64 ns
2.2311712397e-02, // time = 5.65 ns
2.2414411282e-02, // time = 5.66 ns
2.2516983850e-02, // time = 5.67 ns
2.2619427980e-02, // time = 5.68 ns
2.2721741570e-02, // time = 5.69 ns
2.2823922540e-02, // time = 5.70 ns
2.2925968827e-02, // time = 5.71 ns
2.3027878390e-02, // time = 5.72 ns
2.3129649206e-02, // time = 5.73 ns
2.3231279271e-02, // time = 5.74 ns
2.3332766602e-02, // time = 5.75 ns
2.3434109235e-02, // time = 5.76 ns
2.3535305224e-02, // time = 5.77 ns
2.3636352643e-02, // time = 5.78 ns
2.3737249584e-02, // time = 5.79 ns
2.3837994159e-02, // time = 5.80 ns
2.3938584498e-02, // time = 5.81 ns
2.4039018750e-02, // time = 5.82 ns
2.4139295081e-02, // time = 5.83 ns
2.4239411677e-02, // time = 5.84 ns
2.4339366743e-02, // time = 5.85 ns
2.4439158498e-02, // time = 5.86 ns
2.4538785183e-02, // time = 5.87 ns
2.4638245056e-02, // time = 5.88 ns
2.4737536390e-02, // time = 5.89 ns
2.4836657480e-02, // time = 5.90 ns
2.4935606635e-02, // time = 5.91 ns
2.5034382182e-02, // time = 5.92 ns
2.5132982467e-02, // time = 5.93 ns
2.5231405850e-02, // time = 5.94 ns
2.5329650711e-02, // time = 5.95 ns
2.5427715445e-02, // time = 5.96 ns
2.5525598466e-02, // time = 5.97 ns
2.5623298201e-02, // time = 5.98 ns
2.5720813097e-02, // time = 5.99 ns
2.5818141616e-02, // time = 6.00 ns
2.5915282237e-02, // time = 6.01 ns
2.6012233454e-02, // time = 6.02 ns
2.6108993779e-02, // time = 6.03 ns
2.6205561738e-02, // time = 6.04 ns
2.6301935875e-02, // time = 6.05 ns
2.6398114748e-02, // time = 6.06 ns
2.6494096932e-02, // time = 6.07 ns
2.6589881018e-02, // time = 6.08 ns
2.6685465611e-02, // time = 6.09 ns
2.6780849333e-02, // time = 6.10 ns
2.6876030820e-02, // time = 6.11 ns
2.6971008724e-02, // time = 6.12 ns
2.7065781713e-02, // time = 6.13 ns
2.7160348468e-02, // time = 6.14 ns
2.7254707686e-02, // time = 6.15 ns
2.7348858078e-02, // time = 6.16 ns
2.7442798373e-02, // time = 6.17 ns
2.7536527310e-02, // time = 6.18 ns
2.7630043645e-02, // time = 6.19 ns
2.7723346149e-02, // time = 6.20 ns
2.7816433605e-02, // time = 6.21 ns
2.7909304812e-02, // time = 6.22 ns
2.8001958582e-02, // time = 6.23 ns
2.8094393742e-02, // time = 6.24 ns
2.8186609131e-02, // time = 6.25 ns
2.8278603605e-02, // time = 6.26 ns
2.8370376030e-02, // time = 6.27 ns
2.8461925288e-02, // time = 6.28 ns
2.8553250273e-02, // time = 6.29 ns
2.8644349892e-02, // time = 6.30 ns
2.8735223067e-02, // time = 6.31 ns
2.8825868731e-02, // time = 6.32 ns
2.8916285832e-02, // time = 6.33 ns
2.9006473329e-02, // time = 6.34 ns
2.9096430194e-02, // time = 6.35 ns
2.9186155413e-02, // time = 6.36 ns
2.9275647982e-02, // time = 6.37 ns
2.9364906913e-02, // time = 6.38 ns
2.9453931227e-02, // time = 6.39 ns
2.9542719958e-02, // time = 6.40 ns
2.9631272154e-02, // time = 6.41 ns
2.9719586872e-02, // time = 6.42 ns
2.9807663183e-02, // time = 6.43 ns
2.9895500169e-02, // time = 6.44 ns
2.9983096924e-02, // time = 6.45 ns
3.0070452553e-02, // time = 6.46 ns
3.0157566173e-02, // time = 6.47 ns
3.0244436913e-02, // time = 6.48 ns
3.0331063911e-02, // time = 6.49 ns
3.0417446319e-02, // time = 6.50 ns
3.0503583299e-02, // time = 6.51 ns
3.0589474023e-02, // time = 6.52 ns
3.0675117675e-02, // time = 6.53 ns
3.0760513450e-02, // time = 6.54 ns
3.0845660553e-02, // time = 6.55 ns
3.0930558200e-02, // time = 6.56 ns
3.1015205618e-02, // time = 6.57 ns
3.1099602044e-02, // time = 6.58 ns
3.1183746726e-02, // time = 6.59 ns
3.1267638921e-02, // time = 6.60 ns
3.1351277899e-02, // time = 6.61 ns
3.1434662936e-02, // time = 6.62 ns
3.1517793322e-02, // time = 6.63 ns
3.1600668355e-02, // time = 6.64 ns
3.1683287345e-02, // time = 6.65 ns
3.1765649608e-02, // time = 6.66 ns
3.1847754474e-02, // time = 6.67 ns
3.1929601281e-02, // time = 6.68 ns
3.2011189377e-02, // time = 6.69 ns
3.2092518118e-02, // time = 6.70 ns
3.2173586873e-02, // time = 6.71 ns
3.2254395017e-02, // time = 6.72 ns
3.2334941937e-02, // time = 6.73 ns
3.2415227027e-02, // time = 6.74 ns
3.2495249694e-02, // time = 6.75 ns
3.2575009350e-02, // time = 6.76 ns
3.2654505420e-02, // time = 6.77 ns
3.2733737335e-02, // time = 6.78 ns
3.2812704537e-02, // time = 6.79 ns
3.2891406477e-02, // time = 6.80 ns
3.2969842615e-02, // time = 6.81 ns
3.3048012418e-02, // time = 6.82 ns
3.3125915365e-02, // time = 6.83 ns
3.3203550943e-02, // time = 6.84 ns
3.3280918645e-02, // time = 6.85 ns
3.3358017977e-02, // time = 6.86 ns
3.3434848450e-02, // time = 6.87 ns
3.3511409587e-02, // time = 6.88 ns
3.3587700917e-02, // time = 6.89 ns
3.3663721980e-02, // time = 6.90 ns
3.3739472321e-02, // time = 6.91 ns
3.3814951497e-02, // time = 6.92 ns
3.3890159072e-02, // time = 6.93 ns
3.3965094619e-02, // time = 6.94 ns
3.4039757717e-02, // time = 6.95 ns
3.4114147958e-02, // time = 6.96 ns
3.4188264937e-02, // time = 6.97 ns
3.4262108261e-02, // time = 6.98 ns
3.4335677544e-02, // time = 6.99 ns
3.4408972408e-02, // time = 7.00 ns
3.4481992483e-02, // time = 7.01 ns
3.4554737407e-02, // time = 7.02 ns
3.4627206828e-02, // time = 7.03 ns
3.4699400399e-02, // time = 7.04 ns
3.4771317782e-02, // time = 7.05 ns
3.4842958649e-02, // time = 7.06 ns
3.4914322677e-02, // time = 7.07 ns
3.4985409552e-02, // time = 7.08 ns
3.5056218968e-02, // time = 7.09 ns
3.5126750628e-02, // time = 7.10 ns
3.5197004239e-02, // time = 7.11 ns
3.5266979521e-02, // time = 7.12 ns
3.5336676196e-02, // time = 7.13 ns
3.5406093999e-02, // time = 7.14 ns
3.5475232668e-02, // time = 7.15 ns
3.5544091952e-02, // time = 7.16 ns
3.5612671605e-02, // time = 7.17 ns
3.5680971390e-02, // time = 7.18 ns
3.5748991078e-02, // time = 7.19 ns
3.5816730445e-02, // time = 7.20 ns
3.5884189277e-02, // time = 7.21 ns
3.5951367365e-02, // time = 7.22 ns
3.6018264510e-02, // time = 7.23 ns
3.6084880518e-02, // time = 7.24 ns
3.6151215202e-02, // time = 7.25 ns
3.6217268385e-02, // time = 7.26 ns
3.6283039894e-02, // time = 7.27 ns
3.6348529564e-02, // time = 7.28 ns
3.6413737239e-02, // time = 7.29 ns
3.6478662768e-02, // time = 7.30 ns
3.6543306006e-02, // time = 7.31 ns
3.6607666819e-02, // time = 7.32 ns
3.6671745075e-02, // time = 7.33 ns
3.6735540652e-02, // time = 7.34 ns
3.6799053435e-02, // time = 7.35 ns
3.6862283314e-02, // time = 7.36 ns
3.6925230186e-02, // time = 7.37 ns
3.6987893957e-02, // time = 7.38 ns
3.7050274537e-02, // time = 7.39 ns
3.7112371844e-02, // time = 7.40 ns
3.7174185802e-02, // time = 7.41 ns
3.7235716342e-02, // time = 7.42 ns
3.7296963401e-02, // time = 7.43 ns
3.7357926924e-02, // time = 7.44 ns
3.7418606859e-02, // time = 7.45 ns
3.7479003165e-02, // time = 7.46 ns
3.7539115804e-02, // time = 7.47 ns
3.7598944746e-02, // time = 7.48 ns
3.7658489965e-02, // time = 7.49 ns
3.7717751444e-02, // time = 7.50 ns
3.7776729171e-02, // time = 7.51 ns
3.7835423140e-02, // time = 7.52 ns
3.7893833352e-02, // time = 7.53 ns
3.7951959812e-02, // time = 7.54 ns
3.8009802534e-02, // time = 7.55 ns
3.8067361534e-02, // time = 7.56 ns
3.8124636839e-02, // time = 7.57 ns
3.8181628477e-02, // time = 7.58 ns
3.8238336486e-02, // time = 7.59 ns
3.8294760907e-02, // time = 7.60 ns
3.8350901786e-02, // time = 7.61 ns
3.8406759179e-02, // time = 7.62 ns
3.8462333144e-02, // time = 7.63 ns
3.8517623746e-02, // time = 7.64 ns
3.8572631054e-02, // time = 7.65 ns
3.8627355146e-02, // time = 7.66 ns
3.8681796102e-02, // time = 7.67 ns
3.8735954008e-02, // time = 7.68 ns
3.8789828959e-02, // time = 7.69 ns
3.8843421050e-02, // time = 7.70 ns
3.8896730386e-02, // time = 7.71 ns
3.8949757074e-02, // time = 7.72 ns
3.9002501228e-02, // time = 7.73 ns
3.9054962968e-02, // time = 7.74 ns
3.9107142416e-02, // time = 7.75 ns
3.9159039703e-02, // time = 7.76 ns
3.9210654962e-02, // time = 7.77 ns
3.9261988333e-02, // time = 7.78 ns
3.9313039960e-02, // time = 7.79 ns
3.9363809992e-02, // time = 7.80 ns
3.9414298585e-02, // time = 7.81 ns
3.9464505896e-02, // time = 7.82 ns
3.9514432090e-02, // time = 7.83 ns
3.9564077336e-02, // time = 7.84 ns
3.9613441807e-02, // time = 7.85 ns
3.9662525682e-02, // time = 7.86 ns
3.9711329143e-02, // time = 7.87 ns
3.9759852379e-02, // time = 7.88 ns
3.9808095582e-02, // time = 7.89 ns
3.9856058947e-02, // time = 7.90 ns
3.9903742678e-02, // time = 7.91 ns
3.9951146980e-02, // time = 7.92 ns
3.9998272062e-02, // time = 7.93 ns
4.0045118140e-02, // time = 7.94 ns
4.0091685433e-02, // time = 7.95 ns
4.0137974165e-02, // time = 7.96 ns
4.0183984562e-02, // time = 7.97 ns
4.0229716858e-02, // time = 7.98 ns
4.0275171288e-02, // time = 7.99 ns
4.0320348093e-02, // time = 8.00 ns
4.0365247518e-02, // time = 8.01 ns
4.0409869810e-02, // time = 8.02 ns
4.0454215224e-02, // time = 8.03 ns
4.0498284015e-02, // time = 8.04 ns
4.0542076445e-02, // time = 8.05 ns
4.0585592779e-02, // time = 8.06 ns
4.0628833284e-02, // time = 8.07 ns
4.0671798234e-02, // time = 8.08 ns
4.0714487906e-02, // time = 8.09 ns
4.0756902579e-02, // time = 8.10 ns
4.0799042538e-02, // time = 8.11 ns
4.0840908071e-02, // time = 8.12 ns
4.0882499469e-02, // time = 8.13 ns
4.0923817027e-02, // time = 8.14 ns
4.0964861045e-02, // time = 8.15 ns
4.1005631825e-02, // time = 8.16 ns
4.1046129674e-02, // time = 8.17 ns
4.1086354900e-02, // time = 8.18 ns
4.1126307818e-02, // time = 8.19 ns
4.1165988744e-02, // time = 8.20 ns
4.1205397998e-02, // time = 8.21 ns
4.1244535904e-02, // time = 8.22 ns
4.1283402790e-02, // time = 8.23 ns
4.1321998985e-02, // time = 8.24 ns
4.1360324823e-02, // time = 8.25 ns
4.1398380641e-02, // time = 8.26 ns
4.1436166781e-02, // time = 8.27 ns
4.1473683584e-02, // time = 8.28 ns
4.1510931399e-02, // time = 8.29 ns
4.1547910575e-02, // time = 8.30 ns
4.1584621466e-02, // time = 8.31 ns
4.1621064427e-02, // time = 8.32 ns
4.1657239819e-02, // time = 8.33 ns
4.1693148003e-02, // time = 8.34 ns
4.1728789345e-02, // time = 8.35 ns
4.1764164214e-02, // time = 8.36 ns
4.1799272982e-02, // time = 8.37 ns
4.1834116022e-02, // time = 8.38 ns
4.1868693712e-02, // time = 8.39 ns
4.1903006433e-02, // time = 8.40 ns
4.1937054567e-02, // time = 8.41 ns
4.1970838502e-02, // time = 8.42 ns
4.2004358625e-02, // time = 8.43 ns
4.2037615328e-02, // time = 8.44 ns
4.2070609006e-02, // time = 8.45 ns
4.2103340056e-02, // time = 8.46 ns
4.2135808878e-02, // time = 8.47 ns
4.2168015875e-02, // time = 8.48 ns
4.2199961451e-02, // time = 8.49 ns
4.2231646015e-02, // time = 8.50 ns
4.2263069977e-02, // time = 8.51 ns
4.2294233751e-02, // time = 8.52 ns
4.2325137751e-02, // time = 8.53 ns
4.2355782397e-02, // time = 8.54 ns
4.2386168109e-02, // time = 8.55 ns
4.2416295310e-02, // time = 8.56 ns
4.2446164425e-02, // time = 8.57 ns
4.2475775884e-02, // time = 8.58 ns
4.2505130116e-02, // time = 8.59 ns
4.2534227555e-02, // time = 8.60 ns
4.2563068635e-02, // time = 8.61 ns
4.2591653795e-02, // time = 8.62 ns
4.2619983474e-02, // time = 8.63 ns
4.2648058114e-02, // time = 8.64 ns
4.2675878161e-02, // time = 8.65 ns
4.2703444060e-02, // time = 8.66 ns
4.2730756261e-02, // time = 8.67 ns
4.2757815216e-02, // time = 8.68 ns
4.2784621377e-02, // time = 8.69 ns
4.2811175199e-02, // time = 8.70 ns
4.2837477142e-02, // time = 8.71 ns
4.2863527663e-02, // time = 8.72 ns
4.2889327226e-02, // time = 8.73 ns
4.2914876294e-02, // time = 8.74 ns
4.2940175333e-02, // time = 8.75 ns
4.2965224811e-02, // time = 8.76 ns
4.2990025198e-02, // time = 8.77 ns
4.3014576966e-02, // time = 8.78 ns
4.3038880588e-02, // time = 8.79 ns
4.3062936541e-02, // time = 8.80 ns
4.3086745303e-02, // time = 8.81 ns
4.3110307352e-02, // time = 8.82 ns
4.3133623171e-02, // time = 8.83 ns
4.3156693242e-02, // time = 8.84 ns
4.3179518051e-02, // time = 8.85 ns
4.3202098085e-02, // time = 8.86 ns
4.3224433832e-02, // time = 8.87 ns
4.3246525782e-02, // time = 8.88 ns
4.3268374428e-02, // time = 8.89 ns
4.3289980264e-02, // time = 8.90 ns
4.3311343785e-02, // time = 8.91 ns
4.3332465488e-02, // time = 8.92 ns
4.3353345872e-02, // time = 8.93 ns
4.3373985438e-02, // time = 8.94 ns
4.3394384688e-02, // time = 8.95 ns
4.3414544124e-02, // time = 8.96 ns
4.3434464253e-02, // time = 8.97 ns
4.3454145581e-02, // time = 8.98 ns
4.3473588617e-02, // time = 8.99 ns
4.3492793869e-02, // time = 9.00 ns
4.3511761849e-02, // time = 9.01 ns
4.3530493070e-02, // time = 9.02 ns
4.3548988046e-02, // time = 9.03 ns
4.3567247292e-02, // time = 9.04 ns
4.3585271325e-02, // time = 9.05 ns
4.3603060663e-02, // time = 9.06 ns
4.3620615826e-02, // time = 9.07 ns
4.3637937335e-02, // time = 9.08 ns
4.3655025711e-02, // time = 9.09 ns
4.3671881478e-02, // time = 9.10 ns
4.3688505162e-02, // time = 9.11 ns
4.3704897287e-02, // time = 9.12 ns
4.3721058381e-02, // time = 9.13 ns
4.3736988972e-02, // time = 9.14 ns
4.3752689590e-02, // time = 9.15 ns
4.3768160766e-02, // time = 9.16 ns
4.3783403030e-02, // time = 9.17 ns
4.3798416918e-02, // time = 9.18 ns
4.3813202961e-02, // time = 9.19 ns
4.3827761696e-02, // time = 9.20 ns
4.3842093659e-02, // time = 9.21 ns
4.3856199386e-02, // time = 9.22 ns
4.3870079417e-02, // time = 9.23 ns
4.3883734290e-02, // time = 9.24 ns
4.3897164545e-02, // time = 9.25 ns
4.3910370724e-02, // time = 9.26 ns
4.3923353370e-02, // time = 9.27 ns
4.3936113024e-02, // time = 9.28 ns
4.3948650231e-02, // time = 9.29 ns
4.3960965536e-02, // time = 9.30 ns
4.3973059484e-02, // time = 9.31 ns
4.3984932623e-02, // time = 9.32 ns
4.3996585499e-02, // time = 9.33 ns
4.4008018661e-02, // time = 9.34 ns
4.4019232657e-02, // time = 9.35 ns
4.4030228038e-02, // time = 9.36 ns
4.4041005354e-02, // time = 9.37 ns
4.4051565157e-02, // time = 9.38 ns
4.4061907998e-02, // time = 9.39 ns
4.4072034430e-02, // time = 9.40 ns
4.4081945006e-02, // time = 9.41 ns
4.4091640281e-02, // time = 9.42 ns
4.4101120809e-02, // time = 9.43 ns
4.4110387146e-02, // time = 9.44 ns
4.4119439848e-02, // time = 9.45 ns
4.4128279471e-02, // time = 9.46 ns
4.4136906572e-02, // time = 9.47 ns
4.4145321709e-02, // time = 9.48 ns
4.4153525441e-02, // time = 9.49 ns
4.4161518326e-02, // time = 9.50 ns
4.4169300924e-02, // time = 9.51 ns
4.4176873794e-02, // time = 9.52 ns
4.4184237498e-02, // time = 9.53 ns
4.4191392594e-02, // time = 9.54 ns
4.4198339646e-02, // time = 9.55 ns
4.4205079215e-02, // time = 9.56 ns
4.4211611862e-02, // time = 9.57 ns
4.4217938150e-02, // time = 9.58 ns
4.4224058643e-02, // time = 9.59 ns
4.4229973903e-02, // time = 9.60 ns
4.4235684494e-02, // time = 9.61 ns
4.4241190981e-02, // time = 9.62 ns
4.4246493927e-02, // time = 9.63 ns
4.4251593898e-02, // time = 9.64 ns
4.4256491458e-02, // time = 9.65 ns
4.4261187173e-02, // time = 9.66 ns
4.4265681608e-02, // time = 9.67 ns
4.4269975329e-02, // time = 9.68 ns
4.4274068903e-02, // time = 9.69 ns
4.4277962895e-02, // time = 9.70 ns
4.4281657872e-02, // time = 9.71 ns
4.4285154401e-02, // time = 9.72 ns
4.4288453049e-02, // time = 9.73 ns
4.4291554383e-02, // time = 9.74 ns
4.4294458970e-02, // time = 9.75 ns
4.4297167378e-02, // time = 9.76 ns
4.4299680174e-02, // time = 9.77 ns
4.4301997927e-02, // time = 9.78 ns
4.4304121204e-02, // time = 9.79 ns
4.4306050573e-02, // time = 9.80 ns
4.4307786602e-02, // time = 9.81 ns
4.4309329860e-02, // time = 9.82 ns
4.4310680914e-02, // time = 9.83 ns
4.4311840333e-02, // time = 9.84 ns
4.4312808686e-02, // time = 9.85 ns
4.4313586540e-02, // time = 9.86 ns
4.4314174465e-02, // time = 9.87 ns
4.4314573028e-02, // time = 9.88 ns
4.4314782799e-02, // time = 9.89 ns
4.4314804345e-02, // time = 9.90 ns
4.4314638236e-02, // time = 9.91 ns
4.4314285039e-02, // time = 9.92 ns
4.4313745323e-02, // time = 9.93 ns
4.4313019656e-02, // time = 9.94 ns
4.4312108607e-02, // time = 9.95 ns
4.4311012744e-02, // time = 9.96 ns
4.4309732634e-02, // time = 9.97 ns
4.4308268847e-02, // time = 9.98 ns
4.4306943489e-02, // time = 9.99 ns
4.4305497338e-02, // time = 10.00 ns
4.4304148409e-02, // time = 10.01 ns
4.4302503963e-02, // time = 10.02 ns
4.4300287188e-02, // time = 10.03 ns
4.4297890382e-02, // time = 10.04 ns
4.4295313621e-02, // time = 10.05 ns
4.4292557310e-02, // time = 10.06 ns
4.4289621962e-02, // time = 10.07 ns
4.4286508124e-02, // time = 10.08 ns
4.4283216357e-02, // time = 10.09 ns
4.4279747225e-02, // time = 10.10 ns
4.4276101295e-02, // time = 10.11 ns
4.4272279131e-02, // time = 10.12 ns
4.4268281299e-02, // time = 10.13 ns
4.4264108366e-02, // time = 10.14 ns
4.4259760895e-02, // time = 10.15 ns
4.4255239453e-02, // time = 10.16 ns
4.4250544605e-02, // time = 10.17 ns
4.4245676914e-02, // time = 10.18 ns
4.4240636946e-02, // time = 10.19 ns
4.4235425264e-02, // time = 10.20 ns
4.4230042432e-02, // time = 10.21 ns
4.4224489014e-02, // time = 10.22 ns
4.4218765573e-02, // time = 10.23 ns
4.4212872672e-02, // time = 10.24 ns
4.4206810874e-02, // time = 10.25 ns
4.4200580741e-02, // time = 10.26 ns
4.4194182835e-02, // time = 10.27 ns
4.4187617718e-02, // time = 10.28 ns
4.4180885951e-02, // time = 10.29 ns
4.4173988094e-02, // time = 10.30 ns
4.4166924710e-02, // time = 10.31 ns
4.4159696357e-02, // time = 10.32 ns
4.4152303597e-02, // time = 10.33 ns
4.4144746988e-02, // time = 10.34 ns
4.4137027089e-02, // time = 10.35 ns
4.4129144460e-02, // time = 10.36 ns
4.4121099658e-02, // time = 10.37 ns
4.4112893242e-02, // time = 10.38 ns
4.4104525770e-02, // time = 10.39 ns
4.4095997798e-02, // time = 10.40 ns
4.4087309883e-02, // time = 10.41 ns
4.4078462582e-02, // time = 10.42 ns
4.4069456450e-02, // time = 10.43 ns
4.4060292043e-02, // time = 10.44 ns
4.4050969916e-02, // time = 10.45 ns
4.4041490624e-02, // time = 10.46 ns
4.4031854720e-02, // time = 10.47 ns
4.4022062757e-02, // time = 10.48 ns
4.4012115291e-02, // time = 10.49 ns
4.4002012872e-02, // time = 10.50 ns
4.3991756053e-02, // time = 10.51 ns
4.3981345386e-02, // time = 10.52 ns
4.3970781422e-02, // time = 10.53 ns
4.3960064712e-02, // time = 10.54 ns
4.3949195806e-02, // time = 10.55 ns
4.3938175253e-02, // time = 10.56 ns
4.3927003603e-02, // time = 10.57 ns
4.3915681405e-02, // time = 10.58 ns
4.3904209206e-02, // time = 10.59 ns
4.3892587554e-02, // time = 10.60 ns
4.3880816996e-02, // time = 10.61 ns
4.3868898079e-02, // time = 10.62 ns
4.3856831349e-02, // time = 10.63 ns
4.3844617351e-02, // time = 10.64 ns
4.3832256629e-02, // time = 10.65 ns
4.3819749728e-02, // time = 10.66 ns
4.3807097193e-02, // time = 10.67 ns
4.3794299565e-02, // time = 10.68 ns
4.3781357387e-02, // time = 10.69 ns
4.3768271201e-02, // time = 10.70 ns
4.3755041549e-02, // time = 10.71 ns
4.3741668971e-02, // time = 10.72 ns
4.3728154008e-02, // time = 10.73 ns
4.3714497198e-02, // time = 10.74 ns
4.3700699081e-02, // time = 10.75 ns
4.3686760195e-02, // time = 10.76 ns
4.3672681077e-02, // time = 10.77 ns
4.3658462266e-02, // time = 10.78 ns
4.3644104296e-02, // time = 10.79 ns
4.3629607703e-02, // time = 10.80 ns
4.3614973023e-02, // time = 10.81 ns
4.3600200791e-02, // time = 10.82 ns
4.3585291539e-02, // time = 10.83 ns
4.3570245801e-02, // time = 10.84 ns
4.3555064109e-02, // time = 10.85 ns
4.3539746996e-02, // time = 10.86 ns
4.3524294991e-02, // time = 10.87 ns
4.3508708626e-02, // time = 10.88 ns
4.3492988430e-02, // time = 10.89 ns
4.3477134932e-02, // time = 10.90 ns
4.3461148660e-02, // time = 10.91 ns
4.3445030142e-02, // time = 10.92 ns
4.3428779906e-02, // time = 10.93 ns
4.3412398476e-02, // time = 10.94 ns
4.3395886379e-02, // time = 10.95 ns
4.3379244138e-02, // time = 10.96 ns
4.3362472279e-02, // time = 10.97 ns
4.3345571325e-02, // time = 10.98 ns
4.3328541797e-02, // time = 10.99 ns
4.3311384218e-02, // time = 11.00 ns
4.3294099109e-02, // time = 11.01 ns
4.3276686989e-02, // time = 11.02 ns
4.3259148379e-02, // time = 11.03 ns
4.3241483798e-02, // time = 11.04 ns
4.3223693763e-02, // time = 11.05 ns
4.3205778791e-02, // time = 11.06 ns
4.3187739400e-02, // time = 11.07 ns
4.3169576104e-02, // time = 11.08 ns
4.3151289419e-02, // time = 11.09 ns
4.3132879858e-02, // time = 11.10 ns
4.3114347936e-02, // time = 11.11 ns
4.3095694164e-02, // time = 11.12 ns
4.3076919054e-02, // time = 11.13 ns
4.3058023118e-02, // time = 11.14 ns
4.3039006865e-02, // time = 11.15 ns
4.3019870805e-02, // time = 11.16 ns
4.3000615446e-02, // time = 11.17 ns
4.2981241296e-02, // time = 11.18 ns
4.2961748862e-02, // time = 11.19 ns
4.2942138650e-02, // time = 11.20 ns
4.2922411165e-02, // time = 11.21 ns
4.2902566911e-02, // time = 11.22 ns
4.2882606392e-02, // time = 11.23 ns
4.2862530111e-02, // time = 11.24 ns
4.2842338570e-02, // time = 11.25 ns
4.2822032269e-02, // time = 11.26 ns
4.2801611709e-02, // time = 11.27 ns
4.2781077388e-02, // time = 11.28 ns
4.2760429806e-02, // time = 11.29 ns
4.2739669461e-02, // time = 11.30 ns
4.2718796848e-02, // time = 11.31 ns
4.2697812463e-02, // time = 11.32 ns
4.2676716802e-02, // time = 11.33 ns
4.2655510359e-02, // time = 11.34 ns
4.2634193627e-02, // time = 11.35 ns
4.2612767097e-02, // time = 11.36 ns
4.2591231263e-02, // time = 11.37 ns
4.2569586614e-02, // time = 11.38 ns
4.2547833639e-02, // time = 11.39 ns
4.2525972829e-02, // time = 11.40 ns
4.2504004669e-02, // time = 11.41 ns
4.2481929649e-02, // time = 11.42 ns
4.2459748252e-02, // time = 11.43 ns
4.2437460966e-02, // time = 11.44 ns
4.2415068273e-02, // time = 11.45 ns
4.2392570658e-02, // time = 11.46 ns
4.2369968603e-02, // time = 11.47 ns
4.2347262589e-02, // time = 11.48 ns
4.2324453096e-02, // time = 11.49 ns
4.2301540605e-02, // time = 11.50 ns
4.2278525595e-02, // time = 11.51 ns
4.2255408542e-02, // time = 11.52 ns
4.2232189924e-02, // time = 11.53 ns
4.2208870217e-02, // time = 11.54 ns
4.2185449896e-02, // time = 11.55 ns
4.2161929435e-02, // time = 11.56 ns
4.2138309306e-02, // time = 11.57 ns
4.2114589983e-02, // time = 11.58 ns
4.2090771936e-02, // time = 11.59 ns
4.2066855636e-02, // time = 11.60 ns
4.2042841552e-02, // time = 11.61 ns
4.2018730152e-02, // time = 11.62 ns
4.1994521904e-02, // time = 11.63 ns
4.1970217275e-02, // time = 11.64 ns
4.1945816729e-02, // time = 11.65 ns
4.1921320731e-02, // time = 11.66 ns
4.1896729746e-02, // time = 11.67 ns
4.1872044235e-02, // time = 11.68 ns
4.1847264660e-02, // time = 11.69 ns
4.1822391482e-02, // time = 11.70 ns
4.1797425160e-02, // time = 11.71 ns
4.1772366154e-02, // time = 11.72 ns
4.1747214921e-02, // time = 11.73 ns
4.1721971918e-02, // time = 11.74 ns
4.1696637600e-02, // time = 11.75 ns
4.1671212423e-02, // time = 11.76 ns
4.1645696840e-02, // time = 11.77 ns
4.1620091304e-02, // time = 11.78 ns
4.1594396268e-02, // time = 11.79 ns
4.1568612181e-02, // time = 11.80 ns
4.1542739495e-02, // time = 11.81 ns
4.1516778657e-02, // time = 11.82 ns
4.1490730116e-02, // time = 11.83 ns
4.1464594319e-02, // time = 11.84 ns
4.1438371711e-02, // time = 11.85 ns
4.1412062738e-02, // time = 11.86 ns
4.1385667844e-02, // time = 11.87 ns
4.1359187471e-02, // time = 11.88 ns
4.1332622061e-02, // time = 11.89 ns
4.1305972056e-02, // time = 11.90 ns
4.1279237896e-02, // time = 11.91 ns
4.1252420019e-02, // time = 11.92 ns
4.1225518863e-02, // time = 11.93 ns
4.1198534866e-02, // time = 11.94 ns
4.1171468463e-02, // time = 11.95 ns
4.1144320090e-02, // time = 11.96 ns
4.1117090179e-02, // time = 11.97 ns
4.1089779165e-02, // time = 11.98 ns
4.1062387479e-02, // time = 11.99 ns
4.1034915552e-02, // time = 12.00 ns
4.1007363814e-02, // time = 12.01 ns
4.0979732694e-02, // time = 12.02 ns
4.0952022619e-02, // time = 12.03 ns
4.0924234018e-02, // time = 12.04 ns
4.0896367315e-02, // time = 12.05 ns
4.0868422935e-02, // time = 12.06 ns
4.0840401303e-02, // time = 12.07 ns
4.0812302841e-02, // time = 12.08 ns
4.0784127970e-02, // time = 12.09 ns
4.0755877113e-02, // time = 12.10 ns
4.0727550688e-02, // time = 12.11 ns
4.0699149114e-02, // time = 12.12 ns
4.0670672810e-02, // time = 12.13 ns
4.0642122192e-02, // time = 12.14 ns
4.0613497675e-02, // time = 12.15 ns
4.0584799674e-02, // time = 12.16 ns
4.0556028603e-02, // time = 12.17 ns
4.0527184875e-02, // time = 12.18 ns
4.0498268902e-02, // time = 12.19 ns
4.0469281093e-02, // time = 12.20 ns
4.0440221859e-02, // time = 12.21 ns
4.0411091608e-02, // time = 12.22 ns
4.0381890748e-02, // time = 12.23 ns
4.0352619685e-02, // time = 12.24 ns
4.0323278825e-02, // time = 12.25 ns
4.0293868572e-02, // time = 12.26 ns
4.0264389331e-02, // time = 12.27 ns
4.0234841502e-02, // time = 12.28 ns
4.0205225489e-02, // time = 12.29 ns
4.0175541690e-02, // time = 12.30 ns
4.0145790507e-02, // time = 12.31 ns
4.0115972336e-02, // time = 12.32 ns
4.0086087576e-02, // time = 12.33 ns
4.0056136622e-02, // time = 12.34 ns
4.0026119871e-02, // time = 12.35 ns
3.9996037716e-02, // time = 12.36 ns
3.9965890550e-02, // time = 12.37 ns
3.9935678767e-02, // time = 12.38 ns
3.9905402756e-02, // time = 12.39 ns
3.9875062909e-02, // time = 12.40 ns
3.9844659615e-02, // time = 12.41 ns
3.9814193261e-02, // time = 12.42 ns
3.9783664235e-02, // time = 12.43 ns
3.9753072924e-02, // time = 12.44 ns
3.9722419711e-02, // time = 12.45 ns
3.9691704982e-02, // time = 12.46 ns
3.9660929118e-02, // time = 12.47 ns
3.9630092504e-02, // time = 12.48 ns
3.9599195518e-02, // time = 12.49 ns
3.9568238542e-02, // time = 12.50 ns
3.9537221954e-02, // time = 12.51 ns
3.9506146133e-02, // time = 12.52 ns
3.9475011455e-02, // time = 12.53 ns
3.9443818296e-02, // time = 12.54 ns
3.9412567031e-02, // time = 12.55 ns
3.9381258034e-02, // time = 12.56 ns
3.9349891678e-02, // time = 12.57 ns
3.9318468335e-02, // time = 12.58 ns
3.9286988375e-02, // time = 12.59 ns
3.9255452169e-02, // time = 12.60 ns
3.9223860085e-02, // time = 12.61 ns
3.9192212491e-02, // time = 12.62 ns
3.9160509754e-02, // time = 12.63 ns
3.9128752239e-02, // time = 12.64 ns
3.9096940311e-02, // time = 12.65 ns
3.9065074334e-02, // time = 12.66 ns
3.9033154671e-02, // time = 12.67 ns
3.9001181684e-02, // time = 12.68 ns
3.8969155732e-02, // time = 12.69 ns
3.8937077176e-02, // time = 12.70 ns
3.8904946374e-02, // time = 12.71 ns
3.8872763685e-02, // time = 12.72 ns
3.8840529464e-02, // time = 12.73 ns
3.8808244067e-02, // time = 12.74 ns
3.8775907849e-02, // time = 12.75 ns
3.8743521164e-02, // time = 12.76 ns
3.8711084363e-02, // time = 12.77 ns
3.8678597799e-02, // time = 12.78 ns
3.8646061823e-02, // time = 12.79 ns
3.8613476783e-02, // time = 12.80 ns
3.8580843028e-02, // time = 12.81 ns
3.8548160906e-02, // time = 12.82 ns
3.8515430764e-02, // time = 12.83 ns
3.8482652946e-02, // time = 12.84 ns
3.8449827798e-02, // time = 12.85 ns
3.8416955663e-02, // time = 12.86 ns
3.8384036883e-02, // time = 12.87 ns
3.8351071800e-02, // time = 12.88 ns
3.8318060755e-02, // time = 12.89 ns
3.8285004087e-02, // time = 12.90 ns
3.8251902134e-02, // time = 12.91 ns
3.8218755234e-02, // time = 12.92 ns
3.8185563724e-02, // time = 12.93 ns
3.8152327939e-02, // time = 12.94 ns
3.8119048214e-02, // time = 12.95 ns
3.8085724881e-02, // time = 12.96 ns
3.8052358274e-02, // time = 12.97 ns
3.8018948725e-02, // time = 12.98 ns
3.7985496563e-02, // time = 12.99 ns
3.7952002118e-02, // time = 13.00 ns
3.7918465719e-02, // time = 13.01 ns
3.7884887693e-02, // time = 13.02 ns
3.7851268367e-02, // time = 13.03 ns
3.7817608066e-02, // time = 13.04 ns
3.7783907116e-02, // time = 13.05 ns
3.7750165838e-02, // time = 13.06 ns
3.7716384557e-02, // time = 13.07 ns
3.7682563594e-02, // time = 13.08 ns
3.7648703269e-02, // time = 13.09 ns
3.7614803902e-02, // time = 13.10 ns
3.7580865812e-02, // time = 13.11 ns
3.7546889316e-02, // time = 13.12 ns
3.7512874731e-02, // time = 13.13 ns
3.7478822373e-02, // time = 13.14 ns
3.7444732556e-02, // time = 13.15 ns
3.7410605595e-02, // time = 13.16 ns
3.7376441801e-02, // time = 13.17 ns
3.7342241487e-02, // time = 13.18 ns
3.7308004963e-02, // time = 13.19 ns
3.7273732540e-02, // time = 13.20 ns
3.7239424526e-02, // time = 13.21 ns
3.7205081229e-02, // time = 13.22 ns
3.7170702956e-02, // time = 13.23 ns
3.7136290012e-02, // time = 13.24 ns
3.7101842704e-02, // time = 13.25 ns
3.7067361334e-02, // time = 13.26 ns
3.7032846206e-02, // time = 13.27 ns
3.6998297622e-02, // time = 13.28 ns
3.6963715882e-02, // time = 13.29 ns
3.6929101288e-02, // time = 13.30 ns
3.6894454138e-02, // time = 13.31 ns
3.6859774731e-02, // time = 13.32 ns
3.6825063363e-02, // time = 13.33 ns
3.6790320330e-02, // time = 13.34 ns
3.6755545929e-02, // time = 13.35 ns
3.6720740454e-02, // time = 13.36 ns
3.6685904197e-02, // time = 13.37 ns
3.6651037451e-02, // time = 13.38 ns
3.6616140509e-02, // time = 13.39 ns
3.6581213659e-02, // time = 13.40 ns
3.6546257192e-02, // time = 13.41 ns
3.6511271397e-02, // time = 13.42 ns
3.6476256561e-02, // time = 13.43 ns
3.6441212970e-02, // time = 13.44 ns
3.6406140911e-02, // time = 13.45 ns
3.6371040669e-02, // time = 13.46 ns
3.6335912526e-02, // time = 13.47 ns
3.6300756767e-02, // time = 13.48 ns
3.6265573673e-02, // time = 13.49 ns
3.6230363524e-02, // time = 13.50 ns
3.6195126602e-02, // time = 13.51 ns
3.6159863185e-02, // time = 13.52 ns
3.6124573552e-02, // time = 13.53 ns
3.6089257979e-02, // time = 13.54 ns
3.6053916744e-02, // time = 13.55 ns
3.6018550121e-02, // time = 13.56 ns
3.5983158385e-02, // time = 13.57 ns
3.5947741810e-02, // time = 13.58 ns
3.5912300667e-02, // time = 13.59 ns
3.5876835230e-02, // time = 13.60 ns
3.5841345767e-02, // time = 13.61 ns
3.5805832551e-02, // time = 13.62 ns
3.5770295848e-02, // time = 13.63 ns
3.5734735927e-02, // time = 13.64 ns
3.5699153056e-02, // time = 13.65 ns
3.5663547500e-02, // time = 13.66 ns
3.5627919525e-02, // time = 13.67 ns
3.5592269394e-02, // time = 13.68 ns
3.5556597371e-02, // time = 13.69 ns
3.5520903719e-02, // time = 13.70 ns
3.5485188699e-02, // time = 13.71 ns
3.5449452572e-02, // time = 13.72 ns
3.5413695597e-02, // time = 13.73 ns
3.5377918034e-02, // time = 13.74 ns
3.5342120139e-02, // time = 13.75 ns
3.5306302171e-02, // time = 13.76 ns
3.5270464385e-02, // time = 13.77 ns
3.5234607036e-02, // time = 13.78 ns
3.5198730378e-02, // time = 13.79 ns
3.5162834666e-02, // time = 13.80 ns
3.5126920151e-02, // time = 13.81 ns
3.5090987085e-02, // time = 13.82 ns
3.5055035719e-02, // time = 13.83 ns
3.5019066302e-02, // time = 13.84 ns
3.4983079083e-02, // time = 13.85 ns
3.4947074311e-02, // time = 13.86 ns
3.4911052232e-02, // time = 13.87 ns
3.4875013092e-02, // time = 13.88 ns
3.4838957138e-02, // time = 13.89 ns
3.4802884612e-02, // time = 13.90 ns
3.4766795760e-02, // time = 13.91 ns
3.4730690823e-02, // time = 13.92 ns
3.4694570043e-02, // time = 13.93 ns
3.4658433662e-02, // time = 13.94 ns
3.4622281919e-02, // time = 13.95 ns
3.4586115053e-02, // time = 13.96 ns
3.4549933302e-02, // time = 13.97 ns
3.4513736905e-02, // time = 13.98 ns
3.4477526097e-02, // time = 13.99 ns
3.4441301115e-02, // time = 14.00 ns
3.4405062192e-02, // time = 14.01 ns
3.4368809563e-02, // time = 14.02 ns
3.4332543462e-02, // time = 14.03 ns
3.4296264119e-02, // time = 14.04 ns
3.4259971766e-02, // time = 14.05 ns
3.4223666635e-02, // time = 14.06 ns
3.4187348954e-02, // time = 14.07 ns
3.4151018952e-02, // time = 14.08 ns
3.4114676857e-02, // time = 14.09 ns
3.4078322897e-02, // time = 14.10 ns
3.4041957297e-02, // time = 14.11 ns
3.4005580282e-02, // time = 14.12 ns
3.3969192077e-02, // time = 14.13 ns
3.3932792906e-02, // time = 14.14 ns
3.3896382992e-02, // time = 14.15 ns
3.3859962556e-02, // time = 14.16 ns
3.3823531819e-02, // time = 14.17 ns
3.3787091003e-02, // time = 14.18 ns
3.3750640325e-02, // time = 14.19 ns
3.3714180005e-02, // time = 14.20 ns
3.3677710261e-02, // time = 14.21 ns
3.3641231309e-02, // time = 14.22 ns
3.3604743366e-02, // time = 14.23 ns
3.3568246646e-02, // time = 14.24 ns
3.3531741364e-02, // time = 14.25 ns
3.3495227734e-02, // time = 14.26 ns
3.3458705968e-02, // time = 14.27 ns
3.3422176279e-02, // time = 14.28 ns
3.3385638877e-02, // time = 14.29 ns
3.3349093973e-02, // time = 14.30 ns
3.3312541776e-02, // time = 14.31 ns
3.3275982494e-02, // time = 14.32 ns
3.3239416337e-02, // time = 14.33 ns
3.3202843510e-02, // time = 14.34 ns
3.3166264219e-02, // time = 14.35 ns
3.3129678671e-02, // time = 14.36 ns
3.3093087070e-02, // time = 14.37 ns
3.3056489620e-02, // time = 14.38 ns
3.3019886522e-02, // time = 14.39 ns
3.2983277981e-02, // time = 14.40 ns
3.2946664197e-02, // time = 14.41 ns
3.2910045370e-02, // time = 14.42 ns
3.2873421700e-02, // time = 14.43 ns
3.2836793387e-02, // time = 14.44 ns
3.2800160628e-02, // time = 14.45 ns
3.2763523621e-02, // time = 14.46 ns
3.2726882563e-02, // time = 14.47 ns
3.2690237648e-02, // time = 14.48 ns
3.2653589073e-02, // time = 14.49 ns
3.2616937031e-02, // time = 14.50 ns
3.2580281716e-02, // time = 14.51 ns
3.2543623320e-02, // time = 14.52 ns
3.2506962036e-02, // time = 14.53 ns
3.2470298054e-02, // time = 14.54 ns
3.2433631564e-02, // time = 14.55 ns
3.2396962757e-02, // time = 14.56 ns
3.2360291820e-02, // time = 14.57 ns
3.2323618943e-02, // time = 14.58 ns
3.2286944311e-02, // time = 14.59 ns
3.2250268112e-02, // time = 14.60 ns
3.2213590531e-02, // time = 14.61 ns
3.2176911753e-02, // time = 14.62 ns
3.2140231962e-02, // time = 14.63 ns
3.2103551342e-02, // time = 14.64 ns
3.2066870075e-02, // time = 14.65 ns
3.2030188342e-02, // time = 14.66 ns
3.1993506326e-02, // time = 14.67 ns
3.1956824206e-02, // time = 14.68 ns
3.1920142162e-02, // time = 14.69 ns
3.1883460373e-02, // time = 14.70 ns
3.1846779017e-02, // time = 14.71 ns
3.1810098270e-02, // time = 14.72 ns
3.1773418311e-02, // time = 14.73 ns
3.1736739314e-02, // time = 14.74 ns
3.1700061454e-02, // time = 14.75 ns
3.1663384907e-02, // time = 14.76 ns
3.1626709845e-02, // time = 14.77 ns
3.1590036441e-02, // time = 14.78 ns
3.1553364868e-02, // time = 14.79 ns
3.1516695297e-02, // time = 14.80 ns
3.1480027899e-02, // time = 14.81 ns
3.1443362843e-02, // time = 14.82 ns
3.1406700299e-02, // time = 14.83 ns
3.1370040435e-02, // time = 14.84 ns
3.1333383418e-02, // time = 14.85 ns
3.1296729417e-02, // time = 14.86 ns
3.1260078597e-02, // time = 14.87 ns
3.1223431124e-02, // time = 14.88 ns
3.1186787162e-02, // time = 14.89 ns
3.1150146876e-02, // time = 14.90 ns
3.1113510429e-02, // time = 14.91 ns
3.1076877984e-02, // time = 14.92 ns
3.1040249703e-02, // time = 14.93 ns
3.1003625747e-02, // time = 14.94 ns
3.0967006277e-02, // time = 14.95 ns
3.0930391453e-02, // time = 14.96 ns
3.0893781433e-02, // time = 14.97 ns
3.0857176376e-02, // time = 14.98 ns
3.0820576440e-02, // time = 14.99 ns
3.0783981783e-02, // time = 15.00 ns
3.0747392559e-02, // time = 15.01 ns
3.0710808926e-02, // time = 15.02 ns
3.0674231037e-02, // time = 15.03 ns
3.0637659048e-02, // time = 15.04 ns
3.0601093112e-02, // time = 15.05 ns
3.0564533381e-02, // time = 15.06 ns
3.0527980008e-02, // time = 15.07 ns
3.0491433145e-02, // time = 15.08 ns
3.0454892941e-02, // time = 15.09 ns
3.0418359549e-02, // time = 15.10 ns
3.0381833116e-02, // time = 15.11 ns
3.0345313791e-02, // time = 15.12 ns
3.0308801723e-02, // time = 15.13 ns
3.0272297060e-02, // time = 15.14 ns
3.0235799947e-02, // time = 15.15 ns
3.0199310532e-02, // time = 15.16 ns
3.0162828958e-02, // time = 15.17 ns
3.0126355372e-02, // time = 15.18 ns
3.0089889918e-02, // time = 15.19 ns
3.0053432737e-02, // time = 15.20 ns
3.0016983975e-02, // time = 15.21 ns
2.9980543771e-02, // time = 15.22 ns
2.9944112269e-02, // time = 15.23 ns
2.9907689608e-02, // time = 15.24 ns
2.9871275929e-02, // time = 15.25 ns
2.9834871372e-02, // time = 15.26 ns
2.9798476074e-02, // time = 15.27 ns
2.9762090175e-02, // time = 15.28 ns
2.9725713811e-02, // time = 15.29 ns
2.9689347120e-02, // time = 15.30 ns
2.9652990237e-02, // time = 15.31 ns
2.9616643299e-02, // time = 15.32 ns
2.9580306441e-02, // time = 15.33 ns
2.9543979795e-02, // time = 15.34 ns
2.9507663497e-02, // time = 15.35 ns
2.9471357680e-02, // time = 15.36 ns
2.9435062474e-02, // time = 15.37 ns
2.9398778013e-02, // time = 15.38 ns
2.9362504428e-02, // time = 15.39 ns
2.9326241848e-02, // time = 15.40 ns
2.9289990404e-02, // time = 15.41 ns
2.9253750225e-02, // time = 15.42 ns
2.9217521439e-02, // time = 15.43 ns
2.9181304175e-02, // time = 15.44 ns
2.9145098560e-02, // time = 15.45 ns
2.9108904720e-02, // time = 15.46 ns
2.9072722782e-02, // time = 15.47 ns
2.9036552871e-02, // time = 15.48 ns
2.9000395112e-02, // time = 15.49 ns
2.8964249629e-02, // time = 15.50 ns
2.8928116546e-02, // time = 15.51 ns
2.8891995986e-02, // time = 15.52 ns
2.8855888071e-02, // time = 15.53 ns
2.8819792924e-02, // time = 15.54 ns
2.8783710665e-02, // time = 15.55 ns
2.8747641415e-02, // time = 15.56 ns
2.8711585294e-02, // time = 15.57 ns
2.8675542421e-02, // time = 15.58 ns
2.8639512916e-02, // time = 15.59 ns
2.8603496896e-02, // time = 15.60 ns
2.8567494479e-02, // time = 15.61 ns
2.8531505783e-02, // time = 15.62 ns
2.8495530923e-02, // time = 15.63 ns
2.8459570015e-02, // time = 15.64 ns
2.8423623175e-02, // time = 15.65 ns
2.8387690517e-02, // time = 15.66 ns
2.8351772156e-02, // time = 15.67 ns
2.8315868205e-02, // time = 15.68 ns
2.8279978776e-02, // time = 15.69 ns
2.8244103983e-02, // time = 15.70 ns
2.8208243937e-02, // time = 15.71 ns
2.8172398749e-02, // time = 15.72 ns
2.8136568529e-02, // time = 15.73 ns
2.8100753389e-02, // time = 15.74 ns
2.8064953436e-02, // time = 15.75 ns
2.8029168781e-02, // time = 15.76 ns
2.7993399532e-02, // time = 15.77 ns
2.7957645795e-02, // time = 15.78 ns
2.7921907680e-02, // time = 15.79 ns
2.7886185291e-02, // time = 15.80 ns
2.7850478736e-02, // time = 15.81 ns
2.7814788119e-02, // time = 15.82 ns
2.7779113546e-02, // time = 15.83 ns
2.7743455121e-02, // time = 15.84 ns
2.7707812948e-02, // time = 15.85 ns
2.7672187131e-02, // time = 15.86 ns
2.7636577771e-02, // time = 15.87 ns
2.7600984972e-02, // time = 15.88 ns
2.7565408834e-02, // time = 15.89 ns
2.7529849459e-02, // time = 15.90 ns
2.7494306948e-02, // time = 15.91 ns
2.7458781401e-02, // time = 15.92 ns
2.7423272916e-02, // time = 15.93 ns
2.7387781594e-02, // time = 15.94 ns
2.7352307532e-02, // time = 15.95 ns
2.7316850828e-02, // time = 15.96 ns
2.7281411579e-02, // time = 15.97 ns
2.7245989883e-02, // time = 15.98 ns
2.7210585836e-02, // time = 15.99 ns
2.7175199533e-02, // time = 16.00 ns
2.7139831069e-02, // time = 16.01 ns
2.7104480540e-02, // time = 16.02 ns
2.7069148038e-02, // time = 16.03 ns
2.7033833659e-02, // time = 16.04 ns
2.6998537495e-02, // time = 16.05 ns
2.6963259639e-02, // time = 16.06 ns
2.6928000183e-02, // time = 16.07 ns
2.6892759217e-02, // time = 16.08 ns
2.6857536834e-02, // time = 16.09 ns
2.6822333124e-02, // time = 16.10 ns
2.6787148177e-02, // time = 16.11 ns
2.6751982082e-02, // time = 16.12 ns
2.6716834929e-02, // time = 16.13 ns
2.6681706805e-02, // time = 16.14 ns
2.6646597800e-02, // time = 16.15 ns
2.6611507999e-02, // time = 16.16 ns
2.6576437491e-02, // time = 16.17 ns
2.6541386361e-02, // time = 16.18 ns
2.6506354697e-02, // time = 16.19 ns
2.6471342582e-02, // time = 16.20 ns
2.6436350103e-02, // time = 16.21 ns
2.6401377343e-02, // time = 16.22 ns
2.6366424387e-02, // time = 16.23 ns
2.6331491317e-02, // time = 16.24 ns
2.6296578219e-02, // time = 16.25 ns
2.6261685172e-02, // time = 16.26 ns
2.6226812261e-02, // time = 16.27 ns
2.6191959565e-02, // time = 16.28 ns
2.6157127167e-02, // time = 16.29 ns
2.6122315147e-02, // time = 16.30 ns
2.6087523585e-02, // time = 16.31 ns
2.6052752560e-02, // time = 16.32 ns
2.6018002152e-02, // time = 16.33 ns
2.5983272440e-02, // time = 16.34 ns
2.5948563501e-02, // time = 16.35 ns
2.5913875413e-02, // time = 16.36 ns
2.5879208254e-02, // time = 16.37 ns
2.5844562101e-02, // time = 16.38 ns
2.5809937029e-02, // time = 16.39 ns
2.5775333114e-02, // time = 16.40 ns
2.5740750433e-02, // time = 16.41 ns
2.5706189059e-02, // time = 16.42 ns
2.5671649067e-02, // time = 16.43 ns
2.5637130532e-02, // time = 16.44 ns
2.5602633527e-02, // time = 16.45 ns
2.5568158124e-02, // time = 16.46 ns
2.5533704397e-02, // time = 16.47 ns
2.5499272418e-02, // time = 16.48 ns
2.5464862258e-02, // time = 16.49 ns
2.5430473988e-02, // time = 16.50 ns
2.5396107680e-02, // time = 16.51 ns
2.5361763404e-02, // time = 16.52 ns
2.5327441230e-02, // time = 16.53 ns
2.5293141227e-02, // time = 16.54 ns
2.5258863464e-02, // time = 16.55 ns
2.5224608010e-02, // time = 16.56 ns
2.5190374933e-02, // time = 16.57 ns
2.5156164300e-02, // time = 16.58 ns
2.5121976180e-02, // time = 16.59 ns
2.5087810638e-02, // time = 16.60 ns
2.5053667742e-02, // time = 16.61 ns
2.5019547556e-02, // time = 16.62 ns
2.4985450147e-02, // time = 16.63 ns
2.4951375580e-02, // time = 16.64 ns
2.4917323920e-02, // time = 16.65 ns
2.4883295230e-02, // time = 16.66 ns
2.4849289575e-02, // time = 16.67 ns
2.4815307017e-02, // time = 16.68 ns
2.4781347621e-02, // time = 16.69 ns
2.4747411447e-02, // time = 16.70 ns
2.4713498560e-02, // time = 16.71 ns
2.4679609019e-02, // time = 16.72 ns
2.4645742887e-02, // time = 16.73 ns
2.4611900225e-02, // time = 16.74 ns
2.4578081092e-02, // time = 16.75 ns
2.4544285550e-02, // time = 16.76 ns
2.4510513657e-02, // time = 16.77 ns
2.4476765472e-02, // time = 16.78 ns
2.4443041055e-02, // time = 16.79 ns
2.4409340465e-02, // time = 16.80 ns
2.4375663758e-02, // time = 16.81 ns
2.4342010993e-02, // time = 16.82 ns
2.4308382226e-02, // time = 16.83 ns
2.4274777516e-02, // time = 16.84 ns
2.4241196917e-02, // time = 16.85 ns
2.4207640486e-02, // time = 16.86 ns
2.4174108279e-02, // time = 16.87 ns
2.4140600351e-02, // time = 16.88 ns
2.4107116756e-02, // time = 16.89 ns
2.4073657549e-02, // time = 16.90 ns
2.4040222784e-02, // time = 16.91 ns
2.4006812515e-02, // time = 16.92 ns
2.3973426795e-02, // time = 16.93 ns
2.3940065676e-02, // time = 16.94 ns
2.3906729212e-02, // time = 16.95 ns
2.3873417454e-02, // time = 16.96 ns
2.3840130454e-02, // time = 16.97 ns
2.3806868263e-02, // time = 16.98 ns
2.3773630933e-02, // time = 16.99 ns
2.3740418513e-02, // time = 17.00 ns
2.3707231054e-02, // time = 17.01 ns
2.3674068607e-02, // time = 17.02 ns
2.3640931219e-02, // time = 17.03 ns
2.3607818940e-02, // time = 17.04 ns
2.3574731820e-02, // time = 17.05 ns
2.3541669906e-02, // time = 17.06 ns
2.3508633246e-02, // time = 17.07 ns
2.3475621887e-02, // time = 17.08 ns
2.3442635878e-02, // time = 17.09 ns
2.3409675265e-02, // time = 17.10 ns
2.3376740093e-02, // time = 17.11 ns
2.3343830411e-02, // time = 17.12 ns
2.3310946262e-02, // time = 17.13 ns
2.3278087693e-02, // time = 17.14 ns
2.3245254748e-02, // time = 17.15 ns
2.3212447473e-02, // time = 17.16 ns
2.3179665911e-02, // time = 17.17 ns
2.3146910106e-02, // time = 17.18 ns
2.3114180103e-02, // time = 17.19 ns
2.3081475944e-02, // time = 17.20 ns
2.3048797672e-02, // time = 17.21 ns
2.3016145330e-02, // time = 17.22 ns
2.2983518960e-02, // time = 17.23 ns
2.2950918604e-02, // time = 17.24 ns
2.2918344303e-02, // time = 17.25 ns
2.2885796099e-02, // time = 17.26 ns
2.2853274032e-02, // time = 17.27 ns
2.2820778143e-02, // time = 17.28 ns
2.2788308472e-02, // time = 17.29 ns
2.2755865059e-02, // time = 17.30 ns
2.2723447942e-02, // time = 17.31 ns
2.2691057162e-02, // time = 17.32 ns
2.2658692758e-02, // time = 17.33 ns
2.2626354766e-02, // time = 17.34 ns
2.2594043227e-02, // time = 17.35 ns
2.2561758177e-02, // time = 17.36 ns
2.2529499654e-02, // time = 17.37 ns
2.2497267694e-02, // time = 17.38 ns
2.2465062336e-02, // time = 17.39 ns
2.2432883615e-02, // time = 17.40 ns
2.2400731568e-02, // time = 17.41 ns
2.2368606229e-02, // time = 17.42 ns
2.2336507636e-02, // time = 17.43 ns
2.2304435822e-02, // time = 17.44 ns
2.2272390824e-02, // time = 17.45 ns
2.2240372674e-02, // time = 17.46 ns
2.2208381409e-02, // time = 17.47 ns
2.2176417060e-02, // time = 17.48 ns
2.2144479663e-02, // time = 17.49 ns
2.2112569250e-02, // time = 17.50 ns
2.2080685854e-02, // time = 17.51 ns
2.2048829508e-02, // time = 17.52 ns
2.2017000244e-02, // time = 17.53 ns
2.1985198095e-02, // time = 17.54 ns
2.1953423092e-02, // time = 17.55 ns
2.1921675266e-02, // time = 17.56 ns
2.1889954648e-02, // time = 17.57 ns
2.1858261270e-02, // time = 17.58 ns
2.1826595161e-02, // time = 17.59 ns
2.1794956353e-02, // time = 17.60 ns
2.1763344874e-02, // time = 17.61 ns
2.1731760755e-02, // time = 17.62 ns
2.1700204024e-02, // time = 17.63 ns
2.1668674712e-02, // time = 17.64 ns
2.1637172845e-02, // time = 17.65 ns
2.1605698454e-02, // time = 17.66 ns
2.1574251565e-02, // time = 17.67 ns
2.1542832207e-02, // time = 17.68 ns
2.1511440407e-02, // time = 17.69 ns
2.1480076193e-02, // time = 17.70 ns
2.1448739591e-02, // time = 17.71 ns
2.1417430629e-02, // time = 17.72 ns
2.1386149332e-02, // time = 17.73 ns
2.1354895726e-02, // time = 17.74 ns
2.1323669837e-02, // time = 17.75 ns
2.1292471692e-02, // time = 17.76 ns
2.1261301314e-02, // time = 17.77 ns
2.1230158730e-02, // time = 17.78 ns
2.1199043963e-02, // time = 17.79 ns
2.1167957038e-02, // time = 17.80 ns
2.1136897980e-02, // time = 17.81 ns
2.1105866811e-02, // time = 17.82 ns
2.1074863556e-02, // time = 17.83 ns
2.1043888238e-02, // time = 17.84 ns
2.1012940879e-02, // time = 17.85 ns
2.0982021504e-02, // time = 17.86 ns
2.0951130133e-02, // time = 17.87 ns
2.0920266789e-02, // time = 17.88 ns
2.0889431495e-02, // time = 17.89 ns
2.0858624271e-02, // time = 17.90 ns
2.0827845140e-02, // time = 17.91 ns
2.0797094122e-02, // time = 17.92 ns
2.0766371238e-02, // time = 17.93 ns
2.0735676509e-02, // time = 17.94 ns
2.0705009956e-02, // time = 17.95 ns
2.0674371597e-02, // time = 17.96 ns
2.0643761453e-02, // time = 17.97 ns
2.0613179544e-02, // time = 17.98 ns
2.0582625889e-02, // time = 17.99 ns
2.0552100507e-02, // time = 18.00 ns
2.0521603416e-02, // time = 18.01 ns
2.0491134636e-02, // time = 18.02 ns
2.0460694184e-02, // time = 18.03 ns
2.0430282079e-02, // time = 18.04 ns
2.0399898337e-02, // time = 18.05 ns
2.0369542978e-02, // time = 18.06 ns
2.0339216018e-02, // time = 18.07 ns
2.0308917474e-02, // time = 18.08 ns
2.0278647362e-02, // time = 18.09 ns
2.0248405701e-02, // time = 18.10 ns
2.0218192504e-02, // time = 18.11 ns
2.0188007790e-02, // time = 18.12 ns
2.0157851573e-02, // time = 18.13 ns
2.0127723869e-02, // time = 18.14 ns
2.0097624693e-02, // time = 18.15 ns
2.0067554061e-02, // time = 18.16 ns
2.0037511987e-02, // time = 18.17 ns
2.0007498486e-02, // time = 18.18 ns
1.9977513572e-02, // time = 18.19 ns
1.9947557260e-02, // time = 18.20 ns
1.9917629563e-02, // time = 18.21 ns
1.9887730494e-02, // time = 18.22 ns
1.9857860068e-02, // time = 18.23 ns
1.9828018298e-02, // time = 18.24 ns
1.9798205196e-02, // time = 18.25 ns
1.9768420775e-02, // time = 18.26 ns
1.9738665047e-02, // time = 18.27 ns
1.9708938026e-02, // time = 18.28 ns
1.9679239723e-02, // time = 18.29 ns
1.9649570149e-02, // time = 18.30 ns
1.9619929317e-02, // time = 18.31 ns
1.9590317237e-02, // time = 18.32 ns
1.9560733922e-02, // time = 18.33 ns
1.9531179381e-02, // time = 18.34 ns
1.9501653626e-02, // time = 18.35 ns
1.9472156666e-02, // time = 18.36 ns
1.9442688514e-02, // time = 18.37 ns
1.9413249177e-02, // time = 18.38 ns
1.9383838666e-02, // time = 18.39 ns
1.9354456992e-02, // time = 18.40 ns
1.9325104162e-02, // time = 18.41 ns
1.9295780187e-02, // time = 18.42 ns
1.9266485075e-02, // time = 18.43 ns
1.9237218835e-02, // time = 18.44 ns
1.9207981475e-02, // time = 18.45 ns
1.9178773005e-02, // time = 18.46 ns
1.9149593432e-02, // time = 18.47 ns
1.9120442763e-02, // time = 18.48 ns
1.9091321007e-02, // time = 18.49 ns
1.9062228172e-02, // time = 18.50 ns
1.9033164264e-02, // time = 18.51 ns
1.9004129290e-02, // time = 18.52 ns
1.8975123258e-02, // time = 18.53 ns
1.8946146174e-02, // time = 18.54 ns
1.8917198045e-02, // time = 18.55 ns
1.8888278877e-02, // time = 18.56 ns
1.8859388676e-02, // time = 18.57 ns
1.8830527447e-02, // time = 18.58 ns
1.8801695197e-02, // time = 18.59 ns
1.8772891932e-02, // time = 18.60 ns
1.8744117655e-02, // time = 18.61 ns
1.8715372373e-02, // time = 18.62 ns
1.8686656090e-02, // time = 18.63 ns
1.8657968812e-02, // time = 18.64 ns
1.8629310542e-02, // time = 18.65 ns
1.8600681285e-02, // time = 18.66 ns
1.8572081045e-02, // time = 18.67 ns
1.8543509826e-02, // time = 18.68 ns
1.8514967631e-02, // time = 18.69 ns
1.8486454465e-02, // time = 18.70 ns
1.8457970331e-02, // time = 18.71 ns
1.8429515231e-02, // time = 18.72 ns
1.8401089169e-02, // time = 18.73 ns
1.8372692148e-02, // time = 18.74 ns
1.8344324170e-02, // time = 18.75 ns
1.8315985238e-02, // time = 18.76 ns
1.8287675354e-02, // time = 18.77 ns
1.8259394521e-02, // time = 18.78 ns
1.8231142739e-02, // time = 18.79 ns
1.8202920011e-02, // time = 18.80 ns
1.8174726338e-02, // time = 18.81 ns
1.8146561722e-02, // time = 18.82 ns
1.8118426164e-02, // time = 18.83 ns
1.8090319665e-02, // time = 18.84 ns
1.8062242226e-02, // time = 18.85 ns
1.8034193847e-02, // time = 18.86 ns
1.8006174529e-02, // time = 18.87 ns
1.7978184272e-02, // time = 18.88 ns
1.7950223077e-02, // time = 18.89 ns
1.7922290943e-02, // time = 18.90 ns
1.7894387870e-02, // time = 18.91 ns
1.7866513858e-02, // time = 18.92 ns
1.7838668907e-02, // time = 18.93 ns
1.7810853015e-02, // time = 18.94 ns
1.7783066182e-02, // time = 18.95 ns
1.7755308406e-02, // time = 18.96 ns
1.7727579687e-02, // time = 18.97 ns
1.7699880024e-02, // time = 18.98 ns
1.7672209414e-02, // time = 18.99 ns
1.7644567856e-02, // time = 19.00 ns
1.7616955348e-02, // time = 19.01 ns
1.7589371888e-02, // time = 19.02 ns
1.7561817474e-02, // time = 19.03 ns
1.7534292104e-02, // time = 19.04 ns
1.7506795775e-02, // time = 19.05 ns
1.7479328485e-02, // time = 19.06 ns
1.7451890230e-02, // time = 19.07 ns
1.7424481009e-02, // time = 19.08 ns
1.7397100816e-02, // time = 19.09 ns
1.7369749651e-02, // time = 19.10 ns
1.7342427508e-02, // time = 19.11 ns
1.7315134385e-02, // time = 19.12 ns
1.7287870277e-02, // time = 19.13 ns
1.7260635181e-02, // time = 19.14 ns
1.7233429093e-02, // time = 19.15 ns
1.7206252009e-02, // time = 19.16 ns
1.7179103924e-02, // time = 19.17 ns
1.7151984833e-02, // time = 19.18 ns
1.7124894733e-02, // time = 19.19 ns
1.7097833619e-02, // time = 19.20 ns
1.7070801485e-02, // time = 19.21 ns
1.7043798326e-02, // time = 19.22 ns
1.7016824138e-02, // time = 19.23 ns
1.6989878914e-02, // time = 19.24 ns
1.6962962650e-02, // time = 19.25 ns
1.6936075340e-02, // time = 19.26 ns
1.6909216978e-02, // time = 19.27 ns
1.6882387558e-02, // time = 19.28 ns
1.6855587073e-02, // time = 19.29 ns
1.6828815519e-02, // time = 19.30 ns
1.6802072889e-02, // time = 19.31 ns
1.6775359175e-02, // time = 19.32 ns
1.6748674372e-02, // time = 19.33 ns
1.6722018473e-02, // time = 19.34 ns
1.6695391470e-02, // time = 19.35 ns
1.6668793357e-02, // time = 19.36 ns
1.6642224127e-02, // time = 19.37 ns
1.6615683772e-02, // time = 19.38 ns
1.6589172286e-02, // time = 19.39 ns
1.6562689660e-02, // time = 19.40 ns
1.6536235886e-02, // time = 19.41 ns
1.6509810957e-02, // time = 19.42 ns
1.6483414866e-02, // time = 19.43 ns
1.6457047603e-02, // time = 19.44 ns
1.6430709162e-02, // time = 19.45 ns
1.6404399532e-02, // time = 19.46 ns
1.6378118707e-02, // time = 19.47 ns
1.6351866677e-02, // time = 19.48 ns
1.6325643434e-02, // time = 19.49 ns
1.6299448968e-02, // time = 19.50 ns
1.6273283272e-02, // time = 19.51 ns
1.6247146335e-02, // time = 19.52 ns
1.6221038149e-02, // time = 19.53 ns
1.6194958704e-02, // time = 19.54 ns
1.6168907992e-02, // time = 19.55 ns
1.6142886001e-02, // time = 19.56 ns
1.6116892723e-02, // time = 19.57 ns
1.6090928148e-02, // time = 19.58 ns
1.6064992266e-02, // time = 19.59 ns
1.6039085067e-02, // time = 19.60 ns
1.6013206540e-02, // time = 19.61 ns
1.5987356676e-02, // time = 19.62 ns
1.5961535464e-02, // time = 19.63 ns
1.5935742893e-02, // time = 19.64 ns
1.5909978953e-02, // time = 19.65 ns
1.5884243634e-02, // time = 19.66 ns
1.5858536923e-02, // time = 19.67 ns
1.5832858811e-02, // time = 19.68 ns
1.5807209286e-02, // time = 19.69 ns
1.5781588337e-02, // time = 19.70 ns
1.5755995952e-02, // time = 19.71 ns
1.5730432121e-02, // time = 19.72 ns
1.5704896831e-02, // time = 19.73 ns
1.5679390071e-02, // time = 19.74 ns
1.5653911830e-02, // time = 19.75 ns
1.5628462095e-02, // time = 19.76 ns
1.5603040854e-02, // time = 19.77 ns
1.5577648095e-02, // time = 19.78 ns
1.5552283807e-02, // time = 19.79 ns
1.5526947976e-02, // time = 19.80 ns
1.5501640591e-02, // time = 19.81 ns
1.5476361638e-02, // time = 19.82 ns
1.5451111106e-02, // time = 19.83 ns
1.5425888981e-02, // time = 19.84 ns
1.5400695251e-02, // time = 19.85 ns
1.5375529902e-02, // time = 19.86 ns
1.5350392921e-02, // time = 19.87 ns
1.5325284297e-02, // time = 19.88 ns
1.5300204014e-02, // time = 19.89 ns
1.5275152060e-02, // time = 19.90 ns
1.5250128421e-02, // time = 19.91 ns
1.5225133084e-02, // time = 19.92 ns
1.5200166035e-02, // time = 19.93 ns
1.5175227260e-02, // time = 19.94 ns
1.5150316746e-02, // time = 19.95 ns
1.5125434477e-02, // time = 19.96 ns
1.5100580441e-02, // time = 19.97 ns
1.5075754624e-02, // time = 19.98 ns
1.5050957010e-02, // time = 19.99 ns
1.5016287700e-02, // time = 20.00 ns
1.4998974872e-02, // time = 20.01 ns
1.4979204709e-02, // time = 20.02 ns
1.4954517054e-02, // time = 20.03 ns
1.4929857433e-02, // time = 20.04 ns
1.4905225904e-02, // time = 20.05 ns
1.4880622472e-02, // time = 20.06 ns
1.4856047130e-02, // time = 20.07 ns
1.4831499863e-02, // time = 20.08 ns
1.4806980657e-02, // time = 20.09 ns
1.4770254430e-02, // time = 20.10 ns
1.4745819134e-02, // time = 20.11 ns
1.4721402415e-02, // time = 20.12 ns
1.4697010588e-02, // time = 20.13 ns
1.4672645743e-02, // time = 20.14 ns
1.4648308556e-02, // time = 20.15 ns
1.4623999231e-02, // time = 20.16 ns
1.4599717822e-02, // time = 20.17 ns
1.4575464330e-02, // time = 20.18 ns
1.4551238743e-02, // time = 20.19 ns
1.4527041045e-02, // time = 20.20 ns
1.4502871218e-02, // time = 20.21 ns
1.4478729243e-02, // time = 20.22 ns
1.4454615103e-02, // time = 20.23 ns
1.4430528780e-02, // time = 20.24 ns
1.4406470255e-02, // time = 20.25 ns
1.4382439511e-02, // time = 20.26 ns
1.4358436530e-02, // time = 20.27 ns
1.4334461295e-02, // time = 20.28 ns
1.4310513787e-02, // time = 20.29 ns
1.4286593991e-02, // time = 20.30 ns
1.4262701887e-02, // time = 20.31 ns
1.4238837459e-02, // time = 20.32 ns
1.4215000689e-02, // time = 20.33 ns
1.4191191559e-02, // time = 20.34 ns
1.4167410053e-02, // time = 20.35 ns
1.4143656153e-02, // time = 20.36 ns
1.4119929840e-02, // time = 20.37 ns
1.4096231098e-02, // time = 20.38 ns
1.4072559908e-02, // time = 20.39 ns
1.4048916253e-02, // time = 20.40 ns
1.4025300115e-02, // time = 20.41 ns
1.4001711475e-02, // time = 20.42 ns
1.3978150317e-02, // time = 20.43 ns
1.3954616621e-02, // time = 20.44 ns
1.3931110369e-02, // time = 20.45 ns
1.3907631544e-02, // time = 20.46 ns
1.3884180126e-02, // time = 20.47 ns
1.3860756099e-02, // time = 20.48 ns
1.3837359442e-02, // time = 20.49 ns
1.3813990137e-02, // time = 20.50 ns
1.3790648167e-02, // time = 20.51 ns
1.3767333511e-02, // time = 20.52 ns
1.3744046152e-02, // time = 20.53 ns
1.3720786070e-02, // time = 20.54 ns
1.3697553246e-02, // time = 20.55 ns
1.3674347662e-02, // time = 20.56 ns
1.3651169298e-02, // time = 20.57 ns
1.3628018135e-02, // time = 20.58 ns
1.3604894154e-02, // time = 20.59 ns
1.3581797336e-02, // time = 20.60 ns
1.3558727660e-02, // time = 20.61 ns
1.3535685109e-02, // time = 20.62 ns
1.3512669661e-02, // time = 20.63 ns
1.3489681299e-02, // time = 20.64 ns
1.3466720001e-02, // time = 20.65 ns
1.3443785750e-02, // time = 20.66 ns
1.3420878524e-02, // time = 20.67 ns
1.3397998305e-02, // time = 20.68 ns
1.3375145073e-02, // time = 20.69 ns
1.3352318808e-02, // time = 20.70 ns
1.3329519490e-02, // time = 20.71 ns
1.3306747100e-02, // time = 20.72 ns
1.3284001618e-02, // time = 20.73 ns
1.3261283024e-02, // time = 20.74 ns
1.3238591299e-02, // time = 20.75 ns
1.3215926421e-02, // time = 20.76 ns
1.3193288372e-02, // time = 20.77 ns
1.3170677131e-02, // time = 20.78 ns
1.3148092678e-02, // time = 20.79 ns
1.3125534993e-02, // time = 20.80 ns
1.3103004056e-02, // time = 20.81 ns
1.3080499846e-02, // time = 20.82 ns
1.3058022344e-02, // time = 20.83 ns
1.3035571529e-02, // time = 20.84 ns
1.3013147382e-02, // time = 20.85 ns
1.2990749882e-02, // time = 20.86 ns
1.2968379009e-02, // time = 20.87 ns
1.2946034743e-02, // time = 20.88 ns
1.2923717064e-02, // time = 20.89 ns
1.2901425953e-02, // time = 20.90 ns
1.2879161388e-02, // time = 20.91 ns
1.2856923349e-02, // time = 20.92 ns
1.2834711817e-02, // time = 20.93 ns
1.2812526770e-02, // time = 20.94 ns
1.2790368188e-02, // time = 20.95 ns
1.2768236050e-02, // time = 20.96 ns
1.2746130336e-02, // time = 20.97 ns
1.2724051024e-02, // time = 20.98 ns
1.2701998096e-02, // time = 20.99 ns
1.2679971529e-02, // time = 21.00 ns
1.2657971305e-02, // time = 21.01 ns
1.2635997404e-02, // time = 21.02 ns
1.2614049807e-02, // time = 21.03 ns
1.2592128496e-02, // time = 21.04 ns
1.2570233453e-02, // time = 21.05 ns
1.2548364661e-02, // time = 21.06 ns
1.2526522104e-02, // time = 21.07 ns
1.2504705768e-02, // time = 21.08 ns
1.2482915639e-02, // time = 21.09 ns
1.2461151701e-02, // time = 21.10 ns
1.2439413942e-02, // time = 21.11 ns
1.2417702343e-02, // time = 21.12 ns
1.2396016886e-02, // time = 21.13 ns
1.2374357543e-02, // time = 21.14 ns
1.2352724280e-02, // time = 21.15 ns
1.2331117058e-02, // time = 21.16 ns
1.2309535830e-02, // time = 21.17 ns
1.2287980541e-02, // time = 21.18 ns
1.2266451146e-02, // time = 21.19 ns
1.2244947618e-02, // time = 21.20 ns
1.2223469918e-02, // time = 21.21 ns
1.2202018020e-02, // time = 21.22 ns
1.2180591904e-02, // time = 21.23 ns
1.2159191557e-02, // time = 21.24 ns
1.2137816971e-02, // time = 21.25 ns
1.2116468137e-02, // time = 21.26 ns
1.2095145048e-02, // time = 21.27 ns
1.2073847695e-02, // time = 21.28 ns
1.2052576067e-02, // time = 21.29 ns
1.2031330150e-02, // time = 21.30 ns
1.2010109929e-02, // time = 21.31 ns
1.1988915386e-02, // time = 21.32 ns
1.1967746502e-02, // time = 21.33 ns
1.1946603256e-02, // time = 21.34 ns
1.1925485626e-02, // time = 21.35 ns
1.1904393589e-02, // time = 21.36 ns
1.1883327122e-02, // time = 21.37 ns
1.1862286202e-02, // time = 21.38 ns
1.1841270803e-02, // time = 21.39 ns
1.1820280902e-02, // time = 21.40 ns
1.1799316474e-02, // time = 21.41 ns
1.1778377495e-02, // time = 21.42 ns
1.1757463941e-02, // time = 21.43 ns
1.1736575786e-02, // time = 21.44 ns
1.1715713008e-02, // time = 21.45 ns
1.1694875581e-02, // time = 21.46 ns
1.1674063481e-02, // time = 21.47 ns
1.1653276684e-02, // time = 21.48 ns
1.1632515166e-02, // time = 21.49 ns
1.1611778905e-02, // time = 21.50 ns
1.1591067878e-02, // time = 21.51 ns
1.1570382064e-02, // time = 21.52 ns
1.1549721444e-02, // time = 21.53 ns
1.1529086000e-02, // time = 21.54 ns
1.1508475712e-02, // time = 21.55 ns
1.1487890561e-02, // time = 21.56 ns
1.1467330520e-02, // time = 21.57 ns
1.1446795555e-02, // time = 21.58 ns
1.1426285625e-02, // time = 21.59 ns
1.1405800681e-02, // time = 21.60 ns
1.1385340671e-02, // time = 21.61 ns
1.1364905541e-02, // time = 21.62 ns
1.1344495242e-02, // time = 21.63 ns
1.1324109728e-02, // time = 21.64 ns
1.1303748943e-02, // time = 21.65 ns
1.1283412801e-02, // time = 21.66 ns
1.1263101145e-02, // time = 21.67 ns
1.1242813832e-02, // time = 21.68 ns
1.1222551015e-02, // time = 21.69 ns
1.1202313079e-02, // time = 21.70 ns
1.1182100220e-02, // time = 21.71 ns
1.1161912403e-02, // time = 21.72 ns
1.1141750008e-02, // time = 21.73 ns
1.1121612327e-02, // time = 21.74 ns
1.1101499066e-02, // time = 21.75 ns
1.1081410331e-02, // time = 21.76 ns
1.1067976241e-02, // time = 21.77 ns
1.1044908155e-02, // time = 21.78 ns
1.1028872778e-02, // time = 21.79 ns
1.1008810991e-02, // time = 21.80 ns
1.0984749703e-02, // time = 21.81 ns
1.0965697621e-02, // time = 21.82 ns
1.0949209463e-02, // time = 21.83 ns
1.0927025688e-02, // time = 21.84 ns
1.0903226244e-02, // time = 21.85 ns
1.0882034161e-02, // time = 21.86 ns
1.0871869227e-02, // time = 21.87 ns
1.0844507113e-02, // time = 21.88 ns
1.0824722074e-02, // time = 21.89 ns
1.0805547399e-02, // time = 21.90 ns
1.0786429128e-02, // time = 21.91 ns
1.0766725739e-02, // time = 21.92 ns
1.0747047650e-02, // time = 21.93 ns
1.0727393354e-02, // time = 21.94 ns
1.0707761991e-02, // time = 21.95 ns
1.0688153385e-02, // time = 21.96 ns
1.0668567902e-02, // time = 21.97 ns
1.0649006263e-02, // time = 21.98 ns
1.0629469347e-02, // time = 21.99 ns
1.0609957980e-02, // time = 22.00 ns
1.0590472756e-02, // time = 22.01 ns
1.0571013926e-02, // time = 22.02 ns
1.0551581378e-02, // time = 22.03 ns
1.0532174710e-02, // time = 22.04 ns
1.0512793349e-02, // time = 22.05 ns
1.0493436667e-02, // time = 22.06 ns
1.0474104084e-02, // time = 22.07 ns
1.0454795119e-02, // time = 22.08 ns
1.0435509415e-02, // time = 22.09 ns
1.0416246751e-02, // time = 22.10 ns
1.0397006972e-02, // time = 22.11 ns
1.0377790019e-02, // time = 22.12 ns
1.0358595898e-02, // time = 22.13 ns
1.0339424658e-02, // time = 22.14 ns
1.0320276370e-02, // time = 22.15 ns
1.0301151114e-02, // time = 22.16 ns
1.0282048967e-02, // time = 22.17 ns
1.0262970003e-02, // time = 22.18 ns
1.0243914284e-02, // time = 22.19 ns
1.0224881864e-02, // time = 22.20 ns
1.0205872785e-02, // time = 22.21 ns
1.0186887079e-02, // time = 22.22 ns
1.0167924769e-02, // time = 22.23 ns
1.0148985871e-02, // time = 22.24 ns
1.0130070392e-02, // time = 22.25 ns
1.0111178334e-02, // time = 22.26 ns
1.0092309695e-02, // time = 22.27 ns
1.0073464467e-02, // time = 22.28 ns
1.0054642639e-02, // time = 22.29 ns
1.0035844199e-02, // time = 22.30 ns
1.0017069130e-02, // time = 22.31 ns
9.9983174167e-03, // time = 22.32 ns
9.9795890394e-03, // time = 22.33 ns
9.9608839784e-03, // time = 22.34 ns
9.9422022121e-03, // time = 22.35 ns
9.9235437171e-03, // time = 22.36 ns
9.9049084681e-03, // time = 22.37 ns
9.8862964367e-03, // time = 22.38 ns
9.8677075920e-03, // time = 22.39 ns
9.8491418994e-03, // time = 22.40 ns
9.8305993210e-03, // time = 22.41 ns
9.8120798159e-03, // time = 22.42 ns
9.7935833414e-03, // time = 22.43 ns
9.7751098544e-03, // time = 22.44 ns
9.7566593134e-03, // time = 22.45 ns
9.7382316804e-03, // time = 22.46 ns
9.7198269230e-03, // time = 22.47 ns
9.7014450152e-03, // time = 22.48 ns
9.6830859380e-03, // time = 22.49 ns
9.6647496789e-03, // time = 22.50 ns
9.6464362300e-03, // time = 22.51 ns
9.6281455868e-03, // time = 22.52 ns
9.6098777456e-03, // time = 22.53 ns
9.5916327019e-03, // time = 22.54 ns
9.5734104487e-03, // time = 22.55 ns
9.5552109758e-03, // time = 22.56 ns
9.5370342686e-03, // time = 22.57 ns
9.5188803084e-03, // time = 22.58 ns
9.5007490724e-03, // time = 22.59 ns
9.4826405342e-03, // time = 22.60 ns
9.4645546646e-03, // time = 22.61 ns
9.4464914319e-03, // time = 22.62 ns
9.4284508026e-03, // time = 22.63 ns
9.4104327423e-03, // time = 22.64 ns
9.3924372159e-03, // time = 22.65 ns
9.3744641884e-03, // time = 22.66 ns
9.3565136247e-03, // time = 22.67 ns
9.3385854906e-03, // time = 22.68 ns
9.3206797526e-03, // time = 22.69 ns
9.3027963781e-03, // time = 22.70 ns
9.2849353348e-03, // time = 22.71 ns
9.2670965911e-03, // time = 22.72 ns
9.2492801168e-03, // time = 22.73 ns
9.2314858829e-03, // time = 22.74 ns
9.2137138610e-03, // time = 22.75 ns
9.1959640236e-03, // time = 22.76 ns
9.1782363438e-03, // time = 22.77 ns
9.1605307954e-03, // time = 22.78 ns
9.1428473526e-03, // time = 22.79 ns
9.1251859900e-03, // time = 22.80 ns
9.1075466826e-03, // time = 22.81 ns
9.0899294058e-03, // time = 22.82 ns
9.0723341354e-03, // time = 22.83 ns
9.0547608470e-03, // time = 22.84 ns
9.0372095169e-03, // time = 22.85 ns
9.0196801213e-03, // time = 22.86 ns
9.0021726364e-03, // time = 22.87 ns
8.9846870387e-03, // time = 22.88 ns
8.9672233047e-03, // time = 22.89 ns
8.9497814108e-03, // time = 22.90 ns
8.9323613336e-03, // time = 22.91 ns
8.9149630496e-03, // time = 22.92 ns
8.8975865353e-03, // time = 22.93 ns
8.8802317672e-03, // time = 22.94 ns
8.8628987219e-03, // time = 22.95 ns
8.8455873756e-03, // time = 22.96 ns
8.8282977048e-03, // time = 22.97 ns
8.8110296860e-03, // time = 22.98 ns
8.7937832953e-03, // time = 22.99 ns
8.7765585091e-03, // time = 23.00 ns
8.7593553036e-03, // time = 23.01 ns
8.7421736551e-03, // time = 23.02 ns
8.7250135397e-03, // time = 23.03 ns
8.7078749334e-03, // time = 23.04 ns
8.6907578125e-03, // time = 23.05 ns
8.6736621530e-03, // time = 23.06 ns
8.6565879308e-03, // time = 23.07 ns
8.6395351221e-03, // time = 23.08 ns
8.6225037027e-03, // time = 23.09 ns
8.6054936487e-03, // time = 23.10 ns
8.5885049359e-03, // time = 23.11 ns
8.5715375403e-03, // time = 23.12 ns
8.5545914377e-03, // time = 23.13 ns
8.5376666040e-03, // time = 23.14 ns
8.5207630152e-03, // time = 23.15 ns
8.5038806469e-03, // time = 23.16 ns
8.4870194752e-03, // time = 23.17 ns
8.4701794758e-03, // time = 23.18 ns
8.4533606245e-03, // time = 23.19 ns
8.4365628971e-03, // time = 23.20 ns
8.4197862696e-03, // time = 23.21 ns
8.4030307176e-03, // time = 23.22 ns
8.3862962170e-03, // time = 23.23 ns
8.3695827437e-03, // time = 23.24 ns
8.3528902733e-03, // time = 23.25 ns
8.3362187818e-03, // time = 23.26 ns
8.3195682449e-03, // time = 23.27 ns
8.3029386385e-03, // time = 23.28 ns
8.2863299383e-03, // time = 23.29 ns
8.2697421203e-03, // time = 23.30 ns
8.2531751601e-03, // time = 23.31 ns
8.2366290337e-03, // time = 23.32 ns
8.2201037168e-03, // time = 23.33 ns
8.2035991854e-03, // time = 23.34 ns
8.1871154152e-03, // time = 23.35 ns
8.1706523822e-03, // time = 23.36 ns
8.1542100621e-03, // time = 23.37 ns
8.1377884308e-03, // time = 23.38 ns
8.1213874642e-03, // time = 23.39 ns
8.1050071382e-03, // time = 23.40 ns
8.0886474287e-03, // time = 23.41 ns
8.0723083115e-03, // time = 23.42 ns
8.0559897626e-03, // time = 23.43 ns
8.0396917578e-03, // time = 23.44 ns
8.0234142731e-03, // time = 23.45 ns
8.0071572844e-03, // time = 23.46 ns
7.9909207676e-03, // time = 23.47 ns
7.9747046987e-03, // time = 23.48 ns
7.9585090536e-03, // time = 23.49 ns
7.9423338083e-03, // time = 23.50 ns
7.9261789387e-03, // time = 23.51 ns
7.9100444208e-03, // time = 23.52 ns
7.8939302306e-03, // time = 23.53 ns
7.8778363441e-03, // time = 23.54 ns
7.8617627373e-03, // time = 23.55 ns
7.8457093862e-03, // time = 23.56 ns
7.8296762667e-03, // time = 23.57 ns
7.8136633551e-03, // time = 23.58 ns
7.7976706272e-03, // time = 23.59 ns
7.7816980591e-03, // time = 23.60 ns
7.7657456269e-03, // time = 23.61 ns
7.7498133066e-03, // time = 23.62 ns
7.7339010744e-03, // time = 23.63 ns
7.7180089063e-03, // time = 23.64 ns
7.7021367784e-03, // time = 23.65 ns
7.6862846668e-03, // time = 23.66 ns
7.6704525476e-03, // time = 23.67 ns
7.6546403970e-03, // time = 23.68 ns
7.6388481911e-03, // time = 23.69 ns
7.6230759060e-03, // time = 23.70 ns
7.6073235179e-03, // time = 23.71 ns
7.5915910030e-03, // time = 23.72 ns
7.5758783374e-03, // time = 23.73 ns
7.5601854974e-03, // time = 23.74 ns
7.5445124591e-03, // time = 23.75 ns
7.5288591988e-03, // time = 23.76 ns
7.5132256926e-03, // time = 23.77 ns
7.4976119169e-03, // time = 23.78 ns
7.4820178478e-03, // time = 23.79 ns
7.4664434616e-03, // time = 23.80 ns
7.4508887347e-03, // time = 23.81 ns
7.4353536432e-03, // time = 23.82 ns
7.4198381635e-03, // time = 23.83 ns
7.4043422719e-03, // time = 23.84 ns
7.3888659447e-03, // time = 23.85 ns
7.3734091582e-03, // time = 23.86 ns
7.3579718887e-03, // time = 23.87 ns
7.3425541127e-03, // time = 23.88 ns
7.3271558065e-03, // time = 23.89 ns
7.3117769465e-03, // time = 23.90 ns
7.2964175091e-03, // time = 23.91 ns
7.2810774706e-03, // time = 23.92 ns
7.2657568076e-03, // time = 23.93 ns
7.2504554963e-03, // time = 23.94 ns
7.2351735134e-03, // time = 23.95 ns
7.2199108352e-03, // time = 23.96 ns
7.2046674382e-03, // time = 23.97 ns
7.1894432989e-03, // time = 23.98 ns
7.1742383938e-03, // time = 23.99 ns
7.1590526994e-03, // time = 24.00 ns
7.1438861923e-03, // time = 24.01 ns
7.1287388489e-03, // time = 24.02 ns
7.1136106459e-03, // time = 24.03 ns
7.0985015598e-03, // time = 24.04 ns
7.0834115671e-03, // time = 24.05 ns
7.0683406446e-03, // time = 24.06 ns
7.0532887688e-03, // time = 24.07 ns
7.0382559163e-03, // time = 24.08 ns
7.0232420637e-03, // time = 24.09 ns
7.0082471878e-03, // time = 24.10 ns
6.9932712652e-03, // time = 24.11 ns
6.9783142726e-03, // time = 24.12 ns
6.9633761866e-03, // time = 24.13 ns
6.9484569841e-03, // time = 24.14 ns
6.9335566417e-03, // time = 24.15 ns
6.9186751362e-03, // time = 24.16 ns
6.9038124443e-03, // time = 24.17 ns
6.8889685429e-03, // time = 24.18 ns
6.8741434087e-03, // time = 24.19 ns
6.8593370185e-03, // time = 24.20 ns
6.8445493491e-03, // time = 24.21 ns
6.8297803775e-03, // time = 24.22 ns
6.8150300804e-03, // time = 24.23 ns
6.8002984347e-03, // time = 24.24 ns
6.7855854173e-03, // time = 24.25 ns
6.7708910052e-03, // time = 24.26 ns
6.7562151752e-03, // time = 24.27 ns
6.7415579042e-03, // time = 24.28 ns
6.7269191693e-03, // time = 24.29 ns
6.7122989475e-03, // time = 24.30 ns
6.6976972156e-03, // time = 24.31 ns
6.6831139507e-03, // time = 24.32 ns
6.6685491299e-03, // time = 24.33 ns
6.6540027302e-03, // time = 24.34 ns
6.6394747286e-03, // time = 24.35 ns
6.6249651022e-03, // time = 24.36 ns
6.6104738281e-03, // time = 24.37 ns
6.5960008834e-03, // time = 24.38 ns
6.5815462453e-03, // time = 24.39 ns
6.5671098908e-03, // time = 24.40 ns
6.5526917973e-03, // time = 24.41 ns
6.5382919418e-03, // time = 24.42 ns
6.5239103015e-03, // time = 24.43 ns
6.5095468537e-03, // time = 24.44 ns
6.4952015756e-03, // time = 24.45 ns
6.4808744445e-03, // time = 24.46 ns
6.4665654376e-03, // time = 24.47 ns
6.4522745323e-03, // time = 24.48 ns
6.4380017058e-03, // time = 24.49 ns
6.4237469356e-03, // time = 24.50 ns
6.4095101989e-03, // time = 24.51 ns
6.3952914730e-03, // time = 24.52 ns
6.3810907356e-03, // time = 24.53 ns
6.3669079638e-03, // time = 24.54 ns
6.3527431352e-03, // time = 24.55 ns
6.3385962272e-03, // time = 24.56 ns
6.3244672172e-03, // time = 24.57 ns
6.3103560829e-03, // time = 24.58 ns
6.2962628016e-03, // time = 24.59 ns
6.2821873509e-03, // time = 24.60 ns
6.2681297084e-03, // time = 24.61 ns
6.2540898516e-03, // time = 24.62 ns
6.2400677581e-03, // time = 24.63 ns
6.2260634056e-03, // time = 24.64 ns
6.2120767717e-03, // time = 24.65 ns
6.1981078340e-03, // time = 24.66 ns
6.1841565702e-03, // time = 24.67 ns
6.1702229580e-03, // time = 24.68 ns
6.1563069751e-03, // time = 24.69 ns
6.1424085993e-03, // time = 24.70 ns
6.1285278083e-03, // time = 24.71 ns
6.1146645799e-03, // time = 24.72 ns
6.1008188919e-03, // time = 24.73 ns
6.0869907222e-03, // time = 24.74 ns
6.0731800485e-03, // time = 24.75 ns
6.0593868488e-03, // time = 24.76 ns
6.0456111009e-03, // time = 24.77 ns
6.0318527828e-03, // time = 24.78 ns
6.0181118724e-03, // time = 24.79 ns
6.0043883476e-03, // time = 24.80 ns
5.9906821865e-03, // time = 24.81 ns
5.9769933670e-03, // time = 24.82 ns
5.9633218671e-03, // time = 24.83 ns
5.9496676650e-03, // time = 24.84 ns
5.9360307386e-03, // time = 24.85 ns
5.9224110660e-03, // time = 24.86 ns
5.9088086254e-03, // time = 24.87 ns
5.8952233950e-03, // time = 24.88 ns
5.8816553528e-03, // time = 24.89 ns
5.8681044770e-03, // time = 24.90 ns
5.8545707460e-03, // time = 24.91 ns
5.8410541378e-03, // time = 24.92 ns
5.8275546307e-03, // time = 24.93 ns
5.8140722031e-03, // time = 24.94 ns
5.8006068331e-03, // time = 24.95 ns
5.7871584992e-03, // time = 24.96 ns
5.7737271797e-03, // time = 24.97 ns
5.7603128529e-03, // time = 24.98 ns
5.7469154972e-03, // time = 24.99 ns
5.7335350911e-03, // time = 25.00 ns
5.7201716130e-03, // time = 25.01 ns
5.7068250413e-03, // time = 25.02 ns
5.6934953545e-03, // time = 25.03 ns
5.6801825312e-03, // time = 25.04 ns
5.6668865498e-03, // time = 25.05 ns
5.6536073889e-03, // time = 25.06 ns
5.6403450271e-03, // time = 25.07 ns
5.6270994430e-03, // time = 25.08 ns
5.6138706153e-03, // time = 25.09 ns
5.6006585225e-03, // time = 25.10 ns
5.5874631433e-03, // time = 25.11 ns
5.5742844565e-03, // time = 25.12 ns
5.5611224407e-03, // time = 25.13 ns
5.5479770747e-03, // time = 25.14 ns
5.5348483372e-03, // time = 25.15 ns
5.5217362071e-03, // time = 25.16 ns
5.5086406632e-03, // time = 25.17 ns
5.4955616842e-03, // time = 25.18 ns
5.4824992491e-03, // time = 25.19 ns
5.4694533368e-03, // time = 25.20 ns
5.4564239261e-03, // time = 25.21 ns
5.4434109959e-03, // time = 25.22 ns
5.4304145253e-03, // time = 25.23 ns
5.4174344933e-03, // time = 25.24 ns
5.4044708787e-03, // time = 25.25 ns
5.3915236606e-03, // time = 25.26 ns
5.3785928182e-03, // time = 25.27 ns
5.3656783304e-03, // time = 25.28 ns
5.3527801763e-03, // time = 25.29 ns
5.3398983352e-03, // time = 25.30 ns
5.3270327860e-03, // time = 25.31 ns
5.3141835080e-03, // time = 25.32 ns
5.3013504804e-03, // time = 25.33 ns
5.2885336824e-03, // time = 25.34 ns
5.2757330932e-03, // time = 25.35 ns
5.2629486920e-03, // time = 25.36 ns
5.2501804583e-03, // time = 25.37 ns
5.2374283712e-03, // time = 25.38 ns
5.2246924101e-03, // time = 25.39 ns
5.2119725543e-03, // time = 25.40 ns
5.1992687833e-03, // time = 25.41 ns
5.1865810764e-03, // time = 25.42 ns
5.1739094130e-03, // time = 25.43 ns
5.1612537727e-03, // time = 25.44 ns
5.1486141348e-03, // time = 25.45 ns
5.1359904788e-03, // time = 25.46 ns
5.1233827843e-03, // time = 25.47 ns
5.1107910309e-03, // time = 25.48 ns
5.0982151979e-03, // time = 25.49 ns
5.0856552652e-03, // time = 25.50 ns
5.0731112122e-03, // time = 25.51 ns
5.0605830185e-03, // time = 25.52 ns
5.0480706640e-03, // time = 25.53 ns
5.0355741281e-03, // time = 25.54 ns
5.0230933906e-03, // time = 25.55 ns
5.0106284313e-03, // time = 25.56 ns
4.9981792298e-03, // time = 25.57 ns
4.9857457660e-03, // time = 25.58 ns
4.9733280196e-03, // time = 25.59 ns
4.9609259704e-03, // time = 25.60 ns
4.9485395983e-03, // time = 25.61 ns
4.9361688832e-03, // time = 25.62 ns
4.9238138048e-03, // time = 25.63 ns
4.9114743431e-03, // time = 25.64 ns
4.8991504781e-03, // time = 25.65 ns
4.8868421897e-03, // time = 25.66 ns
4.8745494578e-03, // time = 25.67 ns
4.8622722624e-03, // time = 25.68 ns
4.8500105836e-03, // time = 25.69 ns
4.8377644013e-03, // time = 25.70 ns
4.8255336957e-03, // time = 25.71 ns
4.8133184469e-03, // time = 25.72 ns
4.8011186348e-03, // time = 25.73 ns
4.7889342397e-03, // time = 25.74 ns
4.7767652417e-03, // time = 25.75 ns
4.7646116209e-03, // time = 25.76 ns
4.7524733577e-03, // time = 25.77 ns
4.7403504320e-03, // time = 25.78 ns
4.7282428243e-03, // time = 25.79 ns
4.7161505147e-03, // time = 25.80 ns
4.7040734836e-03, // time = 25.81 ns
4.6920117112e-03, // time = 25.82 ns
4.6799651779e-03, // time = 25.83 ns
4.6679338640e-03, // time = 25.84 ns
4.6559177499e-03, // time = 25.85 ns
4.6439168160e-03, // time = 25.86 ns
4.6319310426e-03, // time = 25.87 ns
4.6199604102e-03, // time = 25.88 ns
4.6080048993e-03, // time = 25.89 ns
4.5960644903e-03, // time = 25.90 ns
4.5841391638e-03, // time = 25.91 ns
4.5722289003e-03, // time = 25.92 ns
4.5603336802e-03, // time = 25.93 ns
4.5484534842e-03, // time = 25.94 ns
4.5365882929e-03, // time = 25.95 ns
4.5247380869e-03, // time = 25.96 ns
4.5129028467e-03, // time = 25.97 ns
4.5010825531e-03, // time = 25.98 ns
4.4892771867e-03, // time = 25.99 ns
4.4774867283e-03, // time = 26.00 ns
4.4657111584e-03, // time = 26.01 ns
4.4539504580e-03, // time = 26.02 ns
4.4422046077e-03, // time = 26.03 ns
4.4304735883e-03, // time = 26.04 ns
4.4187573807e-03, // time = 26.05 ns
4.4070559656e-03, // time = 26.06 ns
4.3953693239e-03, // time = 26.07 ns
4.3836974365e-03, // time = 26.08 ns
4.3720402843e-03, // time = 26.09 ns
4.3603978482e-03, // time = 26.10 ns
4.3487701091e-03, // time = 26.11 ns
4.3371570479e-03, // time = 26.12 ns
4.3255586458e-03, // time = 26.13 ns
4.3139748836e-03, // time = 26.14 ns
4.3024057424e-03, // time = 26.15 ns
4.2908512033e-03, // time = 26.16 ns
4.2793112472e-03, // time = 26.17 ns
4.2677858554e-03, // time = 26.18 ns
4.2562750088e-03, // time = 26.19 ns
4.2447786888e-03, // time = 26.20 ns
4.2332968763e-03, // time = 26.21 ns
4.2218295526e-03, // time = 26.22 ns
4.2103766990e-03, // time = 26.23 ns
4.1989382965e-03, // time = 26.24 ns
4.1875143265e-03, // time = 26.25 ns
4.1761047702e-03, // time = 26.26 ns
4.1647096089e-03, // time = 26.27 ns
4.1533288239e-03, // time = 26.28 ns
4.1419623967e-03, // time = 26.29 ns
4.1306103084e-03, // time = 26.30 ns
4.1192725405e-03, // time = 26.31 ns
4.1079490745e-03, // time = 26.32 ns
4.0966398916e-03, // time = 26.33 ns
4.0853449735e-03, // time = 26.34 ns
4.0740643014e-03, // time = 26.35 ns
4.0627978570e-03, // time = 26.36 ns
4.0515456217e-03, // time = 26.37 ns
4.0403075772e-03, // time = 26.38 ns
4.0290837048e-03, // time = 26.39 ns
4.0178739863e-03, // time = 26.40 ns
4.0066784031e-03, // time = 26.41 ns
3.9954969370e-03, // time = 26.42 ns
3.9843295696e-03, // time = 26.43 ns
3.9731762826e-03, // time = 26.44 ns
3.9620370576e-03, // time = 26.45 ns
3.9509118764e-03, // time = 26.46 ns
3.9398007206e-03, // time = 26.47 ns
3.9287035722e-03, // time = 26.48 ns
3.9176204128e-03, // time = 26.49 ns
3.9065512242e-03, // time = 26.50 ns
3.8954959883e-03, // time = 26.51 ns
3.8844546869e-03, // time = 26.52 ns
3.8734273020e-03, // time = 26.53 ns
3.8624138153e-03, // time = 26.54 ns
3.8514142089e-03, // time = 26.55 ns
3.8404284646e-03, // time = 26.56 ns
3.8294565644e-03, // time = 26.57 ns
3.8184984903e-03, // time = 26.58 ns
3.8075542244e-03, // time = 26.59 ns
3.7966237486e-03, // time = 26.60 ns
3.7857070450e-03, // time = 26.61 ns
3.7748040957e-03, // time = 26.62 ns
3.7639148828e-03, // time = 26.63 ns
3.7530393883e-03, // time = 26.64 ns
3.7421775946e-03, // time = 26.65 ns
3.7313294836e-03, // time = 26.66 ns
3.7204950377e-03, // time = 26.67 ns
3.7096742390e-03, // time = 26.68 ns
3.6988670698e-03, // time = 26.69 ns
3.6880735123e-03, // time = 26.70 ns
3.6772935488e-03, // time = 26.71 ns
3.6665271616e-03, // time = 26.72 ns
3.6557743331e-03, // time = 26.73 ns
3.6450350456e-03, // time = 26.74 ns
3.6343092815e-03, // time = 26.75 ns
3.6235970231e-03, // time = 26.76 ns
3.6128982529e-03, // time = 26.77 ns
3.6022129534e-03, // time = 26.78 ns
3.5915411070e-03, // time = 26.79 ns
3.5808826962e-03, // time = 26.80 ns
3.5702377035e-03, // time = 26.81 ns
3.5596061114e-03, // time = 26.82 ns
3.5489879026e-03, // time = 26.83 ns
3.5383830595e-03, // time = 26.84 ns
3.5277915649e-03, // time = 26.85 ns
3.5172134012e-03, // time = 26.86 ns
3.5066485513e-03, // time = 26.87 ns
3.4960969977e-03, // time = 26.88 ns
3.4855587231e-03, // time = 26.89 ns
3.4750337104e-03, // time = 26.90 ns
3.4645219421e-03, // time = 26.91 ns
3.4540234011e-03, // time = 26.92 ns
3.4435380702e-03, // time = 26.93 ns
3.4330659321e-03, // time = 26.94 ns
3.4226069698e-03, // time = 26.95 ns
3.4121611661e-03, // time = 26.96 ns
3.4017285038e-03, // time = 26.97 ns
3.3913089659e-03, // time = 26.98 ns
3.3809025352e-03, // time = 26.99 ns
3.3705091948e-03, // time = 27.00 ns
3.3601289276e-03, // time = 27.01 ns
3.3497617166e-03, // time = 27.02 ns
3.3394075448e-03, // time = 27.03 ns
3.3290663953e-03, // time = 27.04 ns
3.3187382511e-03, // time = 27.05 ns
3.3084230954e-03, // time = 27.06 ns
3.2981209112e-03, // time = 27.07 ns
3.2878316816e-03, // time = 27.08 ns
3.2775553898e-03, // time = 27.09 ns
3.2672920191e-03, // time = 27.10 ns
3.2570415525e-03, // time = 27.11 ns
3.2468039734e-03, // time = 27.12 ns
3.2365792649e-03, // time = 27.13 ns
3.2263674103e-03, // time = 27.14 ns
3.2161683930e-03, // time = 27.15 ns
3.2059821963e-03, // time = 27.16 ns
3.1958088034e-03, // time = 27.17 ns
3.1856481978e-03, // time = 27.18 ns
3.1755003628e-03, // time = 27.19 ns
3.1653652818e-03, // time = 27.20 ns
3.1552429383e-03, // time = 27.21 ns
3.1451333157e-03, // time = 27.22 ns
3.1350363975e-03, // time = 27.23 ns
3.1249521672e-03, // time = 27.24 ns
3.1148806083e-03, // time = 27.25 ns
3.1048217043e-03, // time = 27.26 ns
3.0947754388e-03, // time = 27.27 ns
3.0847417955e-03, // time = 27.28 ns
3.0747207578e-03, // time = 27.29 ns
3.0647123095e-03, // time = 27.30 ns
3.0547164342e-03, // time = 27.31 ns
3.0447331155e-03, // time = 27.32 ns
3.0347623372e-03, // time = 27.33 ns
3.0248040830e-03, // time = 27.34 ns
3.0148583366e-03, // time = 27.35 ns
3.0049250818e-03, // time = 27.36 ns
2.9950043023e-03, // time = 27.37 ns
2.9850959821e-03, // time = 27.38 ns
2.9752001049e-03, // time = 27.39 ns
2.9653166546e-03, // time = 27.40 ns
2.9554456150e-03, // time = 27.41 ns
2.9455869701e-03, // time = 27.42 ns
2.9357407037e-03, // time = 27.43 ns
2.9259067999e-03, // time = 27.44 ns
2.9160852426e-03, // time = 27.45 ns
2.9062760157e-03, // time = 27.46 ns
2.8964791033e-03, // time = 27.47 ns
2.8866944894e-03, // time = 27.48 ns
2.8769221581e-03, // time = 27.49 ns
2.8671620934e-03, // time = 27.50 ns
2.8574142794e-03, // time = 27.51 ns
2.8476787003e-03, // time = 27.52 ns
2.8379553402e-03, // time = 27.53 ns
2.8282441832e-03, // time = 27.54 ns
2.8185452136e-03, // time = 27.55 ns
2.8088584156e-03, // time = 27.56 ns
2.7991837733e-03, // time = 27.57 ns
2.7895212710e-03, // time = 27.58 ns
2.7798708930e-03, // time = 27.59 ns
2.7702326236e-03, // time = 27.60 ns
2.7606064471e-03, // time = 27.61 ns
2.7509923479e-03, // time = 27.62 ns
2.7413903102e-03, // time = 27.63 ns
2.7318003186e-03, // time = 27.64 ns
2.7222223572e-03, // time = 27.65 ns
2.7126564107e-03, // time = 27.66 ns
2.7031024635e-03, // time = 27.67 ns
2.6935604999e-03, // time = 27.68 ns
2.6840305046e-03, // time = 27.69 ns
2.6745124619e-03, // time = 27.70 ns
2.6650063565e-03, // time = 27.71 ns
2.6555121729e-03, // time = 27.72 ns
2.6460298956e-03, // time = 27.73 ns
2.6365595093e-03, // time = 27.74 ns
2.6271009985e-03, // time = 27.75 ns
2.6176543479e-03, // time = 27.76 ns
2.6082195422e-03, // time = 27.77 ns
2.5987965661e-03, // time = 27.78 ns
2.5893854041e-03, // time = 27.79 ns
2.5799860412e-03, // time = 27.80 ns
2.5705984619e-03, // time = 27.81 ns
2.5612226511e-03, // time = 27.82 ns
2.5518585935e-03, // time = 27.83 ns
2.5425062740e-03, // time = 27.84 ns
2.5331656774e-03, // time = 27.85 ns
2.5238367885e-03, // time = 27.86 ns
2.5145195922e-03, // time = 27.87 ns
2.5052140734e-03, // time = 27.88 ns
2.4959202170e-03, // time = 27.89 ns
2.4866380080e-03, // time = 27.90 ns
2.4773674312e-03, // time = 27.91 ns
2.4681084716e-03, // time = 27.92 ns
2.4588611144e-03, // time = 27.93 ns
2.4496253443e-03, // time = 27.94 ns
2.4404011466e-03, // time = 27.95 ns
2.4311885062e-03, // time = 27.96 ns
2.4219874083e-03, // time = 27.97 ns
2.4127978379e-03, // time = 27.98 ns
2.4036197802e-03, // time = 27.99 ns
2.3944532202e-03, // time = 28.00 ns
2.3852981432e-03, // time = 28.01 ns
2.3761545344e-03, // time = 28.02 ns
2.3670223788e-03, // time = 28.03 ns
2.3579016619e-03, // time = 28.04 ns
2.3487923687e-03, // time = 28.05 ns
2.3396944846e-03, // time = 28.06 ns
2.3306079948e-03, // time = 28.07 ns
2.3215328847e-03, // time = 28.08 ns
2.3124691395e-03, // time = 28.09 ns
2.3034167447e-03, // time = 28.10 ns
2.2943756856e-03, // time = 28.11 ns
2.2853459475e-03, // time = 28.12 ns
2.2763275159e-03, // time = 28.13 ns
2.2673203762e-03, // time = 28.14 ns
2.2583245139e-03, // time = 28.15 ns
2.2493399144e-03, // time = 28.16 ns
2.2403665632e-03, // time = 28.17 ns
2.2314044458e-03, // time = 28.18 ns
2.2224535478e-03, // time = 28.19 ns
2.2135138547e-03, // time = 28.20 ns
2.2045853520e-03, // time = 28.21 ns
2.1956680254e-03, // time = 28.22 ns
2.1867618604e-03, // time = 28.23 ns
2.1778668428e-03, // time = 28.24 ns
2.1689829581e-03, // time = 28.25 ns
2.1601101920e-03, // time = 28.26 ns
2.1512485302e-03, // time = 28.27 ns
2.1423979585e-03, // time = 28.28 ns
2.1335584625e-03, // time = 28.29 ns
2.1247300280e-03, // time = 28.30 ns
2.1159126407e-03, // time = 28.31 ns
2.1071062866e-03, // time = 28.32 ns
2.0983109512e-03, // time = 28.33 ns
2.0895266206e-03, // time = 28.34 ns
2.0807532806e-03, // time = 28.35 ns
2.0719909170e-03, // time = 28.36 ns
2.0632395157e-03, // time = 28.37 ns
2.0544990626e-03, // time = 28.38 ns
2.0457695437e-03, // time = 28.39 ns
2.0370509449e-03, // time = 28.40 ns
2.0283432521e-03, // time = 28.41 ns
2.0196464515e-03, // time = 28.42 ns
2.0109605289e-03, // time = 28.43 ns
2.0022854704e-03, // time = 28.44 ns
1.9936212621e-03, // time = 28.45 ns
1.9849678901e-03, // time = 28.46 ns
1.9763253403e-03, // time = 28.47 ns
1.9676935990e-03, // time = 28.48 ns
1.9590726522e-03, // time = 28.49 ns
1.9504624861e-03, // time = 28.50 ns
1.9418630869e-03, // time = 28.51 ns
1.9332744408e-03, // time = 28.52 ns
1.9246965339e-03, // time = 28.53 ns
1.9161293526e-03, // time = 28.54 ns
1.9075728830e-03, // time = 28.55 ns
1.8990271113e-03, // time = 28.56 ns
1.8904920240e-03, // time = 28.57 ns
1.8819676073e-03, // time = 28.58 ns
1.8734538474e-03, // time = 28.59 ns
1.8649507309e-03, // time = 28.60 ns
1.8564582440e-03, // time = 28.61 ns
1.8479763731e-03, // time = 28.62 ns
1.8395051046e-03, // time = 28.63 ns
1.8310444249e-03, // time = 28.64 ns
1.8225943205e-03, // time = 28.65 ns
1.8141547779e-03, // time = 28.66 ns
1.8057257835e-03, // time = 28.67 ns
1.7973073238e-03, // time = 28.68 ns
1.7888993853e-03, // time = 28.69 ns
1.7805019546e-03, // time = 28.70 ns
1.7721150182e-03, // time = 28.71 ns
1.7637385628e-03, // time = 28.72 ns
1.7553725748e-03, // time = 28.73 ns
1.7470170410e-03, // time = 28.74 ns
1.7386719479e-03, // time = 28.75 ns
1.7303372822e-03, // time = 28.76 ns
1.7220130306e-03, // time = 28.77 ns
1.7136991797e-03, // time = 28.78 ns
1.7053957164e-03, // time = 28.79 ns
1.6971026272e-03, // time = 28.80 ns
1.6888198990e-03, // time = 28.81 ns
1.6805475185e-03, // time = 28.82 ns
1.6722854726e-03, // time = 28.83 ns
1.6640337479e-03, // time = 28.84 ns
1.6557923314e-03, // time = 28.85 ns
1.6475612099e-03, // time = 28.86 ns
1.6393403702e-03, // time = 28.87 ns
1.6311297992e-03, // time = 28.88 ns
1.6229294839e-03, // time = 28.89 ns
1.6147394111e-03, // time = 28.90 ns
1.6065595678e-03, // time = 28.91 ns
1.5983899409e-03, // time = 28.92 ns
1.5902305175e-03, // time = 28.93 ns
1.5820812844e-03, // time = 28.94 ns
1.5739422288e-03, // time = 28.95 ns
1.5658133377e-03, // time = 28.96 ns
1.5576945980e-03, // time = 28.97 ns
1.5495859969e-03, // time = 28.98 ns
1.5414875215e-03, // time = 28.99 ns
1.5333991588e-03, // time = 29.00 ns
1.5253208960e-03, // time = 29.01 ns
1.5172527202e-03, // time = 29.02 ns
1.5091946187e-03, // time = 29.03 ns
1.5011465785e-03, // time = 29.04 ns
1.4931085869e-03, // time = 29.05 ns
1.4850806311e-03, // time = 29.06 ns
1.4770626983e-03, // time = 29.07 ns
1.4690547757e-03, // time = 29.08 ns
1.4610568508e-03, // time = 29.09 ns
1.4530689107e-03, // time = 29.10 ns
1.4450909427e-03, // time = 29.11 ns
1.4371229342e-03, // time = 29.12 ns
1.4291648726e-03, // time = 29.13 ns
1.4212167451e-03, // time = 29.14 ns
1.4132785392e-03, // time = 29.15 ns
1.4053502423e-03, // time = 29.16 ns
1.3974318418e-03, // time = 29.17 ns
1.3895233251e-03, // time = 29.18 ns
1.3816246796e-03, // time = 29.19 ns
1.3737358930e-03, // time = 29.20 ns
1.3658569526e-03, // time = 29.21 ns
1.3579878459e-03, // time = 29.22 ns
1.3501285606e-03, // time = 29.23 ns
1.3422790841e-03, // time = 29.24 ns
1.3344394039e-03, // time = 29.25 ns
1.3266095078e-03, // time = 29.26 ns
1.3187893832e-03, // time = 29.27 ns
1.3109790178e-03, // time = 29.28 ns
1.3031783993e-03, // time = 29.29 ns
1.2953875152e-03, // time = 29.30 ns
1.2876063533e-03, // time = 29.31 ns
1.2798349013e-03, // time = 29.32 ns
1.2720731468e-03, // time = 29.33 ns
1.2643210776e-03, // time = 29.34 ns
1.2565786814e-03, // time = 29.35 ns
1.2488459459e-03, // time = 29.36 ns
1.2411228591e-03, // time = 29.37 ns
1.2334094086e-03, // time = 29.38 ns
1.2257055822e-03, // time = 29.39 ns
1.2180113679e-03, // time = 29.40 ns
1.2103267534e-03, // time = 29.41 ns
1.2026517266e-03, // time = 29.42 ns
1.1949862755e-03, // time = 29.43 ns
1.1873303878e-03, // time = 29.44 ns
1.1796840516e-03, // time = 29.45 ns
1.1720472547e-03, // time = 29.46 ns
1.1644199851e-03, // time = 29.47 ns
1.1568022308e-03, // time = 29.48 ns
1.1491939798e-03, // time = 29.49 ns
1.1415952200e-03, // time = 29.50 ns
1.1340059396e-03, // time = 29.51 ns
1.1264261265e-03, // time = 29.52 ns
1.1188557688e-03, // time = 29.53 ns
1.1112948545e-03, // time = 29.54 ns
1.1037433719e-03, // time = 29.55 ns
1.0962013089e-03, // time = 29.56 ns
1.0886686537e-03, // time = 29.57 ns
1.0811453945e-03, // time = 29.58 ns
1.0736315194e-03, // time = 29.59 ns
1.0661270166e-03, // time = 29.60 ns
1.0586318743e-03, // time = 29.61 ns
1.0511460807e-03, // time = 29.62 ns
1.0436696241e-03, // time = 29.63 ns
1.0362024926e-03, // time = 29.64 ns
1.0287446746e-03, // time = 29.65 ns
1.0212961583e-03, // time = 29.66 ns
1.0138569320e-03, // time = 29.67 ns
1.0064269841e-03, // time = 29.68 ns
9.9900630290e-04, // time = 29.69 ns
9.9159487670e-04, // time = 29.70 ns
9.8419269388e-04, // time = 29.71 ns
9.7679974285e-04, // time = 29.72 ns
9.6941601200e-04, // time = 29.73 ns
9.6204148974e-04, // time = 29.74 ns
9.5467616451e-04, // time = 29.75 ns
9.4732002476e-04, // time = 29.76 ns
9.3997305896e-04, // time = 29.77 ns
9.3263525559e-04, // time = 29.78 ns
9.2530660316e-04, // time = 29.79 ns
9.1798709017e-04, // time = 29.80 ns
9.1067670517e-04, // time = 29.81 ns
9.0337543670e-04, // time = 29.82 ns
8.9608327334e-04, // time = 29.83 ns
8.8880020366e-04, // time = 29.84 ns
8.8152621627e-04, // time = 29.85 ns
8.7426129978e-04, // time = 29.86 ns
8.6700544283e-04, // time = 29.87 ns
8.5975863408e-04, // time = 29.88 ns
8.5252086217e-04, // time = 29.89 ns
8.4529211581e-04, // time = 29.90 ns
8.3807238368e-04, // time = 29.91 ns
8.3086165450e-04, // time = 29.92 ns
8.2365991702e-04, // time = 29.93 ns
8.1646715996e-04, // time = 29.94 ns
8.0928337211e-04, // time = 29.95 ns
8.0210854224e-04, // time = 29.96 ns
7.9494265915e-04, // time = 29.97 ns
7.8778571165e-04, // time = 29.98 ns
7.8063768857e-04, // time = 29.99 ns
7.7155314684e-04, // time = 30.00 ns
7.6656313013e-04, // time = 30.01 ns
7.6086528589e-04, // time = 30.02 ns
7.5375088195e-04, // time = 30.03 ns
7.4664531521e-04, // time = 30.04 ns
7.3954859750e-04, // time = 30.05 ns
7.3246072530e-04, // time = 30.06 ns
7.2538169006e-04, // time = 30.07 ns
7.1831148155e-04, // time = 30.08 ns
7.1125008902e-04, // time = 30.09 ns
7.0419750158e-04, // time = 30.10 ns
6.9715370826e-04, // time = 30.11 ns
6.9011869811e-04, // time = 30.12 ns
6.8309246019e-04, // time = 30.13 ns
6.7607498357e-04, // time = 30.14 ns
6.6906625733e-04, // time = 30.15 ns
6.6206627057e-04, // time = 30.16 ns
6.5507501240e-04, // time = 30.17 ns
6.4809247196e-04, // time = 30.18 ns
6.4111863838e-04, // time = 30.19 ns
6.3415350083e-04, // time = 30.20 ns
6.2719704848e-04, // time = 30.21 ns
6.2024927053e-04, // time = 30.22 ns
6.1331015619e-04, // time = 30.23 ns
6.0637969469e-04, // time = 30.24 ns
5.9945787526e-04, // time = 30.25 ns
5.9254468716e-04, // time = 30.26 ns
5.8564011966e-04, // time = 30.27 ns
5.7874416204e-04, // time = 30.28 ns
5.7185680362e-04, // time = 30.29 ns
5.6497803371e-04, // time = 30.30 ns
5.5810784163e-04, // time = 30.31 ns
5.5124621675e-04, // time = 30.32 ns
5.4439314842e-04, // time = 30.33 ns
5.3754862603e-04, // time = 30.34 ns
5.3071263896e-04, // time = 30.35 ns
5.2388517663e-04, // time = 30.36 ns
5.1706622848e-04, // time = 30.37 ns
5.1025578392e-04, // time = 30.38 ns
5.0345383243e-04, // time = 30.39 ns
4.9666036348e-04, // time = 30.40 ns
4.8987536655e-04, // time = 30.41 ns
4.8309883115e-04, // time = 30.42 ns
4.7633074679e-04, // time = 30.43 ns
4.6957110300e-04, // time = 30.44 ns
4.6281988934e-04, // time = 30.45 ns
4.5607709536e-04, // time = 30.46 ns
4.4934271065e-04, // time = 30.47 ns
4.4261672479e-04, // time = 30.48 ns
4.3589912740e-04, // time = 30.49 ns
4.2918990810e-04, // time = 30.50 ns
4.2248905653e-04, // time = 30.51 ns
4.1579656234e-04, // time = 30.52 ns
4.0911241520e-04, // time = 30.53 ns
4.0243660479e-04, // time = 30.54 ns
3.9576912082e-04, // time = 30.55 ns
3.8910995299e-04, // time = 30.56 ns
3.8245909104e-04, // time = 30.57 ns
3.7581652470e-04, // time = 30.58 ns
3.6918224373e-04, // time = 30.59 ns
3.6255623791e-04, // time = 30.60 ns
3.5593849703e-04, // time = 30.61 ns
3.4932901089e-04, // time = 30.62 ns
3.4272776929e-04, // time = 30.63 ns
3.3613476208e-04, // time = 30.64 ns
3.2954997911e-04, // time = 30.65 ns
3.2297341022e-04, // time = 30.66 ns
3.1640504531e-04, // time = 30.67 ns
3.0984487425e-04, // time = 30.68 ns
3.0329288696e-04, // time = 30.69 ns
2.9674907335e-04, // time = 30.70 ns
2.9021342336e-04, // time = 30.71 ns
2.8368592694e-04, // time = 30.72 ns
2.7716657406e-04, // time = 30.73 ns
2.7065535468e-04, // time = 30.74 ns
2.6415225880e-04, // time = 30.75 ns
2.5765727644e-04, // time = 30.76 ns
2.5117039760e-04, // time = 30.77 ns
2.4469161233e-04, // time = 30.78 ns
2.3822091068e-04, // time = 30.79 ns
2.3175828271e-04, // time = 30.80 ns
2.2530371850e-04, // time = 30.81 ns
2.1885720814e-04, // time = 30.82 ns
2.1241874175e-04, // time = 30.83 ns
2.0598830943e-04, // time = 30.84 ns
1.9956590134e-04, // time = 30.85 ns
1.9315150761e-04, // time = 30.86 ns
1.8674511842e-04, // time = 30.87 ns
1.8034672394e-04, // time = 30.88 ns
1.7395631437e-04, // time = 30.89 ns
1.6757387991e-04, // time = 30.90 ns
1.6119941079e-04, // time = 30.91 ns
1.5483289723e-04, // time = 30.92 ns
1.4847432949e-04, // time = 30.93 ns
1.4212369784e-04, // time = 30.94 ns
1.3578099255e-04, // time = 30.95 ns
1.2944620391e-04, // time = 30.96 ns
1.2311932223e-04, // time = 30.97 ns
1.1680033782e-04, // time = 30.98 ns
1.1048924103e-04, // time = 30.99 ns
1.0418602220e-04 };// time = 31.00 ns
}
| 41.493914 | 67 | 0.568425 |
219dd34be04d01ba0039885fdc414cc282d234e3 | 15,257 | cpp | C++ | BAPSPresenter/SecurityDialog.cpp | UniversityRadioYork/BAPS2 | af80b66cdd7a980cf34714bef7b5260167714ca5 | [
"BSD-3-Clause"
] | 4 | 2018-12-20T20:58:46.000Z | 2019-05-22T21:32:43.000Z | BAPSPresenter/SecurityDialog.cpp | UniversityRadioYork/BAPS2 | af80b66cdd7a980cf34714bef7b5260167714ca5 | [
"BSD-3-Clause"
] | 9 | 2018-12-22T00:55:13.000Z | 2019-01-21T10:08:30.000Z | BAPSPresenter/SecurityDialog.cpp | UniversityRadioYork/BAPS2 | af80b66cdd7a980cf34714bef7b5260167714ca5 | [
"BSD-3-Clause"
] | 1 | 2018-12-21T19:32:48.000Z | 2018-12-21T19:32:48.000Z | #include "StdAfx.h"
#include "SecurityDialog.h"
#include "UtilityMacros.h"
#undef MessageBox
using namespace BAPSPresenter;
void SecurityDialog::receiveUserCount(System::Object^ _count)
{
grantButton->Enabled = false;
revokeButton->Enabled = false;
availablePermissionList->Enabled = false;
permissionList->Enabled = false;
newPasswordText->Enabled = false;
newPasswordText->Text = "12345";
confirmNewPasswordText->Enabled = false;
confirmNewPasswordText->Text = "12345";
setPasswordButton->Enabled = false;
deleteUserButton->Enabled = false;
selectedUserLabel->Text = "<Select User>";
permissionList->Items->Clear();
availablePermissionList->Items->Clear();
userList->Enabled = false;
userList->Items->Clear();
userCount = safe_cast<int>(_count);
if (userCount == 0)
{
status = SD_DORMANT;
userList->Enabled=true;
}
}
void SecurityDialog::receiveUserInfo(System::String^ username, System::Object^ _permissions)
{
int permissions = safe_cast<int>(_permissions);
userList->Items->Add(gcnew UserInfo(username, permissions));
userCount--;
if (userCount == 0)
{
status = SD_DORMANT;
userList->Enabled=true;
}
}
void SecurityDialog::receivePermissionCount(System::Object^ _count)
{
permissionCount = safe_cast<int>(_count);
permissionInfo = gcnew array<PermissionInfo^>(permissionCount);
}
void SecurityDialog::receivePermissionInfo(System::Object^ _permissionCode, System::String^ description)
{
int permissionCode = safe_cast<int>(_permissionCode);
permissionInfo[permissionInfo->Length-permissionCount] = gcnew PermissionInfo(permissionCode, description);
permissionCount--;
if (permissionCount == 0)
{
status = SD_GETUSERS;
Command cmd = BAPSNET_CONFIG | BAPSNET_GETUSERS;
msgQueue->Enqueue(gcnew ActionMessage(cmd));
}
}
void SecurityDialog::receiveUserResult(System::Object^ _resultCode, System::String^ description)
{
SecurityStatus tempStatus = SD_DORMANT;
int resultCode = safe_cast<int>(_resultCode);
switch (status)
{
case SD_AWAITING_INIT:
case SD_GETUSERS:
System::Windows::Forms::MessageBox::Show(System::String::Concat("Cannot open Security Manager, reason: ", description), "Error:", System::Windows::Forms::MessageBoxButtons::OK);
this->Close();
break;
case SD_DORMANT:
System::Windows::Forms::MessageBox::Show("A recoverable error has occurred, this dialog will be closed. (Result rcvd but no cmd issued)", "Error:", System::Windows::Forms::MessageBoxButtons::OK);
this->Close();
break;
case SD_ADDUSER:
if (resultCode == 0)
{
newUsernameText->Text="";
passwordText->Text="";
confirmPasswordText->Text="";
addUserButton->Enabled=true;
tempStatus = SD_GETUSERS;
status = SD_GETUSERS;
Command cmd = BAPSNET_CONFIG | BAPSNET_GETUSERS;
msgQueue->Enqueue(gcnew ActionMessage(cmd));
}
else
{
System::Windows::Forms::MessageBox::Show(System::String::Concat("Cannot add user, reason: ", description), "Error:", System::Windows::Forms::MessageBoxButtons::OK);
}
break;
case SD_SETPASSWORD:
if (resultCode == 0)
{
newPasswordText->Text="12345";
confirmNewPasswordText->Text="12345";
setPasswordButton->Enabled=true;
}
else
{
System::Windows::Forms::MessageBox::Show(System::String::Concat("Cannot set password, reason: ", description), "Error:", System::Windows::Forms::MessageBoxButtons::OK);
}
break;
case SD_REMOVEUSER:
if (resultCode == 0)
{
tempStatus = SD_GETUSERS;
status = SD_GETUSERS;
Command cmd = BAPSNET_CONFIG | BAPSNET_GETUSERS;
msgQueue->Enqueue(gcnew ActionMessage(cmd));
}
else
{
System::Windows::Forms::MessageBox::Show(System::String::Concat("Cannot delete user, reason: ", description), "Error:", System::Windows::Forms::MessageBoxButtons::OK);
}
break;
case SD_REVOKEPERMISSION:
if (resultCode == 0)
{
tempStatus = SD_GETUSERS;
status = SD_GETUSERS;
Command cmd = BAPSNET_CONFIG | BAPSNET_GETUSERS;
msgQueue->Enqueue(gcnew ActionMessage(cmd));
}
else
{
System::Windows::Forms::MessageBox::Show(System::String::Concat("Cannot revoke permission, reason: ", description), "Error:", System::Windows::Forms::MessageBoxButtons::OK);
}
break;
case SD_GRANTPERMISSION:
if (resultCode == 0)
{
tempStatus = SD_GETUSERS;
status = SD_GETUSERS;
Command cmd = BAPSNET_CONFIG | BAPSNET_GETUSERS;
msgQueue->Enqueue(gcnew ActionMessage(cmd));
}
else
{
System::Windows::Forms::MessageBox::Show(System::String::Concat("Cannot grant permission, reason: ", description), "Error:", System::Windows::Forms::MessageBoxButtons::OK);
}
break;
}
status = tempStatus;
}
System::Void SecurityDialog::refreshButton_Click(System::Object ^ sender, System::EventArgs ^ e)
{
if (status == SD_DORMANT)
{
addUserButton->Enabled=false;
status = SD_GETUSERS;
Command cmd = BAPSNET_CONFIG | BAPSNET_GETUSERS;
msgQueue->Enqueue(gcnew ActionMessage(cmd));
}
else
{
System::Windows::Forms::MessageBox::Show("A command is still being processed please wait and try again", "Notice:", System::Windows::Forms::MessageBoxButtons::OK);
}
}
System::Void SecurityDialog::deleteUserButton_Click(System::Object ^ sender, System::EventArgs ^ e)
{
if (status == SD_DORMANT)
{
System::Windows::Forms::DialogResult dr;
dr = System::Windows::Forms::MessageBox::Show("Are you sure you wish to delete the selcted user?", "Notice:", System::Windows::Forms::MessageBoxButtons::YesNo);
if (dr == System::Windows::Forms::DialogResult::Yes)
{
status = SD_REMOVEUSER;
Command cmd = BAPSNET_CONFIG | BAPSNET_REMOVEUSER;
msgQueue->Enqueue(gcnew ActionMessageString(cmd, selectedUserLabel->Text));
}
}
else
{
System::Windows::Forms::MessageBox::Show("A command is still being processed please wait and try again", "Notice:", System::Windows::Forms::MessageBoxButtons::OK);
}
}
System::Void SecurityDialog::newUserText_Leave(System::Object ^ sender, System::EventArgs ^ e)
{
bool valid = (newUsernameText->Text->Length>0 &&
System::String::Compare(passwordText->Text, confirmPasswordText->Text) == 0);
addUserButton->Enabled = valid;
if (!valid)
{
newUsernameLabel->ForeColor = System::Drawing::Color::Red;
confirmPasswordLabel->ForeColor = System::Drawing::Color::Red;
}
else
{
newUsernameLabel->ForeColor = System::Drawing::SystemColors::ControlText;
confirmPasswordLabel->ForeColor = System::Drawing::SystemColors::ControlText;
}
}
System::Void SecurityDialog::changePassword_TextChanged(System::Object ^ sender, System::EventArgs ^ e)
{
bool valid = (System::String::Compare(newPasswordText->Text, confirmNewPasswordText->Text) == 0);
setPasswordButton->Enabled = valid;
if (!valid)
{
confirmNewPasswordLabel->ForeColor = System::Drawing::Color::Red;
}
else
{
confirmNewPasswordLabel->ForeColor = System::Drawing::SystemColors::ControlText;
}
}
System::Void SecurityDialog::addUserButton_Click(System::Object ^ sender, System::EventArgs ^ e)
{
if (status == SD_DORMANT)
{
addUserButton->Enabled=false;
status = SD_ADDUSER;
Command cmd = BAPSNET_CONFIG | BAPSNET_ADDUSER;
msgQueue->Enqueue(gcnew ActionMessageStringString(cmd, newUsernameText->Text, passwordText->Text));
}
else
{
System::Windows::Forms::MessageBox::Show("A command is still being processed please wait and try again", "Notice:", System::Windows::Forms::MessageBoxButtons::OK);
}
}
System::Void SecurityDialog::setPasswordButton_Click(System::Object ^ sender, System::EventArgs ^ e)
{
if (status == SD_DORMANT)
{
setPasswordButton->Enabled=false;
status = SD_SETPASSWORD;
Command cmd = BAPSNET_CONFIG | BAPSNET_SETPASSWORD;
msgQueue->Enqueue(gcnew ActionMessageStringString(cmd, selectedUserLabel->Text, newPasswordText->Text));
}
else
{
System::Windows::Forms::MessageBox::Show("A command is still being processed please wait and try again", "Notice:", System::Windows::Forms::MessageBoxButtons::OK);
}
}
System::Void SecurityDialog::userList_SelectedIndexChanged(System::Object ^ sender, System::EventArgs ^ e)
{
grantButton->Enabled = false;
revokeButton->Enabled = false;
availablePermissionList->Enabled = false;
permissionList->Enabled = false;
newPasswordText->Enabled = false;
newPasswordText->Text = "12345";
confirmNewPasswordText->Enabled = false;
confirmNewPasswordText->Text = "12345";
setPasswordButton->Enabled = false;
deleteUserButton->Enabled = false;
UserInfo^ userInfo;
if (userList->SelectedIndex != -1)
{
userInfo = static_cast<UserInfo^>(userList->Items[userList->SelectedIndex]);
}
else
{
userInfo = gcnew UserInfo("<None>", 0);
}
selectedUserLabel->Text = userInfo->username;
int permissions = userInfo->permissions;
permissionList->Items->Clear();
availablePermissionList->Items->Clear();
int i;
for (i = 0 ; i < permissionInfo->Length ; i++)
{
if (ISFLAGSET(permissions, permissionInfo[i]->permissionCode))
{
permissionList->Items->Add(permissionInfo[i]);
}
else
{
availablePermissionList->Items->Add(permissionInfo[i]);
}
}
availablePermissionList->Enabled = true;
permissionList->Enabled = true;
newPasswordText->Enabled = true;
confirmNewPasswordText->Enabled = true;
deleteUserButton->Enabled = true;
}
System::Void SecurityDialog::permissionList_SelectedIndexChanged(System::Object ^ sender, System::EventArgs ^ e)
{
revokeButton->Enabled = (permissionList->SelectedIndex != -1);
}
System::Void SecurityDialog::availablePermissionList_SelectedIndexChanged(System::Object ^ sender, System::EventArgs ^ e)
{
grantButton->Enabled = (availablePermissionList->SelectedIndex != -1);
}
System::Void SecurityDialog::revokeButton_Click(System::Object ^ sender, System::EventArgs ^ e)
{
if (status == SD_DORMANT)
{
status = SD_REVOKEPERMISSION;
int permission = static_cast<PermissionInfo^>(permissionList->Items[permissionList->SelectedIndex])->permissionCode;
Command cmd = BAPSNET_CONFIG | BAPSNET_REVOKEPERMISSION;
msgQueue->Enqueue(gcnew ActionMessageStringU32int(cmd, selectedUserLabel->Text, permission));
}
else
{
System::Windows::Forms::MessageBox::Show("A command is still being processed please wait and try again", "Notice:", System::Windows::Forms::MessageBoxButtons::OK);
}
}
System::Void SecurityDialog::grantButton_Click(System::Object ^ sender, System::EventArgs ^ e)
{
if (status == SD_DORMANT)
{
status = SD_GRANTPERMISSION;
int permission = static_cast<PermissionInfo^>(availablePermissionList->Items[availablePermissionList->SelectedIndex])->permissionCode;
Command cmd = BAPSNET_CONFIG | BAPSNET_GRANTPERMISSION;
msgQueue->Enqueue(gcnew ActionMessageStringU32int(cmd, selectedUserLabel->Text, permission));
}
else
{
System::Windows::Forms::MessageBox::Show("A command is still being processed please wait and try again", "Notice:", System::Windows::Forms::MessageBoxButtons::OK);
}
}
void SecurityDialog::receiveIPDenyCount(System::Object^ _count)
{
denyCount = safe_cast<int>(_count);
deniedIPList->Enabled=false;
deniedIPList->Items->Clear();
if (denyCount == 0)
{
if (status == SD_GETIPRESTRICTIONS)
{
status = SD_GETIPRESTRICTIONS2;
}
else
{
status = SD_DORMANT;
}
deniedIPList->Enabled=true;
}
}
void SecurityDialog::receiveIPAllowCount(System::Object^ _count)
{
allowCount = safe_cast<int>(_count);
allowedIPList->Enabled=false;
allowedIPList->Items->Clear();
if (allowCount == 0)
{
if (status == SD_GETIPRESTRICTIONS)
{
status = SD_GETIPRESTRICTIONS2;
}
else
{
status = SD_DORMANT;
}
allowedIPList->Enabled=true;
}
}
void SecurityDialog::receiveIPDeny(System::String^ ipaddress, System::Object^ _mask)
{
int mask = safe_cast<int>(_mask);
deniedIPList->Items->Add(gcnew IPRestriction(ipaddress, mask));
denyCount--;
if (denyCount == 0)
{
if (status == SD_GETIPRESTRICTIONS)
{
status = SD_GETIPRESTRICTIONS2;
}
else
{
status = SD_DORMANT;
}
deniedIPList->Enabled=true;
}
}
void SecurityDialog::receiveIPAllow(System::String^ ipaddress, System::Object^ _mask)
{
int mask = safe_cast<int>(_mask);
allowedIPList->Items->Add(gcnew IPRestriction(ipaddress, mask));
allowCount--;
if (allowCount == 0)
{
if (status == SD_GETIPRESTRICTIONS)
{
status = SD_GETIPRESTRICTIONS2;
}
else
{
status = SD_DORMANT;
}
allowedIPList->Enabled=true;
}
}
System::Void SecurityDialog::securityPageControl_SelectedIndexChanged(System::Object ^ sender, System::EventArgs ^ e)
{
if (securityPageControl->SelectedTab == userManagerPage)
{
if (status == SD_DORMANT)
{
status = SD_GETUSERS;
Command cmd = BAPSNET_CONFIG | BAPSNET_GETUSERS;
msgQueue->Enqueue(gcnew ActionMessage(cmd));
}
else
{
System::Windows::Forms::MessageBox::Show("A command is still being processed please wait and use the refresh button to update the form.", "Notice:", System::Windows::Forms::MessageBoxButtons::OK);
}
}
else if (securityPageControl->SelectedTab == connectionManagerPage)
{
if (status == SD_DORMANT)
{
status = SD_GETIPRESTRICTIONS;
Command cmd = BAPSNET_CONFIG | BAPSNET_GETIPRESTRICTIONS;
msgQueue->Enqueue(gcnew ActionMessage(cmd));
}
else
{
System::Windows::Forms::MessageBox::Show("A command is still being processed please wait and use the refresh button to update the form.", "Notice:", System::Windows::Forms::MessageBoxButtons::OK);
}
}
}
void SecurityDialog::receiveConfigError(System::Object^ _resultCode, System::String^ description)
{
int resultCode = safe_cast<int>(_resultCode);
if (resultCode != 0)
{
System::Windows::Forms::MessageBox::Show(System::String::Concat("Unable to alter IP list, reason: ", description), "Error:", System::Windows::Forms::MessageBoxButtons::OK);
}
status = SD_GETIPRESTRICTIONS;
Command cmd = BAPSNET_CONFIG | BAPSNET_GETIPRESTRICTIONS;
msgQueue->Enqueue(gcnew ActionMessage(cmd));
}
System::Void SecurityDialog::alterRestrictionButton_Click(System::Object ^ sender, System::EventArgs ^ e)
{
if (status == SD_DORMANT)
{
try
{
int cmdMask = safe_cast<int>(static_cast<System::Windows::Forms::Button^>(sender)->Tag);
status = SD_ALTERIPRESTRICTION;
Command cmd = BAPSNET_CONFIG | BAPSNET_ALTERIPRESTRICTION | cmdMask;
msgQueue->Enqueue(gcnew ActionMessageStringU32int(cmd, ipAddressText->Text, (u32int)System::Convert::ToInt32(maskText->Text)));
}
catch (System::FormatException^ )
{
System::Windows::Forms::MessageBox::Show("The mask value must be an integer.", "Error:", System::Windows::Forms::MessageBoxButtons::OK);
status = SD_DORMANT;
}
}
else
{
System::Windows::Forms::MessageBox::Show("A command is still being processed please wait and use the refresh button to update the form.", "Notice:", System::Windows::Forms::MessageBoxButtons::OK);
}
}
System::Void SecurityDialog::SecurityDialog_KeyDown(System::Object^ sender, System::Windows::Forms::KeyEventArgs^ e)
{
bool ignore = false;
switch (e->KeyCode)
{
case 'S' : /** Ctrl+s opens this window, we don't want another **/
if (e->Control & e->Shift)
{
ignore = true;
}
}
if (!ignore)
{
MethodInvokerObjKeyEventArgs^ mi = gcnew MethodInvokerObjKeyEventArgs(bapsPresenterMain, &BAPSPresenterMain::BAPSPresenterMain_KeyDown);
array<System::Object^>^ dd = gcnew array<System::Object^>(2) {bapsPresenterMain, e};
this->Invoke(mi, dd);
}
} | 32.324153 | 199 | 0.730878 |
219f4474b7a0e490495e53119708bdffb0737351 | 950 | cpp | C++ | test/linux/main.cpp | 77Z/Shadow-Engine | a07121d56dcf71a040580e9d4e563f36a70123a3 | [
"MIT"
] | 3 | 2020-08-31T20:38:54.000Z | 2021-06-17T12:31:44.000Z | test/linux/main.cpp | 77Z/Shadow-Engine | a07121d56dcf71a040580e9d4e563f36a70123a3 | [
"MIT"
] | 3 | 2020-08-31T19:08:43.000Z | 2022-03-25T19:11:50.000Z | test/linux/main.cpp | 77Z/Shadow-Engine | a07121d56dcf71a040580e9d4e563f36a70123a3 | [
"MIT"
] | null | null | null | //Copyright © Vince Richter 2020
//Copyright © 77Z™ 2020
#include "main.h"
void print(std::string text) {
std::cout << text << std::endl;
}
inline bool exists(const std::string& name) {
struct stat buffer;
return (stat (name.c_str(), &buffer) == 0);
}
int main() {
print("Running Linux Style Tests");
if (exists("./node_modules/electron/dist/electron")) {
print("Test 1 Passed");
} else {
print("Test 1 Failed");
exit(1);
}
if (exists("./node_modules/node-pty/build/Release/pty.node")) {
print("Test 2 Passed");
} else {
print("Test 2 Failed");
exit(1);
}
if (exists("./node_modules/uuid/dist/index.js")) {
print("Test 3 Passed");
} else {
print("Test 3 Failed");
exit(1);
}
print("All tests passed (Linux)");
//Every Test Passed, exit with code 0
return 0;
}
| 21.111111 | 68 | 0.532632 |
21a0be3e9e52fc6864f119b94e882cd0fb50af9f | 2,681 | cpp | C++ | ExaHyPE/kernels/aderdg/generic/fortran/3d/amrRoutines3D.cpp | yungcheeze/exahype | 897970ea2836132e1c221eec7bd1a717afee97ae | [
"BSD-3-Clause"
] | 2 | 2019-08-14T22:41:26.000Z | 2020-02-04T19:30:24.000Z | ExaHyPE/kernels/aderdg/generic/fortran/3d/amrRoutines3D.cpp | yungcheeze/exahype | 897970ea2836132e1c221eec7bd1a717afee97ae | [
"BSD-3-Clause"
] | null | null | null | ExaHyPE/kernels/aderdg/generic/fortran/3d/amrRoutines3D.cpp | yungcheeze/exahype | 897970ea2836132e1c221eec7bd1a717afee97ae | [
"BSD-3-Clause"
] | 3 | 2019-07-22T10:27:36.000Z | 2020-05-11T12:25:29.000Z | /**
* This file is part of the ExaHyPE project.
* Copyright (c) 2016 http://exahype.eu
* All rights reserved.
*
* The project has received funding from the European Union's Horizon
* 2020 research and innovation programme under grant agreement
* No 671698. For copyrights and licensing, please consult the webpage.
*
* Released under the BSD 3 Open Source License.
* For the full license text, see LICENSE.txt
**/
#include "kernels/aderdg/generic/Kernels.h"
#include "tarch/la/Scalar.h"
#include "tarch/la/ScalarOperations.h"
#include "kernels/GaussLegendreQuadrature.h"
#include "kernels/DGMatrices.h"
#if DIMENSIONS == 3
void kernels::aderdg::generic::fortran::faceUnknownsProlongation(double* lQhbndFine,
double* lFhbndFine,
const double* lQhbndCoarse,
const double* lFhbndCoarse,
const int coarseGridLevel,
const int fineGridLevel,
const tarch::la::Vector<DIMENSIONS-1, int>& subfaceIndex,
const int numberOfVariables, const int basisSize){
// @todo Please implement!
}
void kernels::aderdg::generic::fortran::faceUnknownsRestriction(double* lQhbndCoarse,
double* lFhbndCoarse,
const double* lQhbndFine,
const double* lFhbndFine,
const int coarseGridLevel,
const int fineGridLevel,
const tarch::la::Vector<DIMENSIONS-1, int>& subfaceIndex,
const int numberOfVariables, const int basisSize){
// @todo Please implement!
}
void kernels::aderdg::generic::fortran::volumeUnknownsProlongation(double* luhFine,
const double* luhCoarse,
const int coarseGridLevel,
const int fineGridLevel,
const tarch::la::Vector<DIMENSIONS, int>& subcellIndex,
const int numberOfVariables, const int basisSize){
// @todo Please implement!
}
void kernels::aderdg::generic::fortran::volumeUnknownsRestriction(double* luhCoarse,
const double* luhFine,
const int coarseGridLevel,
const int fineGridLevel,
const tarch::la::Vector<DIMENSIONS, int>& subcellIndex,
const int numberOfVariables, const int basisSize){
// @todo Please implement!
}
#endif
| 42.555556 | 87 | 0.56658 |
21a16fb2c835e0de58984b52ed7b0ce6a9144ce8 | 6,168 | cpp | C++ | source/function.cpp | Venkster123/Zhetapi | 9a034392c06733c57d892afde300e90c4b7036f9 | [
"MIT"
] | 27 | 2020-06-05T15:39:31.000Z | 2022-01-07T05:03:01.000Z | source/function.cpp | Venkster123/Zhetapi | 9a034392c06733c57d892afde300e90c4b7036f9 | [
"MIT"
] | 1 | 2021-02-12T04:51:40.000Z | 2021-02-12T04:51:40.000Z | source/function.cpp | Venkster123/Zhetapi | 9a034392c06733c57d892afde300e90c4b7036f9 | [
"MIT"
] | 4 | 2021-02-12T04:39:55.000Z | 2021-11-15T08:00:06.000Z | #include "../engine/function.hpp"
#include "../engine/engine.hpp"
#include "../engine/core/operation_base.hpp"
namespace zhetapi {
// Static variables
Engine *Function::shared_context = new Engine();
double Function::h = 0.0001;
// Methods
// TODO: use macro
ZHP_TOKEN_METHOD(ftn_deriv_method)
{
// TODO: remove assert (and use a special one that throw mistch errs)
assert(args.size() == 0);
Function *fptr = dynamic_cast <Function *> (tptr);
// Differentiate on first arg by default
return fptr->differentiate(fptr->_params[0]).copy();
}
MethodTable Function::mtable ({
{"derivative", {&ftn_deriv_method, "NA"}}
});
// Constructors
Function::Function() : _threads(1), Token(&Function::mtable) {}
Function::Function(const char *str) : Function(std::string(str)) {}
// TODO: Take an Engine as an input as well: there is no need to delay rvalue resolution
Function::Function(const std::string &str, Engine *context)
: _threads(1), Token(&Function::mtable)
{
// TODO: Remove this (duplication)
std::string pack;
std::string tmp;
size_t count;
size_t index;
size_t start;
size_t end;
size_t i;
bool valid;
bool sb;
bool eb;
count = 0;
valid = false;
sb = false;
eb = false;
// Split string into expression and symbols
for (i = 0; i < str.length(); i++) {
if (str[i] == '=') {
valid = true;
index = i;
++count;
}
}
if (!valid || count != 1)
throw invalid_definition();
_symbol = str.substr(0, index);
// Determine parameters' symbols
for (start = -1, i = 0; i < _symbol.length(); i++) {
if (str[i] == '(' && start == -1) {
start = i;
sb = true;
}
if (str[i] == ')') {
end = i;
eb = true;
}
}
if (!sb || !eb)
throw invalid_definition();
pack = _symbol.substr(start + 1, end - start - 1);
for (i = 0; i < pack.length(); i++) {
if (pack[i] == ',' && !tmp.empty()) {
_params.push_back(tmp);
tmp.clear();
} else if (!isspace(pack[i])) {
tmp += pack[i];
}
}
if (!tmp.empty())
_params.push_back(tmp);
// Determine function's symbol
_symbol = _symbol.substr(0, start);
// Construct the tree manager
_manager = node_manager(context, str.substr(++index), _params);
/* using namespace std;
cout << "FUNCTION manager:" << endl;
print(); */
}
// Member-wise construction (TODO: change to Args)
Function::Function(const std::string &symbol, const std::vector
<std::string> ¶ms, const node_manager &manager) :
_symbol(symbol), _params(params),
_manager(manager), _threads(1), Token(&Function::mtable) {}
Function::Function(const Function &other) :
_symbol(other._symbol), _params(other._params),
_manager(other._manager), _threads(1),
Token(&Function::mtable) {}
// Getters
bool Function::is_variable(const std::string &str) const
{
return std::find(_params.begin(), _params.end(), str)
!= _params.end();
}
std::string &Function::symbol()
{
return _symbol;
}
const std::string Function::symbol() const
{
return _symbol;
}
void Function::set_threads(size_t threads)
{
_threads = threads;
}
// Computational utilities
Token *Function::evaluate(Engine *ctx, const std::vector<Token *> &ins)
{
// TODO: refactor params to args
// TODO: create an assert macro (or constexpr) thats throws
if (ins.size() != _params.size())
throw Functor::insufficient_args(ins.size(), _params.size());
return _manager.substitute_and_compute(ctx, ins);
}
// TODO: useless
Token *Function::compute(const std::vector <Token *> &ins, Engine *ctx)
{
if (ins.size() != _params.size())
throw Functor::insufficient_args(ins.size(), _params.size());
return _manager.substitute_and_compute(ctx, ins);
}
// TODO: remove this (no user is going to use this)
Token *Function::operator()(const std::vector <Token *> &toks, Engine *context)
{
return compute(toks, context);
}
template <class ... A>
Token *Function::derivative(const std::string &str, A ... args)
{
std::vector <Token *> Tokens;
gather(Tokens, args...);
assert(Tokens.size() == _params.size());
size_t i = index(str);
assert(i != -1);
// Right
Token *right;
Tokens[i] = detail::compute("+", {Tokens[i], new Operand <double> (h)});
for (size_t k = 0; k < Tokens.size(); k++) {
if (k != i)
Tokens[k] = Tokens[k]->copy();
}
right = _manager.substitute_and_compute(shared_context, Tokens);
// Left
Token *left;
Tokens[i] = detail::compute("-", {Tokens[i], new Operand <double> (2.0 * h)});
for (size_t k = 0; k < Tokens.size(); k++) {
if (k != i)
Tokens[k] = Tokens[k]->copy();
}
left = _manager.substitute_and_compute(shared_context, Tokens);
// Compute
Token *diff = detail::compute("-", {right, left});
diff = detail::compute("/", {diff, new Operand <double> (2.0 * h)});
return diff;
}
Function Function::differentiate(const std::string &str) const
{
// Improve naming later
std::string name = "d" + _symbol + "/d" + str;
node_manager dm = _manager;
dm.differentiate(str);
Function df = Function(name, _params, dm);
return df;
}
// Virtual functions
Token::type Function::caller() const
{
return Token::ftn;
}
std::string Function::dbg_str() const
{
return display();
}
Token *Function::copy() const
{
return new Function(*this);
}
bool Function::operator==(Token *tptr) const
{
Function *ftn = dynamic_cast <Function *> (tptr);
if (!ftn)
return false;
return ftn->_symbol == _symbol;
}
// Printing utilities
void Function::print() const
{
_manager.print();
}
std::string Function::display() const
{
std::string str = _symbol + "(";
size_t n = _params.size();
for (size_t i = 0; i < n; i++) {
str += _params[i];
if (i < n - 1)
str += ", ";
}
str += ") = " + _manager.display();
return str;
}
std::ostream &operator<<(std::ostream &os, const Function &ftr)
{
os << ftr.display();
return os;
}
// Comparing
bool operator<(const Function &a, const Function &b)
{
return a.symbol() < b.symbol();
}
bool operator>(const Function &a, const Function &b)
{
return a.symbol() > b.symbol();
}
size_t Function::index(const std::string &str) const
{
auto itr = std::find(_params.begin(), _params.end(), str);
if (itr == _params.end())
return -1;
return std::distance(_params.begin(), itr);
}
}
| 19.769231 | 88 | 0.645266 |
21a19ad1a17a1917353ab7501f275153fac025e1 | 20,888 | cc | C++ | src/benchmark.cc | mtrofin/benchmark | 99cfbdd53357477fb328aa54d271178911bd2a84 | [
"Apache-2.0"
] | null | null | null | src/benchmark.cc | mtrofin/benchmark | 99cfbdd53357477fb328aa54d271178911bd2a84 | [
"Apache-2.0"
] | null | null | null | src/benchmark.cc | mtrofin/benchmark | 99cfbdd53357477fb328aa54d271178911bd2a84 | [
"Apache-2.0"
] | null | null | null | // Copyright 2015 Google Inc. 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 "benchmark/benchmark.h"
#include "benchmark_api_internal.h"
#include "benchmark_runner.h"
#include "internal_macros.h"
#ifndef BENCHMARK_OS_WINDOWS
#ifndef BENCHMARK_OS_FUCHSIA
#include <sys/resource.h>
#endif
#include <sys/time.h>
#include <unistd.h>
#endif
#include <algorithm>
#include <atomic>
#include <condition_variable>
#include <cstdio>
#include <cstdlib>
#include <fstream>
#include <iostream>
#include <limits>
#include <map>
#include <memory>
#include <random>
#include <string>
#include <thread>
#include <utility>
#include "absl/flags/flag.h"
#include "absl/flags/parse.h"
#include "absl/synchronization/mutex.h"
#include "check.h"
#include "colorprint.h"
#include "commandlineflags.h"
#include "complexity.h"
#include "counter.h"
#include "internal_macros.h"
#include "log.h"
#include "mutex.h"
#include "perf_counters.h"
#include "re.h"
#include "statistics.h"
#include "string_util.h"
#include "thread_manager.h"
#include "thread_timer.h"
ABSL_FLAG(
bool, benchmark_list_tests, false,
"Print a list of benchmarks. This option overrides all other options.");
ABSL_FLAG(std::string, benchmark_filter, ".",
"A regular expression that specifies the set of benchmarks to "
"execute. If this flag is empty, or if this flag is the string "
"\"all\", all benchmarks linked into the binary are run.");
ABSL_FLAG(
double, benchmark_min_time, 0.5,
"Minimum number of seconds we should run benchmark before results are "
"considered significant. For cpu-time based tests, this is the lower "
"bound on the total cpu time used by all threads that make up the test. "
"For real-time based tests, this is the lower bound on the elapsed time of "
"the benchmark execution, regardless of number of threads.");
ABSL_FLAG(int32_t, benchmark_repetitions, 1,
"The number of runs of each benchmark. If greater than 1, the mean "
"and standard deviation of the runs will be reported.");
ABSL_FLAG(
bool, benchmark_enable_random_interleaving, false,
"If set, enable random interleaving of repetitions of all benchmarks. See "
"http://github.com/google/benchmark/issues/1051 for details.");
ABSL_FLAG(bool, benchmark_report_aggregates_only, false,
"Report the result of each benchmark repetitions. When 'true' is "
"specified only the mean, standard deviation, and other statistics "
"are reported for repeated benchmarks. Affects all reporters.");
ABSL_FLAG(
bool, benchmark_display_aggregates_only, false,
"Display the result of each benchmark repetitions. When 'true' is "
"specified only the mean, standard deviation, and other statistics are "
"displayed for repeated benchmarks. Unlike "
"benchmark_report_aggregates_only, only affects the display reporter, but "
"*NOT* file reporter, which will still contain all the output.");
ABSL_FLAG(std::string, benchmark_format, "console",
"The format to use for console output. Valid values are 'console', "
"'json', or 'csv'.");
ABSL_FLAG(std::string, benchmark_out_format, "json",
"The format to use for file output. Valid values are 'console', "
"'json', or 'csv'.");
ABSL_FLAG(std::string, benchmark_out, "",
"The file to write additional output to.");
ABSL_FLAG(std::string, benchmark_color, "auto",
"Whether to use colors in the output. Valid values: 'true'/'yes'/1, "
"'false'/'no'/0, and 'auto'. 'auto' means to use colors if the "
"output is being sent to a terminal and the TERM environment "
"variable is set to a terminal type that supports colors.");
ABSL_FLAG(
bool, benchmark_counters_tabular, false,
"Whether to use tabular format when printing user counters to the console. "
"Valid values: 'true'/'yes'/1, 'false'/'no'/0. Defaults to false.");
ABSL_FLAG(int32_t, v, 0, "The level of verbose logging to output.");
ABSL_FLAG(std::vector<std::string>, benchmark_perf_counters, {},
"List of additional perf counters to collect, in libpfm format. For "
"more information about libpfm: "
"https://man7.org/linux/man-pages/man3/libpfm.3.html");
ABSL_FLAG(std::string, benchmark_context, "",
"Extra context to include in the output formatted as comma-separated "
"key-value pairs. Kept internal as it's only used for parsing from "
"env/command line.");
namespace benchmark {
namespace internal {
std::map<std::string, std::string>* global_context = nullptr;
// FIXME: wouldn't LTO mess this up?
void UseCharPointer(char const volatile*) {}
} // namespace internal
State::State(IterationCount max_iters, const std::vector<int64_t>& ranges,
int thread_i, int n_threads, internal::ThreadTimer* timer,
internal::ThreadManager* manager,
internal::PerfCountersMeasurement* perf_counters_measurement)
: total_iterations_(0),
batch_leftover_(0),
max_iterations(max_iters),
started_(false),
finished_(false),
error_occurred_(false),
range_(ranges),
complexity_n_(0),
counters(),
thread_index_(thread_i),
threads_(n_threads),
timer_(timer),
manager_(manager),
perf_counters_measurement_(perf_counters_measurement) {
BM_CHECK(max_iterations != 0) << "At least one iteration must be run";
BM_CHECK_LT(thread_index_, threads_)
<< "thread_index must be less than threads";
// Note: The use of offsetof below is technically undefined until C++17
// because State is not a standard layout type. However, all compilers
// currently provide well-defined behavior as an extension (which is
// demonstrated since constexpr evaluation must diagnose all undefined
// behavior). However, GCC and Clang also warn about this use of offsetof,
// which must be suppressed.
#if defined(__INTEL_COMPILER)
#pragma warning push
#pragma warning(disable : 1875)
#elif defined(__GNUC__)
#pragma GCC diagnostic push
#pragma GCC diagnostic ignored "-Winvalid-offsetof"
#endif
// Offset tests to ensure commonly accessed data is on the first cache line.
const int cache_line_size = 64;
static_assert(offsetof(State, error_occurred_) <=
(cache_line_size - sizeof(error_occurred_)),
"");
#if defined(__INTEL_COMPILER)
#pragma warning pop
#elif defined(__GNUC__)
#pragma GCC diagnostic pop
#endif
}
void State::PauseTiming() {
// Add in time accumulated so far
BM_CHECK(started_ && !finished_ && !error_occurred_);
timer_->StopTimer();
if (perf_counters_measurement_) {
auto measurements = perf_counters_measurement_->StopAndGetMeasurements();
for (const auto& name_and_measurement : measurements) {
auto name = name_and_measurement.first;
auto measurement = name_and_measurement.second;
BM_CHECK_EQ(counters[name], 0.0);
counters[name] = Counter(measurement, Counter::kAvgIterations);
}
}
}
void State::ResumeTiming() {
BM_CHECK(started_ && !finished_ && !error_occurred_);
timer_->StartTimer();
if (perf_counters_measurement_) {
perf_counters_measurement_->Start();
}
}
void State::SkipWithError(const char* msg) {
BM_CHECK(msg);
error_occurred_ = true;
{
MutexLock l(manager_->GetBenchmarkMutex());
if (manager_->results.has_error_ == false) {
manager_->results.error_message_ = msg;
manager_->results.has_error_ = true;
}
}
total_iterations_ = 0;
if (timer_->running()) timer_->StopTimer();
}
void State::SetIterationTime(double seconds) {
timer_->SetIterationTime(seconds);
}
void State::SetLabel(const char* label) {
MutexLock l(manager_->GetBenchmarkMutex());
manager_->results.report_label_ = label;
}
void State::StartKeepRunning() {
BM_CHECK(!started_ && !finished_);
started_ = true;
total_iterations_ = error_occurred_ ? 0 : max_iterations;
manager_->StartStopBarrier();
if (!error_occurred_) ResumeTiming();
}
void State::FinishKeepRunning() {
BM_CHECK(started_ && (!finished_ || error_occurred_));
if (!error_occurred_) {
PauseTiming();
}
// Total iterations has now wrapped around past 0. Fix this.
total_iterations_ = 0;
finished_ = true;
manager_->StartStopBarrier();
}
namespace internal {
namespace {
// Flushes streams after invoking reporter methods that write to them. This
// ensures users get timely updates even when streams are not line-buffered.
void FlushStreams(BenchmarkReporter* reporter) {
if (!reporter) return;
std::flush(reporter->GetOutputStream());
std::flush(reporter->GetErrorStream());
}
// Reports in both display and file reporters.
void Report(BenchmarkReporter* display_reporter,
BenchmarkReporter* file_reporter, const RunResults& run_results) {
auto report_one = [](BenchmarkReporter* reporter, bool aggregates_only,
const RunResults& results) {
assert(reporter);
// If there are no aggregates, do output non-aggregates.
aggregates_only &= !results.aggregates_only.empty();
if (!aggregates_only) reporter->ReportRuns(results.non_aggregates);
if (!results.aggregates_only.empty())
reporter->ReportRuns(results.aggregates_only);
};
report_one(display_reporter, run_results.display_report_aggregates_only,
run_results);
if (file_reporter)
report_one(file_reporter, run_results.file_report_aggregates_only,
run_results);
FlushStreams(display_reporter);
FlushStreams(file_reporter);
}
void RunBenchmarks(const std::vector<BenchmarkInstance>& benchmarks,
BenchmarkReporter* display_reporter,
BenchmarkReporter* file_reporter) {
// Note the file_reporter can be null.
BM_CHECK(display_reporter != nullptr);
// Determine the width of the name field using a minimum width of 10.
bool might_have_aggregates = absl::GetFlag(FLAGS_benchmark_repetitions) > 1;
size_t name_field_width = 10;
size_t stat_field_width = 0;
for (const BenchmarkInstance& benchmark : benchmarks) {
name_field_width =
std::max<size_t>(name_field_width, benchmark.name().str().size());
might_have_aggregates |= benchmark.repetitions() > 1;
for (const auto& Stat : benchmark.statistics())
stat_field_width = std::max<size_t>(stat_field_width, Stat.name_.size());
}
if (might_have_aggregates) name_field_width += 1 + stat_field_width;
// Print header here
BenchmarkReporter::Context context;
context.name_field_width = name_field_width;
// Keep track of running times of all instances of each benchmark family.
std::map<int /*family_index*/, BenchmarkReporter::PerFamilyRunReports>
per_family_reports;
if (display_reporter->ReportContext(context) &&
(!file_reporter || file_reporter->ReportContext(context))) {
FlushStreams(display_reporter);
FlushStreams(file_reporter);
size_t num_repetitions_total = 0;
std::vector<internal::BenchmarkRunner> runners;
runners.reserve(benchmarks.size());
for (const BenchmarkInstance& benchmark : benchmarks) {
BenchmarkReporter::PerFamilyRunReports* reports_for_family = nullptr;
if (benchmark.complexity() != oNone)
reports_for_family = &per_family_reports[benchmark.family_index()];
runners.emplace_back(benchmark, reports_for_family);
int num_repeats_of_this_instance = runners.back().GetNumRepeats();
num_repetitions_total += num_repeats_of_this_instance;
if (reports_for_family)
reports_for_family->num_runs_total += num_repeats_of_this_instance;
}
assert(runners.size() == benchmarks.size() && "Unexpected runner count.");
std::vector<size_t> repetition_indices;
repetition_indices.reserve(num_repetitions_total);
for (size_t runner_index = 0, num_runners = runners.size();
runner_index != num_runners; ++runner_index) {
const internal::BenchmarkRunner& runner = runners[runner_index];
std::fill_n(std::back_inserter(repetition_indices),
runner.GetNumRepeats(), runner_index);
}
assert(repetition_indices.size() == num_repetitions_total &&
"Unexpected number of repetition indexes.");
if (absl::GetFlag(FLAGS_benchmark_enable_random_interleaving)) {
std::random_device rd;
std::mt19937 g(rd());
std::shuffle(repetition_indices.begin(), repetition_indices.end(), g);
}
for (size_t repetition_index : repetition_indices) {
internal::BenchmarkRunner& runner = runners[repetition_index];
runner.DoOneRepetition();
if (runner.HasRepeatsRemaining()) continue;
// FIXME: report each repetition separately, not all of them in bulk.
RunResults run_results = runner.GetResults();
// Maybe calculate complexity report
if (const auto* reports_for_family = runner.GetReportsForFamily()) {
if (reports_for_family->num_runs_done ==
reports_for_family->num_runs_total) {
auto additional_run_stats = ComputeBigO(reports_for_family->Runs);
run_results.aggregates_only.insert(run_results.aggregates_only.end(),
additional_run_stats.begin(),
additional_run_stats.end());
per_family_reports.erase(
(int)reports_for_family->Runs.front().family_index);
}
}
Report(display_reporter, file_reporter, run_results);
}
}
display_reporter->Finalize();
if (file_reporter) file_reporter->Finalize();
FlushStreams(display_reporter);
FlushStreams(file_reporter);
}
// Disable deprecated warnings temporarily because we need to reference
// CSVReporter but don't want to trigger -Werror=-Wdeprecated-declarations
#ifdef __GNUC__
#pragma GCC diagnostic push
#pragma GCC diagnostic ignored "-Wdeprecated-declarations"
#endif
std::unique_ptr<BenchmarkReporter> CreateReporter(
std::string const&& name, ConsoleReporter::OutputOptions output_opts) {
typedef std::unique_ptr<BenchmarkReporter> PtrType;
if (name == "console") {
return PtrType(new ConsoleReporter(output_opts));
} else if (name == "json") {
return PtrType(new JSONReporter);
} else if (name == "csv") {
return PtrType(new CSVReporter);
} else {
std::cerr << "Unexpected format: '" << name << "'\n";
std::exit(1);
}
}
#ifdef __GNUC__
#pragma GCC diagnostic pop
#endif
} // end namespace
bool IsZero(double n) {
return std::abs(n) < std::numeric_limits<double>::epsilon();
}
ConsoleReporter::OutputOptions GetOutputOptions(bool force_no_color) {
int output_opts = ConsoleReporter::OO_Defaults;
auto is_benchmark_color = [force_no_color]() -> bool {
if (force_no_color) {
return false;
}
if (absl::GetFlag(FLAGS_benchmark_color) == "auto") {
return IsColorTerminal();
}
return IsTruthyFlagValue(absl::GetFlag(FLAGS_benchmark_color));
};
if (is_benchmark_color()) {
output_opts |= ConsoleReporter::OO_Color;
} else {
output_opts &= ~ConsoleReporter::OO_Color;
}
if (absl::GetFlag(FLAGS_benchmark_counters_tabular)) {
output_opts |= ConsoleReporter::OO_Tabular;
} else {
output_opts &= ~ConsoleReporter::OO_Tabular;
}
return static_cast<ConsoleReporter::OutputOptions>(output_opts);
}
} // end namespace internal
size_t RunSpecifiedBenchmarks() {
return RunSpecifiedBenchmarks(nullptr, nullptr);
}
size_t RunSpecifiedBenchmarks(BenchmarkReporter* display_reporter) {
return RunSpecifiedBenchmarks(display_reporter, nullptr);
}
size_t RunSpecifiedBenchmarks(BenchmarkReporter* display_reporter,
BenchmarkReporter* file_reporter) {
std::string spec = absl::GetFlag(FLAGS_benchmark_filter);
if (spec.empty() || spec == "all")
spec = "."; // Regexp that matches all benchmarks
// Setup the reporters
std::ofstream output_file;
std::unique_ptr<BenchmarkReporter> default_display_reporter;
std::unique_ptr<BenchmarkReporter> default_file_reporter;
if (!display_reporter) {
default_display_reporter = internal::CreateReporter(
absl::GetFlag(FLAGS_benchmark_format), internal::GetOutputOptions());
display_reporter = default_display_reporter.get();
}
auto& Out = display_reporter->GetOutputStream();
auto& Err = display_reporter->GetErrorStream();
const std::string fname = absl::GetFlag(FLAGS_benchmark_out);
if (fname.empty() && file_reporter) {
Err << "A custom file reporter was provided but "
"--benchmark_out=<file> was not specified."
<< std::endl;
std::exit(1);
}
if (!fname.empty()) {
output_file.open(fname);
if (!output_file.is_open()) {
Err << "invalid file name: '" << fname << "'" << std::endl;
std::exit(1);
}
if (!file_reporter) {
default_file_reporter = internal::CreateReporter(
absl::GetFlag(FLAGS_benchmark_out_format), ConsoleReporter::OO_None);
file_reporter = default_file_reporter.get();
}
file_reporter->SetOutputStream(&output_file);
file_reporter->SetErrorStream(&output_file);
}
std::vector<internal::BenchmarkInstance> benchmarks;
if (!FindBenchmarksInternal(spec, &benchmarks, &Err)) return 0;
if (benchmarks.empty()) {
Err << "Failed to match any benchmarks against regex: " << spec << "\n";
return 0;
}
if (absl::GetFlag(FLAGS_benchmark_list_tests)) {
for (auto const& benchmark : benchmarks)
Out << benchmark.name().str() << "\n";
} else {
internal::RunBenchmarks(benchmarks, display_reporter, file_reporter);
}
return benchmarks.size();
}
void RegisterMemoryManager(MemoryManager* manager) {
internal::memory_manager = manager;
}
void AddCustomContext(const std::string& key, const std::string& value) {
if (internal::global_context == nullptr) {
internal::global_context = new std::map<std::string, std::string>();
}
if (!internal::global_context->emplace(key, value).second) {
std::cerr << "Failed to add custom context \"" << key << "\" as it already "
<< "exists with value \"" << value << "\"\n";
}
}
namespace internal {
void PrintUsageAndExit() {
fprintf(stdout,
"benchmark"
" [--benchmark_list_tests={true|false}]\n"
" [--benchmark_filter=<regex>]\n"
" [--benchmark_min_time=<min_time>]\n"
" [--benchmark_repetitions=<num_repetitions>]\n"
" [--benchmark_enable_random_interleaving={true|false}]\n"
" [--benchmark_report_aggregates_only={true|false}]\n"
" [--benchmark_display_aggregates_only={true|false}]\n"
" [--benchmark_format=<console|json|csv>]\n"
" [--benchmark_out=<filename>]\n"
" [--benchmark_out_format=<json|console|csv>]\n"
" [--benchmark_color={auto|true|false}]\n"
" [--benchmark_counters_tabular={true|false}]\n"
" [--benchmark_perf_counters=<counter>,...]\n"
" [--benchmark_context=<key>=<value>,...]\n"
" [--v=<verbosity>]\n");
exit(0);
}
void ValidateCommandLineFlags() {
for (auto const& flag : {absl::GetFlag(FLAGS_benchmark_format),
absl::GetFlag(FLAGS_benchmark_out_format)}) {
if (flag != "console" && flag != "json" && flag != "csv") {
PrintUsageAndExit();
}
}
if (absl::GetFlag(FLAGS_benchmark_color).empty()) {
PrintUsageAndExit();
}
for (const auto& kv : benchmark::KvPairsFromEnv(
absl::GetFlag(FLAGS_benchmark_context).c_str(), {})) {
AddCustomContext(kv.first, kv.second);
}
}
int InitializeStreams() {
static std::ios_base::Init init;
return 0;
}
} // end namespace internal
std::vector<char*> Initialize(int* argc, char** argv) {
using namespace benchmark;
BenchmarkReporter::Context::executable_name =
(argc && *argc > 0) ? argv[0] : "unknown";
auto unparsed = absl::ParseCommandLine(*argc, argv);
*argc = static_cast<int>(unparsed.size());
benchmark::internal::ValidateCommandLineFlags();
internal::LogLevel() = absl::GetFlag(FLAGS_v);
return unparsed;
}
void Shutdown() {
delete internal::global_context;
}
} // end namespace benchmark
| 35.463497 | 80 | 0.69121 |
21a1cda08013be1fd44ffd020a1b22fb404d3906 | 23,941 | cpp | C++ | ofApp.cpp | sj-magic-collab-momoioki/Restoration | 848b9317f0f64fc6dbbd6baa228ac4c23d52317e | [
"MIT"
] | null | null | null | ofApp.cpp | sj-magic-collab-momoioki/Restoration | 848b9317f0f64fc6dbbd6baa228ac4c23d52317e | [
"MIT"
] | null | null | null | ofApp.cpp | sj-magic-collab-momoioki/Restoration | 848b9317f0f64fc6dbbd6baa228ac4c23d52317e | [
"MIT"
] | null | null | null | /************************************************************
************************************************************/
#include "ofApp.h"
/************************************************************
************************************************************/
/******************************
******************************/
ofApp::ofApp(bool _b_Play_EnjoyingMusic)
: Mask_Scan(MASK_SCAN::getInstance())
, Mask_Invert(MASK_INVERT::getInstance())
, Mask_Random(MASK_RANDOM::getInstance())
, Mask_Rapair(MASK_REPAIR::getInstance())
, State(STATE__REPAIRED)
, b_Start(true)
, t_from(0) // Boot直後は、key inputでstart.
, d_DispPos_to_Center(1.0)
, png_id(0)
, t_LastINT(0)
, b_Play_EnjoyingMusic(_b_Play_EnjoyingMusic)
{
fp_Log = fopen("../../../data/Log.csv", "w");
font[FONT_S].load("font/RictyDiminished-Regular.ttf", 13, true, true, true);
font[FONT_M].load("font/RictyDiminished-Regular.ttf", 14, true, true, true);
font[FONT_L].load("font/RictyDiminished-Regular.ttf", 18, true, true, true);
}
/******************************
******************************/
ofApp::~ofApp()
{
if(fp_Log) fclose(fp_Log);
}
/******************************
******************************/
void ofApp::exit(){
Mask_Scan->exit();
Mask_Invert->exit();
Mask_Random->exit();
Mask_Rapair->exit();
}
/******************************
******************************/
void ofApp::setup(){
/********************
********************/
ofSetWindowTitle("Restoration");
ofSetWindowShape( WINDOW_WIDTH, WINDOW_HEIGHT );
ofSetVerticalSync(true);
ofSetFrameRate(60);
ofSetEscapeQuitsApp(false);
/********************
********************/
setup_Gui();
set_dEnjoy();
/********************
********************/
for(int i = 0; i < NUM_FBOS_L; i++) { fbo_L[i].allocate(FBO_L_WIDTH, FBO_L_HEIGHT, GL_RGBA); }
for(int i = 0; i < NUM_FBOS_S; i++) {
fbo_S[i].allocate(BLOCK_SIZE, BLOCK_SIZE, GL_RGBA);
}
pix_image.allocate(BLOCK_SIZE, BLOCK_SIZE, GL_RGBA);
myGlitch.setup(&fbo_L[FBO__OUTPUT]);
/********************
********************/
image.load("image/momoi.png");
drawFbo_org();
/********************
********************/
Mask_Scan->setup();
Mask_Invert->setup();
Mask_Random->setup();
Mask_Rapair->setup();
/********************
********************/
/* */
setup_sound(sound_Ambient[0], "sound/main/airplane.wav", true, 0.6);
sound_Ambient[0].play();
setup_sound(sound_Ambient[1], "sound/main/electrocardiogram_Loop.mp3", true, 1.0);
sound_Ambient[1].play();
/* */
setup_sound(sound_Pi, "sound/main/Cash_Register-Beep01-1.mp3", false, 0.8);
setup_sound(sound_MoveToCenter, "sound/main/AutoDoor.mp3", false, 0.7);
/* */
setup_sound(sound_Enjoying, "sound/main/Enjoy/bbc-051117-Smoky-Jazz-Music-Full-Mix.mp3", true, 0.0);
if(b_Play_EnjoyingMusic) sound_Enjoying.play();
setup_sound(sound_Noise, "sound/main/radio-tuning-noise-short-waves_zydE-HEd.mp3", true, 0.0);
sound_Noise.play();
/********************
********************/
shader_Mask.load( "sj_shader/mask.vert", "sj_shader/mask.frag");
shader_Invert.load( "sj_shader/invert.vert", "sj_shader/invert.frag");
/********************
********************/
FboReader.setAsync(false); // true/ false の違いはよくわからない.
/********************
********************/
ofSleepMillis(100);
}
/******************************
******************************/
void ofApp::set_dEnjoy()
{
d_Enjoy = ofRandom(30, 35);
}
/******************************
******************************/
void ofApp::setup_sound(ofSoundPlayer& sound, string FileName, bool b_Loop, float vol)
{
sound.load(FileName.c_str());
if(sound.isLoaded()){
sound.setLoop(b_Loop);
sound.setMultiPlay(true);
sound.setVolume(vol);
}else{
printf("%s load Error\n", FileName.c_str());
fflush(stdout);
}
}
/******************************
description
memoryを確保は、app start後にしないと、
segmentation faultになってしまった。
******************************/
void ofApp::setup_Gui()
{
/********************
********************/
Gui_Global = new GUI_GLOBAL;
Gui_Global->setup("Void", "gui.xml", 1000, 10);
}
/******************************
******************************/
void ofApp::update(){
/********************
********************/
ofSoundUpdate();
/********************
********************/
float now = ofGetElapsedTimef();
/********************
********************/
Mask_Scan->update(now);
Mask_Invert->update(now);
Mask_Random->update(now);
Mask_Rapair->update(now);
/********************
********************/
StateChart(now);
/*
printf("State = %d\r", State);
fflush(stdout);
*/
printf("%5.2f\r", ofGetFrameRate());
fflush(stdout);
/********************
********************/
t_LastINT = now;
}
/******************************
******************************/
void ofApp::StateChart(float now)
{
/********************
********************/
float Vol = sound_Enjoying.getVolume();
const float VolFade_Speed = 0.2;
if( (State == STATE__REPAIRED) || (State == STATE__REPAIRED_GLITCH) ){
Vol += VolFade_Speed * (now - t_LastINT);
if(1.0 < Vol) Vol = 1.0;
}else{
Vol -= VolFade_Speed * (now - t_LastINT);
if(Vol < 0) Vol = 0.0;
}
sound_Enjoying.setVolume(Vol);
/********************
********************/
float t = float(ofGetElapsedTimeMillis()) / 1.0e+3;
float perlin = ofNoise(t);
const float perlinThresh_Repaired = 0.35;
const float perlinThresh_Repairing = 0.3;
const float vol_Noise = 0.7;
/********************
********************/
switch(State){
case STATE__REPAIRED:
{
if(b_Start && (d_Enjoy < now - t_from)){
State_To_Glitching(now);
}else if(perlin < perlinThresh_Repaired){
State = STATE__REPAIRED_GLITCH;
sound_Noise.setVolume(vol_Noise);
L_UTIL::FisherYates(Glitch_Ids, NUM_GLITCH_TYPES);
NumGlitch_Enable = int(ofRandom(1, MAX_NUM_GLITCHS_ONE_TIME));
for(int i = 0; i < NumGlitch_Enable; i++) { Set_myGlitch(Glitch_Ids[i], true); }
}
}
break;
case STATE__REPAIRED_GLITCH:
{
if(b_Start && (d_Enjoy < now - t_from)){
State_To_Glitching(now);
}else if(perlinThresh_Repaired <= perlin){
State = STATE__REPAIRED;
sound_Noise.setVolume(0.0);
// for(int i = 0; i < NumGlitch_Enable; i++) { Set_myGlitch(Glitch_Ids[i], false); }
Clear_AllGlitch();
}
}
break;
case STATE__GLITCHING:
if(Mask_Invert->IsState_Interval()){
State = STATE__DELETING;
Mask_Rapair->Delete(now);
// sound_Enjoying.setPaused(true);
}
break;
case STATE__DELETING:
if(Mask_Rapair->IsState_Deleted()){
State = STATE__WAIT_AFTER_DELETE;
t_from = now;
}
break;
case STATE__WAIT_AFTER_DELETE:
if(3.5 < now - t_from){
State = STATE__PREP_FOR_SCAN;
t_from = now;
sound_Pi.play();
}
break;
case STATE__PREP_FOR_SCAN:
if(2.0 < now - t_from){
State = STATE__SCANNING;
Mask_Scan->LateRun(true, now);
}
break;
case STATE__SCANNING:
if(Mask_Scan->IsState_Interval()){
State = STATE__REPAIRING;
Mask_Rapair->Rapair(now);
Mask_Invert->LateRun(false, now);
Mask_Random->LateRun(false, now);
t_from = now;
sound_Noise.play();
sound_Noise.setVolume(0.0);
}
break;
case STATE__REPAIRING:
if(Mask_Rapair->IsState_Repaired()){
State_To_Fin(now);
}else if(perlin < perlinThresh_Repairing){
State = STATE__REPAIRING_GLITCH;
sound_Noise.setVolume(vol_Noise);
L_UTIL::FisherYates(Glitch_Ids, NUM_GLITCH_TYPES);
NumGlitch_Enable = int(ofRandom(1, MAX_NUM_GLITCHS_ONE_TIME));
for(int i = 0; i < NumGlitch_Enable; i++) { Set_myGlitch(Glitch_Ids[i], true); }
}
break;
case STATE__REPAIRING_GLITCH:
if(Mask_Rapair->IsState_Repaired()){
State_To_Fin(now);
}else if(perlinThresh_Repairing <= perlin){
State = STATE__REPAIRING;
sound_Noise.setVolume(0.0);
Clear_AllGlitch();
}
break;
case STATE__FIN:
if( (Mask_Scan->IsState_Sleep()) && (Mask_Random->IsState_Sleep()) && (Mask_Invert->IsState_Sleep()) & (1.0 < now - t_from) ){
State = STATE__TO_CENTER;
t_from = now;
DispPos_ToCenter = DispPos__Left;
sound_MoveToCenter.play();
}
break;
case STATE__TO_CENTER:
{
if(d_DispPos_to_Center <= now - t_from){
State = STATE__REPAIRED;
t_from = now;
sound_Noise.play();
sound_Noise.setVolume(0.0);
// sound_Enjoying.setPaused(false);
set_dEnjoy();
}else{
float ratio = (now - t_from) / d_DispPos_to_Center;
DispPos_ToCenter = DispPos__Left + (DispPos__Center - DispPos__Left) * ratio;
}
}
break;
}
}
/******************************
******************************/
void ofApp::State_To_Glitching(float now){
State = STATE__GLITCHING;
Mask_Invert->Run(true, now);
sound_Noise.stop();
Clear_AllGlitch();
}
/******************************
******************************/
void ofApp::State_To_Fin(float now){
State = STATE__FIN;
Mask_Scan->Sleep();
Mask_Random->Sleep();
Mask_Invert->Sleep();
t_from = now;
sound_Noise.stop();
Clear_AllGlitch();
}
/******************************
******************************/
void ofApp::draw(){
/********************
********************/
Mask_Scan->drawToFbo(fbo_L[FBO__SCAN]);
Mask_Invert->drawToFbo(fbo_L[FBO__GLITCH_INVERT]);
Mask_Random->drawToFbo(fbo_L[FBO__GLITCH_RANDOM]);
Mask_Rapair->drawToFbo(fbo_L[FBO__REPAIRED]);
/********************
********************/
drawFbo_masked();
drawFbo_Inverted();
if(State == STATE__REPAIRING){
drawFbo_PartsOfOrg(fbo_S[FBO__BLOCK_TARGET], Mask_Rapair->get_Target_pos_LeftUp());
drawFbo_PartsOfOrg(fbo_S[FBO__BLOCK_MOVE], Mask_Rapair->get_Cross_pos_LeftUp());
}
/********************
********************/
myGlitch.generateFx(); // Apply effects
/********************
********************/
// ofClear(0);
ofBackground(0, 0, 0, 255);
ofSetColor(255, 255, 255, 255);
switch(State){
case STATE__REPAIRED:
case STATE__REPAIRED_GLITCH:
case STATE__GLITCHING:
case STATE__DELETING:
if(State == STATE__REPAIRED_GLITCH){
ofSetColor(50);
ofDrawRectangle(0, 0, ofGetWidth(), ofGetHeight());
}
ofSetColor(255, 255, 255, 255);
draw_FboToScreen(fbo_L[FBO__OUTPUT], fbo_L[FBO__OUTPUT].getWidth(), fbo_L[FBO__OUTPUT].getHeight(), DispPos__Center);
break;
case STATE__WAIT_AFTER_DELETE:
break;
case STATE__PREP_FOR_SCAN:
draw_Scale();
break;
case STATE__SCANNING:
draw_Scale();
draw_FboToScreen(fbo_L[FBO__OUTPUT], fbo_L[FBO__OUTPUT].getWidth(), fbo_L[FBO__OUTPUT].getHeight(), DispPos__Left);
break;
case STATE__REPAIRING:
case STATE__REPAIRING_GLITCH:
draw_Scale();
/* */
draw_FboToScreen(fbo_L[FBO__OUTPUT], fbo_L[FBO__OUTPUT].getWidth(), fbo_L[FBO__OUTPUT].getHeight(), DispPos__Left);
// draw_Fbo_Ovelay(fbo_L[FBO__GLITCH_INVERT], DispPos__Left, 30);
draw_Fbo_Ovelay(fbo_L[FBO__GLITCH_RANDOM], DispPos__Left, 80);
draw_Fbo_Ovelay(fbo_L[FBO__SCAN], DispPos__Left, 40);
draw_NextRepairingTarget(DispPos__Left);
draw_RepairingCursor(DispPos__Left);
draw_FboToScreen(fbo_S[FBO__BLOCK_MOVE], BLOCK_DRAW_SIZE, BLOCK_DRAW_SIZE, DispPos__Right_Left);
draw_FboToScreen(fbo_S[FBO__BLOCK_TARGET], BLOCK_DRAW_SIZE, BLOCK_DRAW_SIZE, DispPos__Right_Right);
drawText_CrossPos();
drawText_RGB(fbo_S[FBO__BLOCK_MOVE], ofVec2f(DispPos__Right_Left.x, 500), false);
drawText_RGB(fbo_S[FBO__BLOCK_TARGET], ofVec2f(DispPos__Right_Right.x, 500), false);
drawText_Progress();
break;
case STATE__FIN:
draw_Scale();
draw_FboToScreen(fbo_L[FBO__OUTPUT], fbo_L[FBO__OUTPUT].getWidth(), fbo_L[FBO__OUTPUT].getHeight(), DispPos__Left);
break;
case STATE__TO_CENTER:
draw_FboToScreen(fbo_L[FBO__OUTPUT], fbo_L[FBO__OUTPUT].getWidth(), fbo_L[FBO__OUTPUT].getHeight(), DispPos_ToCenter);
break;
}
}
/******************************
******************************/
void ofApp::drawText_Progress()
{
Mask_Rapair->get_Progress();
int get_NumPieces();
/********************
********************/
ofEnableAlphaBlending();
// ofEnableBlendMode(OF_BLENDMODE_ADD);
ofEnableBlendMode(OF_BLENDMODE_ALPHA);
/********************
********************/
char buf[BUF_SIZE_S];
ofSetColor(255, 255, 255, 100);
/* */
sprintf(buf, "%5d/%5d %5.0f[s]", Mask_Rapair->get_Progress(), Mask_Rapair->get_NumPieces(), ofGetElapsedTimef() - t_from);
font[FONT_M].drawString(buf, DispPos__Right_Left.x + BLOCK_DRAW_SIZE - font[FONT_M].stringWidth("xxxxx/xxxxx xxxxx[s]"), 450);
}
/******************************
******************************/
void ofApp::drawText_RGB(ofFbo& fbo, ofVec2f pos, bool b_DynamicColor)
{
/********************
********************/
ofEnableAlphaBlending();
// ofEnableBlendMode(OF_BLENDMODE_ADD);
ofEnableBlendMode(OF_BLENDMODE_ALPHA);
/********************
********************/
char buf[BUF_SIZE_S];
ofSetColor(255, 255, 255, 100);
/********************
********************/
const int NUM_LINES = 30;
const int NUM_PER_LINE = 4;
const int STEP_Y = font[FONT_S].stringHeight("FF FF FF") * 2.0;
const int STEP_X = font[FONT_S].stringWidth("FF FF FF") * 1.3;
fbo.readToPixels(pix_image);
// FboReader.readToPixels(fbo, pix_image); // 上手く読み取りできなかった(All zero)
ofPushMatrix();
ofTranslate(pos);
for(int _y = 0; _y < NUM_LINES; _y++){
for(int _x = 0; _x < NUM_PER_LINE; _x++){
ofColor col = pix_image.getColor(_x, _y);
sprintf(buf, "%02X %02X %02X", col.r, col.g, col.b);
if(b_DynamicColor) ofSetColor(col.r, col.g, col.b, 100);
else ofSetColor(255, 255, 255, 100);
font[FONT_S].drawString(buf, STEP_X * _x, STEP_Y * _y);
}
}
ofPopMatrix();
}
/******************************
******************************/
void ofApp::drawText_CrossPos()
{
/********************
********************/
ofEnableAlphaBlending();
// ofEnableBlendMode(OF_BLENDMODE_ADD);
ofEnableBlendMode(OF_BLENDMODE_ALPHA);
/********************
********************/
char buf[BUF_SIZE_S];
ofSetColor(255, 255, 255, 100);
/* */
ofVec2f pos = Mask_Rapair->get_Cross_pos();
sprintf(buf, "%4d, %4d", int(pos.x), int(pos.y));
font[FONT_L].drawString(buf, DispPos__Right_Left.x, 450);
/* */
pos = Mask_Rapair->get_Target_pos();
sprintf(buf, "%4d, %4d", int(pos.x), int(pos.y));
font[FONT_L].drawString(buf, DispPos__Right_Right.x, 450);
}
/******************************
******************************/
void ofApp::draw_Scale()
{
draw_Scale_x(ofVec2f(90, 0), ofVec2f(1, 1));
draw_Scale_x(ofVec2f(90, 1080), ofVec2f(1, -1));
draw_Scale_y(ofVec2f(45, 40), ofVec2f(1, 1));
draw_Scale_y(ofVec2f(935, 40), ofVec2f(-1, 1));
}
/******************************
******************************/
void ofApp::draw_Scale_x(ofVec2f _pos, ofVec2f _scale)
{
/********************
********************/
ofEnableAlphaBlending();
// ofEnableBlendMode(OF_BLENDMODE_ADD);
ofEnableBlendMode(OF_BLENDMODE_ALPHA);
ofSetColor(255, 255, 255, 150);
glPointSize(1.0);
// glLineWidth(1);
ofSetLineWidth(1);
/********************
********************/
const float step = 5;
ofPushMatrix();
ofTranslate(_pos);
ofScale(_scale.x, _scale.y);
int id;
float _x;
for(id = 0, _x = 0; _x < FBO_L_WIDTH; _x += step, id++){
if(id % 10 == 0) ofDrawLine(_x, 0, _x, 20);
else if(id % 5 == 0) ofDrawLine(_x, 0, _x, 15);
else ofDrawLine(_x, 0, _x, 10);
}
ofPopMatrix();
}
/******************************
******************************/
void ofApp::draw_Scale_y(ofVec2f _pos, ofVec2f _scale)
{
/********************
********************/
ofEnableAlphaBlending();
// ofEnableBlendMode(OF_BLENDMODE_ADD);
ofEnableBlendMode(OF_BLENDMODE_ALPHA);
ofSetColor(255, 255, 255, 150);
glPointSize(1.0);
// glLineWidth(1);
ofSetLineWidth(1);
/********************
********************/
const float step = 5;
ofPushMatrix();
ofTranslate(_pos);
ofScale(_scale.x, _scale.y);
int id;
float _y;
for(id = 0, _y = 0; _y < FBO_L_HEIGHT; _y += step, id++){
if(id % 10 == 0) ofDrawLine(0, _y, 20, _y);
else if(id % 5 == 0) ofDrawLine(0, _y, 15, _y);
else ofDrawLine(0, _y, 10, _y);
}
ofPopMatrix();
}
/******************************
******************************/
void ofApp::draw_Fbo_Ovelay(ofFbo& fbo, ofVec2f _pos, float alpha)
{
/********************
oFでは、加算合成とスムージングは同時に効かない。その為、加算合成の前にofDisableSmoothing()を記述。
https://qiita.com/y_UM4/items/b03a66d932536b25b51a
********************/
ofDisableSmoothing();
ofEnableAlphaBlending();
ofEnableBlendMode(OF_BLENDMODE_ADD);
// ofEnableBlendMode(OF_BLENDMODE_ALPHA);
ofSetColor(255, 255, 255, alpha);
/********************
********************/
ofPushMatrix();
ofPushStyle();
ofTranslate(_pos);
fbo.draw(0, 0, fbo.getWidth(), fbo.getHeight());
ofPopStyle();
ofPopMatrix();
}
/******************************
******************************/
void ofApp::draw_RepairingCursor(ofVec2f _pos)
{
/********************
oFでは、加算合成とスムージングは同時に効かない。その為、加算合成の前にofDisableSmoothing()を記述。
https://qiita.com/y_UM4/items/b03a66d932536b25b51a
********************/
// ofEnableSmoothing();
ofEnableAlphaBlending();
// ofEnableBlendMode(OF_BLENDMODE_ADD);
ofEnableBlendMode(OF_BLENDMODE_ALPHA);
ofSetColor(255, 255, 0, 100);
glPointSize(1.0);
// glLineWidth(1);
ofSetLineWidth(1);
/********************
********************/
ofPushMatrix();
ofPushStyle();
ofTranslate(_pos);
ofVec2f Cross = Mask_Rapair->get_Cross_pos();
ofDrawLine(0, Cross.y, fbo_L[FBO__REPAIRED].getWidth(), Cross.y);
ofDrawLine(Cross.x, 0, Cross.x, fbo_L[FBO__REPAIRED].getHeight());
ofPopStyle();
ofPopMatrix();
}
/******************************
******************************/
void ofApp::draw_NextRepairingTarget(ofVec2f _pos)
{
/********************
oFでは、加算合成とスムージングは同時に効かない。その為、加算合成の前にofDisableSmoothing()を記述。
https://qiita.com/y_UM4/items/b03a66d932536b25b51a
********************/
// ofEnableSmoothing();
ofEnableAlphaBlending();
// ofEnableBlendMode(OF_BLENDMODE_ADD);
ofEnableBlendMode(OF_BLENDMODE_ALPHA);
ofSetColor(255, 255, 255, 20);
ofFill();
glPointSize(1.0);
// glLineWidth(1);
ofSetLineWidth(1);
/********************
********************/
ofPushMatrix();
ofPushStyle();
ofTranslate(_pos);
ofVec2f LeftUp = Mask_Rapair->get_Target_pos_LeftUp();
ofDrawRectangle(LeftUp.x, LeftUp.y, BLOCK_SIZE, BLOCK_SIZE);
ofPopStyle();
ofPopMatrix();
}
/******************************
******************************/
void ofApp::draw_FboToScreen(ofFbo& fbo, float width, float height, ofVec2f _pos)
{
/********************
********************/
ofEnableAlphaBlending();
// ofEnableBlendMode(OF_BLENDMODE_ADD);
ofEnableBlendMode(OF_BLENDMODE_ALPHA);
ofSetColor(255, 255, 255, 255);
/********************
********************/
ofPushMatrix();
ofPushStyle();
ofTranslate(_pos);
fbo.draw(0, 0, width, height);
ofPopStyle();
ofPopMatrix();
}
/******************************
******************************/
void ofApp::drawFbo_org()
{
ofDisableAlphaBlending();
fbo_L[FBO__ORG].begin();
ofClear(0, 0, 0, 0);
ofSetColor(255, 255, 255, 255);
image.draw(0, 0, fbo_L[FBO__ORG].getWidth(), fbo_L[FBO__ORG].getHeight());
fbo_L[FBO__ORG].end();
}
/******************************
******************************/
void ofApp::drawFbo_masked()
{
ofDisableAlphaBlending();
fbo_L[FBO__MASKED].begin();
shader_Mask.begin();
ofClear(0, 0, 0, 0);
ofSetColor(255, 255, 255, 255);
shader_Mask.setUniformTexture( "mask_0", fbo_L[FBO__REPAIRED].getTexture(), 1 );
shader_Mask.setUniformTexture( "mask_1", fbo_L[FBO__SCAN].getTexture(), 2 );
shader_Mask.setUniformTexture( "mask_2", fbo_L[FBO__GLITCH_RANDOM].getTexture(), 3 );
fbo_L[FBO__ORG].draw(0, 0, fbo_L[FBO__ORG].getWidth(), fbo_L[FBO__ORG].getHeight());
shader_Mask.end();
fbo_L[FBO__MASKED].end();
}
/******************************
******************************/
void ofApp::drawFbo_Inverted()
{
ofDisableAlphaBlending();
fbo_L[FBO__OUTPUT].begin();
shader_Invert.begin();
ofClear(0, 0, 0, 0);
ofSetColor(255, 255, 255, 255);
shader_Invert.setUniformTexture( "mask", fbo_L[FBO__GLITCH_INVERT].getTexture(), 1 );
fbo_L[FBO__MASKED].draw(0, 0, fbo_L[FBO__OUTPUT].getWidth(), fbo_L[FBO__OUTPUT].getHeight());
shader_Invert.end();
fbo_L[FBO__OUTPUT].end();
}
/******************************
******************************/
void ofApp::drawFbo_PartsOfOrg(ofFbo& fbo, ofVec2f _pos)
{
ofDisableAlphaBlending();
fbo.begin();
ofPushMatrix();
ofTranslate(-_pos);
ofClear(0, 0, 0, 0);
ofSetColor(255, 255, 255, 255);
fbo_L[FBO__ORG].draw(0, 0, fbo_L[FBO__ORG].getWidth(), fbo_L[FBO__ORG].getHeight());
ofPopMatrix();
fbo.end();
}
/******************************
******************************/
void ofApp::Set_myGlitch(int key, bool b_switch)
{
if (key == 0) myGlitch.setFx(OFXPOSTGLITCH_INVERT , b_switch);
if (key == 1) myGlitch.setFx(OFXPOSTGLITCH_CONVERGENCE , b_switch);
if (key == 2) myGlitch.setFx(OFXPOSTGLITCH_GLOW , b_switch);
if (key == 3) myGlitch.setFx(OFXPOSTGLITCH_SHAKER , b_switch);
if (key == 4) myGlitch.setFx(OFXPOSTGLITCH_CUTSLIDER , b_switch);
if (key == 5) myGlitch.setFx(OFXPOSTGLITCH_TWIST , b_switch);
if (key == 6) myGlitch.setFx(OFXPOSTGLITCH_OUTLINE , b_switch);
if (key == 7) myGlitch.setFx(OFXPOSTGLITCH_NOISE , b_switch);
if (key == 8) myGlitch.setFx(OFXPOSTGLITCH_SLITSCAN , b_switch);
if (key == 9) myGlitch.setFx(OFXPOSTGLITCH_SWELL , b_switch);
if (key == 10) myGlitch.setFx(OFXPOSTGLITCH_CR_HIGHCONTRAST, b_switch);
if (key == 11) myGlitch.setFx(OFXPOSTGLITCH_CR_BLUERAISE , b_switch);
if (key == 12) myGlitch.setFx(OFXPOSTGLITCH_CR_REDRAISE , b_switch);
if (key == 13) myGlitch.setFx(OFXPOSTGLITCH_CR_GREENRAISE , b_switch);
if (key == 14) myGlitch.setFx(OFXPOSTGLITCH_CR_BLUEINVERT , b_switch);
if (key == 15) myGlitch.setFx(OFXPOSTGLITCH_CR_REDINVERT , b_switch);
if (key == 16) myGlitch.setFx(OFXPOSTGLITCH_CR_GREENINVERT , b_switch);
}
/******************************
******************************/
void ofApp::Clear_AllGlitch()
{
for(int i = 0; i < NUM_GLITCH_TYPES; i++){
Set_myGlitch(i, false);
}
}
/******************************
******************************/
void ofApp::keyPressed(int key){
switch(key){
case 'g':
b_Start = true;
break;
case ' ':
{
char buf[BUF_SIZE_S];
sprintf(buf, "image_%d.png", png_id);
ofSaveScreen(buf);
// ofSaveFrame();
printf("> %s saved\n", buf);
png_id++;
}
break;
/*
case '0':
Mask_Rapair->Delete(ofGetElapsedTimef());
break;
case '1':
Mask_Rapair->Rapair(ofGetElapsedTimef());
break;
*/
}
}
//--------------------------------------------------------------
void ofApp::keyReleased(int key){
}
//--------------------------------------------------------------
void ofApp::mouseMoved(int x, int y ){
}
//--------------------------------------------------------------
void ofApp::mouseDragged(int x, int y, int button){
}
//--------------------------------------------------------------
void ofApp::mousePressed(int x, int y, int button){
}
//--------------------------------------------------------------
void ofApp::mouseReleased(int x, int y, int button){
}
//--------------------------------------------------------------
void ofApp::mouseEntered(int x, int y){
}
//--------------------------------------------------------------
void ofApp::mouseExited(int x, int y){
}
//--------------------------------------------------------------
void ofApp::windowResized(int w, int h){
}
//--------------------------------------------------------------
void ofApp::gotMessage(ofMessage msg){
}
//--------------------------------------------------------------
void ofApp::dragEvent(ofDragInfo dragInfo){
}
| 25.174553 | 129 | 0.558039 |
426f8c942f3ef9d9433a3321aedf5ad1d7a5757f | 1,819 | cpp | C++ | ibp_external__libtommatch_set01__bn_mp_clamp.cpp | dmitry-lipetsk/libtommath-for-ibprovider--set01 | b7b8e7cf76bd0b2d265d0c31a99836a3b4bad882 | [
"WTFPL"
] | null | null | null | ibp_external__libtommatch_set01__bn_mp_clamp.cpp | dmitry-lipetsk/libtommath-for-ibprovider--set01 | b7b8e7cf76bd0b2d265d0c31a99836a3b4bad882 | [
"WTFPL"
] | null | null | null | ibp_external__libtommatch_set01__bn_mp_clamp.cpp | dmitry-lipetsk/libtommath-for-ibprovider--set01 | b7b8e7cf76bd0b2d265d0c31a99836a3b4bad882 | [
"WTFPL"
] | null | null | null | ////////////////////////////////////////////////////////////////////////////////
#include <_pch_.h>
#pragma hdrstop
#include "source/external/libtommath/set01/ibp_external__libtommatch_set01__tommath_private.h"
namespace ibp{namespace external{namespace libtommath{namespace set01{
////////////////////////////////////////////////////////////////////////////////
/* LibTomMath, multiple-precision integer library -- Tom St Denis
*
* LibTomMath is a library that provides multiple-precision
* integer arithmetic as well as number theoretic functionality.
*
* The library was designed directly after the MPI library by
* Michael Fromberger but has been written from scratch with
* additional optimizations in place.
*
* The library is free for all purposes without any express
* guarantee it works.
*
* Tom St Denis, tomstdenis@gmail.com, http://libtom.org
*/
/* trim unused digits
*
* This is used to ensure that leading zero digits are
* trimed and the leading "used" digit will be non-zero
* Typically very fast. Also fixes the sign if there
* are no more leading digits
*/
void mp_clamp(mp_int* const a)
{
DEBUG_CODE(mp_debug__check_int__light(a);)
// decrease used while the most significant digit is zero.
const mp_digit* p=(a->dp + a->used);
for(;;)
{
if(p == a->dp)
{
a->used = 0;
a->sign = MP_ZPOS;
DEBUG_CODE(mp_debug__check_int__total(a);)
return;
}//if
const mp_digit* const newP = (p - 1);
if((*newP) != 0)
break;
p = newP;
}//for[ever]
assert(p != a->dp);
assert(p >= a->dp);
assert(p <= (a->dp + a->used));
a->used = (p - a->dp);
DEBUG_CODE(mp_debug__check_int__total(a);)
}//mp_clamp
////////////////////////////////////////////////////////////////////////////////
}/*nms set01*/}/*nms libtommath*/}/*nms external*/}/*nms ibp*/
| 24.581081 | 94 | 0.601979 |
4272eab0047a8e82ba1850062b8318565e9f0b9d | 7,231 | cpp | C++ | live/src/v20180801/model/CreateLiveRecordRequest.cpp | li5ch/tencentcloud-sdk-cpp | 12ebfd75a399ee2791f6ac1220a79ce8a9faf7c4 | [
"Apache-2.0"
] | null | null | null | live/src/v20180801/model/CreateLiveRecordRequest.cpp | li5ch/tencentcloud-sdk-cpp | 12ebfd75a399ee2791f6ac1220a79ce8a9faf7c4 | [
"Apache-2.0"
] | null | null | null | live/src/v20180801/model/CreateLiveRecordRequest.cpp | li5ch/tencentcloud-sdk-cpp | 12ebfd75a399ee2791f6ac1220a79ce8a9faf7c4 | [
"Apache-2.0"
] | null | null | null | /*
* Copyright (c) 2017-2019 THL A29 Limited, a Tencent company. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include <tencentcloud/live/v20180801/model/CreateLiveRecordRequest.h>
#include <tencentcloud/core/utils/rapidjson/document.h>
#include <tencentcloud/core/utils/rapidjson/writer.h>
#include <tencentcloud/core/utils/rapidjson/stringbuffer.h>
using namespace TencentCloud::Live::V20180801::Model;
using namespace rapidjson;
using namespace std;
CreateLiveRecordRequest::CreateLiveRecordRequest() :
m_streamNameHasBeenSet(false),
m_appNameHasBeenSet(false),
m_domainNameHasBeenSet(false),
m_startTimeHasBeenSet(false),
m_endTimeHasBeenSet(false),
m_recordTypeHasBeenSet(false),
m_fileFormatHasBeenSet(false),
m_highlightHasBeenSet(false),
m_mixStreamHasBeenSet(false),
m_streamParamHasBeenSet(false)
{
}
string CreateLiveRecordRequest::ToJsonString() const
{
Document d;
d.SetObject();
Document::AllocatorType& allocator = d.GetAllocator();
if (m_streamNameHasBeenSet)
{
Value iKey(kStringType);
string key = "StreamName";
iKey.SetString(key.c_str(), allocator);
d.AddMember(iKey, Value(m_streamName.c_str(), allocator).Move(), allocator);
}
if (m_appNameHasBeenSet)
{
Value iKey(kStringType);
string key = "AppName";
iKey.SetString(key.c_str(), allocator);
d.AddMember(iKey, Value(m_appName.c_str(), allocator).Move(), allocator);
}
if (m_domainNameHasBeenSet)
{
Value iKey(kStringType);
string key = "DomainName";
iKey.SetString(key.c_str(), allocator);
d.AddMember(iKey, Value(m_domainName.c_str(), allocator).Move(), allocator);
}
if (m_startTimeHasBeenSet)
{
Value iKey(kStringType);
string key = "StartTime";
iKey.SetString(key.c_str(), allocator);
d.AddMember(iKey, Value(m_startTime.c_str(), allocator).Move(), allocator);
}
if (m_endTimeHasBeenSet)
{
Value iKey(kStringType);
string key = "EndTime";
iKey.SetString(key.c_str(), allocator);
d.AddMember(iKey, Value(m_endTime.c_str(), allocator).Move(), allocator);
}
if (m_recordTypeHasBeenSet)
{
Value iKey(kStringType);
string key = "RecordType";
iKey.SetString(key.c_str(), allocator);
d.AddMember(iKey, Value(m_recordType.c_str(), allocator).Move(), allocator);
}
if (m_fileFormatHasBeenSet)
{
Value iKey(kStringType);
string key = "FileFormat";
iKey.SetString(key.c_str(), allocator);
d.AddMember(iKey, Value(m_fileFormat.c_str(), allocator).Move(), allocator);
}
if (m_highlightHasBeenSet)
{
Value iKey(kStringType);
string key = "Highlight";
iKey.SetString(key.c_str(), allocator);
d.AddMember(iKey, m_highlight, allocator);
}
if (m_mixStreamHasBeenSet)
{
Value iKey(kStringType);
string key = "MixStream";
iKey.SetString(key.c_str(), allocator);
d.AddMember(iKey, m_mixStream, allocator);
}
if (m_streamParamHasBeenSet)
{
Value iKey(kStringType);
string key = "StreamParam";
iKey.SetString(key.c_str(), allocator);
d.AddMember(iKey, Value(m_streamParam.c_str(), allocator).Move(), allocator);
}
StringBuffer buffer;
Writer<StringBuffer> writer(buffer);
d.Accept(writer);
return buffer.GetString();
}
string CreateLiveRecordRequest::GetStreamName() const
{
return m_streamName;
}
void CreateLiveRecordRequest::SetStreamName(const string& _streamName)
{
m_streamName = _streamName;
m_streamNameHasBeenSet = true;
}
bool CreateLiveRecordRequest::StreamNameHasBeenSet() const
{
return m_streamNameHasBeenSet;
}
string CreateLiveRecordRequest::GetAppName() const
{
return m_appName;
}
void CreateLiveRecordRequest::SetAppName(const string& _appName)
{
m_appName = _appName;
m_appNameHasBeenSet = true;
}
bool CreateLiveRecordRequest::AppNameHasBeenSet() const
{
return m_appNameHasBeenSet;
}
string CreateLiveRecordRequest::GetDomainName() const
{
return m_domainName;
}
void CreateLiveRecordRequest::SetDomainName(const string& _domainName)
{
m_domainName = _domainName;
m_domainNameHasBeenSet = true;
}
bool CreateLiveRecordRequest::DomainNameHasBeenSet() const
{
return m_domainNameHasBeenSet;
}
string CreateLiveRecordRequest::GetStartTime() const
{
return m_startTime;
}
void CreateLiveRecordRequest::SetStartTime(const string& _startTime)
{
m_startTime = _startTime;
m_startTimeHasBeenSet = true;
}
bool CreateLiveRecordRequest::StartTimeHasBeenSet() const
{
return m_startTimeHasBeenSet;
}
string CreateLiveRecordRequest::GetEndTime() const
{
return m_endTime;
}
void CreateLiveRecordRequest::SetEndTime(const string& _endTime)
{
m_endTime = _endTime;
m_endTimeHasBeenSet = true;
}
bool CreateLiveRecordRequest::EndTimeHasBeenSet() const
{
return m_endTimeHasBeenSet;
}
string CreateLiveRecordRequest::GetRecordType() const
{
return m_recordType;
}
void CreateLiveRecordRequest::SetRecordType(const string& _recordType)
{
m_recordType = _recordType;
m_recordTypeHasBeenSet = true;
}
bool CreateLiveRecordRequest::RecordTypeHasBeenSet() const
{
return m_recordTypeHasBeenSet;
}
string CreateLiveRecordRequest::GetFileFormat() const
{
return m_fileFormat;
}
void CreateLiveRecordRequest::SetFileFormat(const string& _fileFormat)
{
m_fileFormat = _fileFormat;
m_fileFormatHasBeenSet = true;
}
bool CreateLiveRecordRequest::FileFormatHasBeenSet() const
{
return m_fileFormatHasBeenSet;
}
int64_t CreateLiveRecordRequest::GetHighlight() const
{
return m_highlight;
}
void CreateLiveRecordRequest::SetHighlight(const int64_t& _highlight)
{
m_highlight = _highlight;
m_highlightHasBeenSet = true;
}
bool CreateLiveRecordRequest::HighlightHasBeenSet() const
{
return m_highlightHasBeenSet;
}
int64_t CreateLiveRecordRequest::GetMixStream() const
{
return m_mixStream;
}
void CreateLiveRecordRequest::SetMixStream(const int64_t& _mixStream)
{
m_mixStream = _mixStream;
m_mixStreamHasBeenSet = true;
}
bool CreateLiveRecordRequest::MixStreamHasBeenSet() const
{
return m_mixStreamHasBeenSet;
}
string CreateLiveRecordRequest::GetStreamParam() const
{
return m_streamParam;
}
void CreateLiveRecordRequest::SetStreamParam(const string& _streamParam)
{
m_streamParam = _streamParam;
m_streamParamHasBeenSet = true;
}
bool CreateLiveRecordRequest::StreamParamHasBeenSet() const
{
return m_streamParamHasBeenSet;
}
| 24.429054 | 85 | 0.718296 |
427418928443107ac12ac31e6e1e5edd3f7a20cc | 940 | cpp | C++ | datasets/github_cpp_10/10/153.cpp | yijunyu/demo-fast | 11c0c84081a3181494b9c469bda42a313c457ad2 | [
"BSD-2-Clause"
] | 1 | 2019-05-03T19:27:45.000Z | 2019-05-03T19:27:45.000Z | datasets/github_cpp_10/10/153.cpp | yijunyu/demo-vscode-fast | 11c0c84081a3181494b9c469bda42a313c457ad2 | [
"BSD-2-Clause"
] | null | null | null | datasets/github_cpp_10/10/153.cpp | yijunyu/demo-vscode-fast | 11c0c84081a3181494b9c469bda42a313c457ad2 | [
"BSD-2-Clause"
] | null | null | null | /*
* EditDistance.cpp
*
* Created on: Aug 11, 2015
* Author: user
#include<iostream>
#include<cstring>
using namespace std;
void editDistance(char X[],char Y[],int m,int n){
int edit[m+1][n+1];
int delcost,inscost,samecost;
//Initialize table
for(int i=0;i<=m;i++){
for(int j=0;j<=n;j++){
edit[i][j]=-1;
}
}
for(int i=0;i<=m;i++){
edit[i][0]=i;
}
for(int j=0;j<=n;j++){
edit[0][j]=j;
}
for(int i=1;i<=m;i++){
for(int j=1;j<=n;j++){
delcost=edit[i-1][j]+1;
inscost=edit[i][j-1]+1;
samecost=edit[i-1][j-1];
samecost+=(X[i-1]!=Y[j-1]);
edit[i][j]=min(delcost,min(inscost,samecost));
}
}
cout<<"Minimum no. of edits are "<<edit[m][n]<<endl;
//Printing edit distance table
for(int i=0;i<=m;i++){
for(int j=0;j<=n;j++){
cout<<edit[i][j]<<" ";
}
cout<<endl;
}
}
int main(){
char X[]="SUNDAY";
char Y[]="SATURDAY";
editDistance(X,Y,strlen(X),strlen(Y));
}
*/
| 17.735849 | 53 | 0.544681 |
42760f70fcbb3e61191edeedac9efce62403ccca | 18,364 | hpp | C++ | 3rdparty/GPSTk/core/lib/GNSSEph/PackedNavBits.hpp | mfkiwl/ICE | e660d031bb1bcea664db1de4946fd8781be5b627 | [
"MIT"
] | 50 | 2019-10-12T01:22:20.000Z | 2022-02-15T23:28:26.000Z | 3rdparty/GPSTk/core/lib/GNSSEph/PackedNavBits.hpp | wuyou33/Enabling-Robust-State-Estimation-through-Measurement-Error-Covariance-Adaptation | 2f1ff054b7c5059da80bb3b2f80c05861a02cc36 | [
"MIT"
] | null | null | null | 3rdparty/GPSTk/core/lib/GNSSEph/PackedNavBits.hpp | wuyou33/Enabling-Robust-State-Estimation-through-Measurement-Error-Covariance-Adaptation | 2f1ff054b7c5059da80bb3b2f80c05861a02cc36 | [
"MIT"
] | 14 | 2019-11-05T01:50:29.000Z | 2021-08-06T06:23:44.000Z | //============================================================================
//
// This file is part of GPSTk, the GPS Toolkit.
//
// The GPSTk is free software; you can redistribute it and/or modify
// it under the terms of the GNU Lesser General Public License as published
// by the Free Software Foundation; either version 3.0 of the License, or
// any later version.
//
// The GPSTk is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public
// License along with GPSTk; if not, write to the Free Software Foundation,
// Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110, USA
//
// Copyright 2004, The University of Texas at Austin
//
//============================================================================
//============================================================================
//
//This software developed by Applied Research Laboratories at the University of
//Texas at Austin, under contract to an agency or agencies within the U.S.
//Department of Defense. The U.S. Government retains all rights to use,
//duplicate, distribute, disclose, or release this software.
//
//Pursuant to DoD Directive 523024
//
// DISTRIBUTION STATEMENT A: This software has been approved for public
// release, distribution is unlimited.
//
//=============================================================================
/**
* @file PackedNavBits.hpp
* Engineering units navigation message abstraction.
*/
#ifndef GPSTK_PACKEDNAVBITS_HPP
#define GPSTK_PACKEDNAVBITS_HPP
#include <vector>
#include <cstddef>
#include "gpstkplatform.h" //#include <stdint.h>
#include <string>
#include "ObsID.hpp"
#include "NavID.hpp"
#include "SatID.hpp"
#include "CommonTime.hpp"
#include "Exception.hpp"
namespace gpstk
{
/// @ingroup ephemcalc
//@{
class PackedNavBits
{
public:
/// empty constructor
PackedNavBits();
/// explicit constructor
PackedNavBits(const SatID& satSysArg,
const ObsID& obsIDArg,
const CommonTime& transmitTimeArg);
/// explicit constructor
PackedNavBits(const SatID& satSysArg,
const ObsID& obsIDArg,
const std::string rxString,
const CommonTime& transmitTimeArg);
/// explicit constructor
PackedNavBits(const SatID& satSysArg,
const ObsID& obsIDArg,
const NavID& navIDArg,
const std::string rxString,
const CommonTime& transmitTimeArg);
PackedNavBits(const PackedNavBits& right); // Copy constructor
//PackedNavBits& operator=(const PackedNavBits& right); // Copy assignment
PackedNavBits* clone() const;
void setSatID(const SatID& satSysArg);
void setObsID(const ObsID& obsIDArg);
void setNavID(const NavID& navIDArg);
void setRxID(const std::string rxString);
void setTime(const CommonTime& transmitTimeArg);
void clearBits();
/* Returnst the satellite system ID for a particular SV */
SatID getsatSys() const;
/* Returns Observation type, Carrier, and Tracking Code */
ObsID getobsID() const;
/* Return navigation message ID */
NavID getNavID() const;
/* Returns string defining the receiver that collected the data.
NOTE: This was a late addition to PackedNavBits and may not
be present in all applications */
std::string getRxID() const;
/* Returns time of transmission from SV */
CommonTime getTransmitTime() const;
/* Returns the number of bits */
size_t getNumBits() const;
/* Output the contents of this class to the given stream. */
void dump(std::ostream& s = std::cout) const throw();
/*** UNPACKING FUNCTIONS *********************************/
/* Unpack an unsigned long integer */
unsigned long asUnsignedLong(const int startBit,
const int numBits,
const int scale ) const;
/* Unpack a signed long integer */
long asLong(const int startBit,
const int numBits,
const int scale ) const;
/* Unpack an unsigned double */
double asUnsignedDouble( const int startBit,
const int numBits,
const int power2) const;
/* Unpack a signed double */
double asSignedDouble( const int startBit,
const int numBits,
const int power2) const;
/* Unpack a double with units of semicircles */
double asDoubleSemiCircles( const int startBit,
const int numBits,
const int power2) const;
/* Unpack a string */
std::string asString(const int startBit,
const int numChars) const;
// The following three methods were added to support
// GLONASS sign/magnitude real values.
//
// Since GLONASS has no disjoint fields (at least not
// up through ICD Edition 5.1) there are no methods
// for unpacking disjoint-field sign/mag quantities.
/* Unpack a sign/mag long */
long asSignMagLong(const int startBit,
const int numBits,
const int scale) const;
/* Unpack a sign/mag double */
double asSignMagDouble( const int startBit,
const int numBits,
const int power2) const;
/* Unpack a sign/mag double with units of semi-circles */
double asSignMagDoubleSemiCircles( const int startBit,
const int numBits,
const int power2) const;
/* Unpack mehthods that join multiple disjoint
navigation message areas as a single field
NOTE: startBit1 is associated with the most significant section
startBit2 is associated with the least significant section
*/
/* Unpack a split unsigned long integer */
unsigned long asUnsignedLong(const unsigned startBits[],
const unsigned numBits[],
const unsigned len,
const int scale ) const;
/* Unpack a signed long integer */
long asLong(const unsigned startBits[],
const unsigned numBits[],
const unsigned len,
const int scale ) const;
/* Unpack a split unsigned double */
double asUnsignedDouble( const unsigned startBits[],
const unsigned numBits[],
const unsigned len,
const int power2) const;
/* Unpack a split signed double */
double asSignedDouble( const unsigned startBits[],
const unsigned numBits[],
const unsigned len,
const int power2) const;
/* Unpack a split double with units of semicircles */
double asDoubleSemiCircles( const unsigned startBits[],
const unsigned numBits[],
const unsigned len,
const int power2) const;
bool asBool( const unsigned bitNum) const;
/*** PACKING FUNCTIONS *********************************/
/* Pack an unsigned long integer */
void addUnsignedLong( const unsigned long value,
const int numBits,
const int scale )
throw(InvalidParameter);
/* Pack a signed long integer */
void addLong( const long value,
const int numBits,
const int scale )
throw(InvalidParameter);
/* Pack an unsigned double */
void addUnsignedDouble( const double value,
const int numBits,
const int power2)
throw(InvalidParameter);
/* Pack a signed double */
void addSignedDouble( const double value,
const int numBits,
const int power2)
throw(InvalidParameter);
/* Pack a double with units of semicircles */
void addDoubleSemiCircles( const double radians,
const int numBits,
const int power2)
throw(InvalidParameter);
/**
* Pack a string.
* Characters in String limited to those defined in IS-GPS-200 Section 20.3.3.5.1.8
* numChars represents number of chars (8 bits each) to add to PackedBits.
* If numChars < length of String only, chars 1..numChars will be added.
* If numChars > length of String, blanks will be added at the end. */
void addString(const std::string String,
const int numChars)
throw(InvalidParameter);
void addPackedNavBits( const PackedNavBits &pnb)
throw(InvalidParameter);
/*
* Output the packed bits as a set of 32 bit
* hex values, four per line, without any
* additional information.
* Returns the number of bits in the object.
*/
int outputPackedBits(std::ostream& s = std::cout,
const short numPerLine=4,
const char delimiter = ' ',
const short numBitsPerWord=32 ) const;
/*
* The equality operator insists that ALL the metadata
* and the complete bit patterns must match.
* However, there are frequently occaisions when only
* a subset of the metadata need be checked, and sometimes
* only certain set of bits. Therefore, operator==( ) is
* supplemented by matchBits( ) and matchMetaData( )
*/
bool operator==(const PackedNavBits& right) const;
/*
* There are frequently cases in which we want to know
* if a pair of PackedNavBits objects are from the same
* SV, but we might want to allow for different receivers
* and/or different ObsIDs. Therefore, matchMetaData( )
* allows specification of the particular metadata items
* that are to be checked using a bit-flag system.
*/
static const unsigned int mmTIME = 0x0001; // Check transmitTime
static const unsigned int mmSAT = 0x0002; // Check SatID
static const unsigned int mmOBS = 0x0004; // Check ObsID
static const unsigned int mmRX = 0x0008; // Check Receiver ID
static const unsigned int mmNAV = 0x0010; // Check NavID
static const unsigned int mmALL = 0xFFFF; // Check ALL metadata
static const unsigned int mmNONE = 0x0000; // NO metadata checks
bool matchMetaData(const PackedNavBits& right,
const unsigned flagBits=mmALL) const;
/*
* Return true if all bits between start and end are identical
* between this object and right. Default is to compare all
* bits.
*
* This method allows comparison of the "unchanging" data in
* nav messages while avoiding the time tags.
*/
bool matchBits(const PackedNavBits& right,
const short startBit=0,
const short endBit=-1) const;
/*
* This is the most flexible of the matching methods.
* A default of match(right) will yield the same
* result as operator==( ).
* However, the arguments provide the means to
* specifically check bits sequences and/or
* selectively check the metadata.
*/
bool match(const PackedNavBits& right,
const short startBit=0,
const short endBit=-1,
const unsigned flagBits=mmALL) const;
/*
* This version was the original equality checker. As
* first implemented, it checks ONLY SAT and OBS for
* equality. Therefore, it is maintained with that
* default functionality. That is to say, when
* checkOverhead==true, the result is the same as a call
* to matchBits(right,startBit,endBit, (mmSAT|mmOBS)).
*
* For clarity, it is suggested that new code use
* operator==(),
* matchMetaData(), and/or
* matchBits( ) using explicit flags.
*
* This version was REMOVED because of ambiguity
* in the signature.
*
* The checkOverhead option allows the user to ignore
* the associated metadata. E.g. ObsID, SatID.
*
bool matchBits(const PackedNavBits& right,
const short startBit=0,
const short endBit=-1,
const bool checkOverhead) const;
*/
/**
* The less than operator is defined in order to support use
* with the NavFilter classes. The idea is to provide a
* "sort" for bits contained in the class. Matching strings
* will fail both a < b and b < a; however, in the process
* all matching strings can be sorted into sets and the
* "winner" determined.
*/
bool operator<(const PackedNavBits& right) const;
/**
* Bitwise invert contents of this object.
*/
void invert( );
/**
* Bit wise copy from another PackecNavBits.
* None of the meta-data (transmit time, SatID, ObsID)
* will be changed.
* This method is intended for use between two
* PackedNavBits objecst that are ALREADY the
* same size (in bits). It will throw an
* InvalidParameter exception if called using two
* objects that are NOT the same size.
* Yes, we could define a copy that would account
* for the difference, but the pre-existing model
* for PNB is that the bits_used variable records
* the # of bits used as items are added to the end
* of the bit array. I didn't want copyBits( )
* to confuse that model by modifying bits_used.
*/
void copyBits(const PackedNavBits& from,
const short startBit=0,
const short endBit=-1)
throw(InvalidParameter);
/**
* This method is not typically used in production; however it
* is used in test support. It assumes the PNB object is already
* created and is already sized to hold at least (startBit+numBits)
* bits. If this is not true, an exception is thrown.
* It overwrites the data that is already present with
* the provided value / scale. If value / scale is too large to
* fit in numBits, then an exception is thrown.
*/
void insertUnsignedLong(const unsigned long value,
const int startBit,
const int numBits,
const int scale=1 )
throw(InvalidParameter);
/**
* Reset number of bits
*/
void reset_num_bits(const int new_bits_used=0);
/* Resize the vector holding the packed data. */
void trimsize();
/**
* Raw bit input
* This function is intended as a test-support function.
* It assumes a string of the form
* ### 0xABCDABCD 0xABCDABCD 0xABCDABCD
* where
* ### is the number of bits to expect in the remainder
* of the line.
* 0xABCDABCD are each 32-bit unsigned hex numbers, left
* justified. The number of bits needs to match or
* exceed ###
* The function returns if the read is succeessful.
* Otherwise,the function throws an exception */
void rawBitInput(const std::string inString )
throw(InvalidParameter);
void setXmitCoerced(bool tf=true) {xMitCoerced=tf;}
bool isXmitCoerced() const {return xMitCoerced;}
private:
SatID satSys; /**< System ID (based on RINEX defintions */
ObsID obsID; /**< Defines carrier and code tracked */
NavID navID; /**< Defines the navigation message tracked */
std::string rxID; /**< Defines the receiver that collected the data */
CommonTime transmitTime; /**< Time nav message is transmitted */
std::vector<bool> bits; /**< Holds the packed data */
int bits_used;
bool xMitCoerced; /**< Used to indicate that the transmit
time is NOT directly derived from
the SOW in the message */
/** Unpack the bits */
uint64_t asUint64_t(const int startBit, const int numBits ) const
throw(InvalidParameter);
/** Pack the bits */
void addUint64_t( const uint64_t value, const int numBits );
/** Extend the sign bit for signed values */
int64_t SignExtend( const int startBit, const int numBits ) const;
/** Scales doubles by their corresponding scale factor */
double ScaleValue( const double value, const int power2) const;
}; // class PackedNavBits
//@}
std::ostream& operator<<(std::ostream& s, const PackedNavBits& pnb);
} // namespace
#endif
| 40.808889 | 92 | 0.556415 |
42768a0b65d6e98e69e348eb23106fa73cff1c2a | 741 | cc | C++ | base/at_exit.cc | Arpan-2109/caroline | 23aba9ac9a35697c02358aeb88ed121d3d97a99c | [
"MIT"
] | 1 | 2017-07-27T15:08:19.000Z | 2017-07-27T15:08:19.000Z | base/at_exit.cc | Arpan-2109/caroline | 23aba9ac9a35697c02358aeb88ed121d3d97a99c | [
"MIT"
] | null | null | null | base/at_exit.cc | Arpan-2109/caroline | 23aba9ac9a35697c02358aeb88ed121d3d97a99c | [
"MIT"
] | 1 | 2020-10-01T08:46:10.000Z | 2020-10-01T08:46:10.000Z | // Copyright (c) 2014 The Caroline authors. All rights reserved.
// Use of this source file is governed by a MIT license that can be found in the
// LICENSE file.
// @author Aleksandr Derbenev <13alexac@gmail.com>
#include "base/at_exit.h"
namespace base {
AtExitManager* AtExitManager::instance_ = nullptr;
AtExitManager::AtExitManager()
: previous_instance_(instance_) {
instance_ = this;
}
AtExitManager::~AtExitManager() {
for (; !callbacks_.empty(); callbacks_.pop())
callbacks_.top()();
instance_ = previous_instance_;
}
// static
AtExitManager* AtExitManager::GetInstance() {
return instance_;
}
void AtExitManager::RegisterCallback(AtExitCallback callback) {
callbacks_.push(callback);
}
} // namespace base
| 22.454545 | 80 | 0.735493 |
4278bd904a9c2025b90f02a445961a9ce574a0f6 | 20,942 | cc | C++ | content/renderer/loader/url_loader_client_impl_unittest.cc | zipated/src | 2b8388091c71e442910a21ada3d97ae8bc1845d3 | [
"BSD-3-Clause"
] | 2,151 | 2020-04-18T07:31:17.000Z | 2022-03-31T08:39:18.000Z | content/renderer/loader/url_loader_client_impl_unittest.cc | cangulcan/src | 2b8388091c71e442910a21ada3d97ae8bc1845d3 | [
"BSD-3-Clause"
] | 395 | 2020-04-18T08:22:18.000Z | 2021-12-08T13:04:49.000Z | content/renderer/loader/url_loader_client_impl_unittest.cc | cangulcan/src | 2b8388091c71e442910a21ada3d97ae8bc1845d3 | [
"BSD-3-Clause"
] | 338 | 2020-04-18T08:03:10.000Z | 2022-03-29T12:33:22.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 "content/renderer/loader/url_loader_client_impl.h"
#include <vector>
#include "base/message_loop/message_loop.h"
#include "base/run_loop.h"
#include "content/renderer/loader/navigation_response_override_parameters.h"
#include "content/renderer/loader/resource_dispatcher.h"
#include "content/renderer/loader/test_request_peer.h"
#include "mojo/public/cpp/bindings/binding.h"
#include "mojo/public/cpp/bindings/interface_ptr.h"
#include "net/traffic_annotation/network_traffic_annotation_test_helper.h"
#include "net/url_request/redirect_info.h"
#include "services/network/public/cpp/weak_wrapper_shared_url_loader_factory.h"
#include "services/network/public/mojom/url_loader_factory.mojom.h"
#include "testing/gtest/include/gtest/gtest.h"
#include "third_party/blink/public/platform/scheduler/test/renderer_scheduler_test_support.h"
namespace content {
class URLLoaderClientImplTest : public ::testing::Test,
public network::mojom::URLLoaderFactory {
protected:
URLLoaderClientImplTest() : dispatcher_(new ResourceDispatcher()) {
request_id_ = dispatcher_->StartAsync(
std::make_unique<network::ResourceRequest>(), 0,
blink::scheduler::GetSingleThreadTaskRunnerForTesting(),
TRAFFIC_ANNOTATION_FOR_TESTS, false, false,
std::make_unique<TestRequestPeer>(dispatcher_.get(),
&request_peer_context_),
base::MakeRefCounted<network::WeakWrapperSharedURLLoaderFactory>(this),
std::vector<std::unique_ptr<URLLoaderThrottle>>(),
nullptr /* navigation_response_override_params */,
nullptr /* continue_navigation_function */);
request_peer_context_.request_id = request_id_;
base::RunLoop().RunUntilIdle();
EXPECT_TRUE(url_loader_client_);
}
void TearDown() override {
url_loader_client_ = nullptr;
}
void CreateLoaderAndStart(network::mojom::URLLoaderRequest request,
int32_t routing_id,
int32_t request_id,
uint32_t options,
const network::ResourceRequest& url_request,
network::mojom::URLLoaderClientPtr client,
const net::MutableNetworkTrafficAnnotationTag&
traffic_annotation) override {
url_loader_client_ = std::move(client);
}
void Clone(network::mojom::URLLoaderFactoryRequest request) override {
NOTREACHED();
}
static MojoCreateDataPipeOptions DataPipeOptions() {
MojoCreateDataPipeOptions options;
options.struct_size = sizeof(MojoCreateDataPipeOptions);
options.flags = MOJO_CREATE_DATA_PIPE_FLAG_NONE;
options.element_num_bytes = 1;
options.capacity_num_bytes = 4096;
return options;
}
base::MessageLoop message_loop_;
std::unique_ptr<ResourceDispatcher> dispatcher_;
TestRequestPeer::Context request_peer_context_;
int request_id_ = 0;
network::mojom::URLLoaderClientPtr url_loader_client_;
};
TEST_F(URLLoaderClientImplTest, OnReceiveResponse) {
network::ResourceResponseHead response_head;
url_loader_client_->OnReceiveResponse(response_head, nullptr);
EXPECT_FALSE(request_peer_context_.received_response);
base::RunLoop().RunUntilIdle();
EXPECT_TRUE(request_peer_context_.received_response);
}
TEST_F(URLLoaderClientImplTest, ResponseBody) {
network::ResourceResponseHead response_head;
url_loader_client_->OnReceiveResponse(response_head, nullptr);
EXPECT_FALSE(request_peer_context_.received_response);
base::RunLoop().RunUntilIdle();
EXPECT_TRUE(request_peer_context_.received_response);
mojo::DataPipe data_pipe(DataPipeOptions());
url_loader_client_->OnStartLoadingResponseBody(
std::move(data_pipe.consumer_handle));
uint32_t size = 5;
MojoResult result = data_pipe.producer_handle->WriteData(
"hello", &size, MOJO_WRITE_DATA_FLAG_NONE);
ASSERT_EQ(MOJO_RESULT_OK, result);
EXPECT_EQ(5u, size);
base::RunLoop().RunUntilIdle();
EXPECT_EQ("hello", request_peer_context_.data);
}
TEST_F(URLLoaderClientImplTest, OnReceiveRedirect) {
network::ResourceResponseHead response_head;
net::RedirectInfo redirect_info;
url_loader_client_->OnReceiveRedirect(redirect_info, response_head);
EXPECT_EQ(0, request_peer_context_.seen_redirects);
base::RunLoop().RunUntilIdle();
EXPECT_EQ(1, request_peer_context_.seen_redirects);
}
TEST_F(URLLoaderClientImplTest, OnDataDownloaded) {
network::ResourceResponseHead response_head;
url_loader_client_->OnReceiveResponse(response_head, nullptr);
url_loader_client_->OnDataDownloaded(8, 13);
url_loader_client_->OnDataDownloaded(2, 1);
EXPECT_FALSE(request_peer_context_.received_response);
EXPECT_EQ(0, request_peer_context_.total_downloaded_data_length);
EXPECT_EQ(0, request_peer_context_.total_encoded_data_length);
base::RunLoop().RunUntilIdle();
EXPECT_TRUE(request_peer_context_.received_response);
EXPECT_EQ(10, request_peer_context_.total_downloaded_data_length);
EXPECT_EQ(14, request_peer_context_.total_encoded_data_length);
}
TEST_F(URLLoaderClientImplTest, OnReceiveCachedMetadata) {
network::ResourceResponseHead response_head;
std::vector<uint8_t> metadata;
metadata.push_back('a');
url_loader_client_->OnReceiveResponse(response_head, nullptr);
url_loader_client_->OnReceiveCachedMetadata(metadata);
EXPECT_FALSE(request_peer_context_.received_response);
EXPECT_TRUE(request_peer_context_.cached_metadata.empty());
base::RunLoop().RunUntilIdle();
EXPECT_TRUE(request_peer_context_.received_response);
ASSERT_EQ(1u, request_peer_context_.cached_metadata.size());
EXPECT_EQ('a', request_peer_context_.cached_metadata[0]);
}
TEST_F(URLLoaderClientImplTest, OnTransferSizeUpdated) {
network::ResourceResponseHead response_head;
url_loader_client_->OnReceiveResponse(response_head, nullptr);
url_loader_client_->OnTransferSizeUpdated(4);
url_loader_client_->OnTransferSizeUpdated(4);
EXPECT_FALSE(request_peer_context_.received_response);
EXPECT_EQ(0, request_peer_context_.total_encoded_data_length);
base::RunLoop().RunUntilIdle();
EXPECT_TRUE(request_peer_context_.received_response);
EXPECT_EQ(8, request_peer_context_.total_encoded_data_length);
}
TEST_F(URLLoaderClientImplTest, OnCompleteWithoutResponseBody) {
network::ResourceResponseHead response_head;
network::URLLoaderCompletionStatus status;
url_loader_client_->OnReceiveResponse(response_head, nullptr);
url_loader_client_->OnComplete(status);
EXPECT_FALSE(request_peer_context_.received_response);
EXPECT_FALSE(request_peer_context_.complete);
base::RunLoop().RunUntilIdle();
EXPECT_TRUE(request_peer_context_.received_response);
EXPECT_TRUE(request_peer_context_.complete);
}
TEST_F(URLLoaderClientImplTest, OnCompleteWithResponseBody) {
network::ResourceResponseHead response_head;
network::URLLoaderCompletionStatus status;
url_loader_client_->OnReceiveResponse(response_head, nullptr);
mojo::DataPipe data_pipe(DataPipeOptions());
url_loader_client_->OnStartLoadingResponseBody(
std::move(data_pipe.consumer_handle));
uint32_t size = 5;
MojoResult result = data_pipe.producer_handle->WriteData(
"hello", &size, MOJO_WRITE_DATA_FLAG_NONE);
ASSERT_EQ(MOJO_RESULT_OK, result);
EXPECT_EQ(5u, size);
data_pipe.producer_handle.reset();
EXPECT_FALSE(request_peer_context_.received_response);
EXPECT_EQ("", request_peer_context_.data);
base::RunLoop().RunUntilIdle();
EXPECT_TRUE(request_peer_context_.received_response);
EXPECT_EQ("hello", request_peer_context_.data);
url_loader_client_->OnComplete(status);
EXPECT_FALSE(request_peer_context_.complete);
base::RunLoop().RunUntilIdle();
EXPECT_TRUE(request_peer_context_.received_response);
EXPECT_EQ("hello", request_peer_context_.data);
EXPECT_TRUE(request_peer_context_.complete);
}
// Due to the lack of ordering guarantee, it is possible that the response body
// bytes arrives after the completion message. URLLoaderClientImpl should
// restore the order.
TEST_F(URLLoaderClientImplTest, OnCompleteShouldBeTheLastMessage) {
network::ResourceResponseHead response_head;
network::URLLoaderCompletionStatus status;
url_loader_client_->OnReceiveResponse(response_head, nullptr);
mojo::DataPipe data_pipe(DataPipeOptions());
url_loader_client_->OnStartLoadingResponseBody(
std::move(data_pipe.consumer_handle));
url_loader_client_->OnComplete(status);
base::RunLoop().RunUntilIdle();
EXPECT_TRUE(request_peer_context_.received_response);
EXPECT_FALSE(request_peer_context_.complete);
uint32_t size = 5;
MojoResult result = data_pipe.producer_handle->WriteData(
"hello", &size, MOJO_WRITE_DATA_FLAG_NONE);
ASSERT_EQ(MOJO_RESULT_OK, result);
EXPECT_EQ(5u, size);
base::RunLoop().RunUntilIdle();
EXPECT_EQ("hello", request_peer_context_.data);
EXPECT_FALSE(request_peer_context_.complete);
data_pipe.producer_handle.reset();
base::RunLoop().RunUntilIdle();
EXPECT_EQ("hello", request_peer_context_.data);
EXPECT_TRUE(request_peer_context_.complete);
}
TEST_F(URLLoaderClientImplTest, CancelOnReceiveResponse) {
request_peer_context_.cancel_on_receive_response = true;
network::ResourceResponseHead response_head;
network::URLLoaderCompletionStatus status;
url_loader_client_->OnReceiveResponse(response_head, nullptr);
mojo::DataPipe data_pipe(DataPipeOptions());
url_loader_client_->OnStartLoadingResponseBody(
std::move(data_pipe.consumer_handle));
url_loader_client_->OnComplete(status);
EXPECT_FALSE(request_peer_context_.received_response);
EXPECT_FALSE(request_peer_context_.complete);
EXPECT_FALSE(request_peer_context_.cancelled);
base::RunLoop().RunUntilIdle();
EXPECT_TRUE(request_peer_context_.received_response);
EXPECT_FALSE(request_peer_context_.complete);
EXPECT_TRUE(request_peer_context_.cancelled);
}
TEST_F(URLLoaderClientImplTest, CancelOnReceiveData) {
request_peer_context_.cancel_on_receive_data = true;
network::ResourceResponseHead response_head;
network::URLLoaderCompletionStatus status;
mojo::DataPipe data_pipe(DataPipeOptions());
uint32_t size = 5;
MojoResult result = data_pipe.producer_handle->WriteData(
"hello", &size, MOJO_WRITE_DATA_FLAG_NONE);
ASSERT_EQ(MOJO_RESULT_OK, result);
EXPECT_EQ(5u, size);
url_loader_client_->OnReceiveResponse(response_head, nullptr);
url_loader_client_->OnStartLoadingResponseBody(
std::move(data_pipe.consumer_handle));
url_loader_client_->OnComplete(status);
EXPECT_FALSE(request_peer_context_.received_response);
EXPECT_EQ("", request_peer_context_.data);
EXPECT_FALSE(request_peer_context_.complete);
EXPECT_FALSE(request_peer_context_.cancelled);
base::RunLoop().RunUntilIdle();
EXPECT_TRUE(request_peer_context_.received_response);
EXPECT_EQ("hello", request_peer_context_.data);
EXPECT_FALSE(request_peer_context_.complete);
EXPECT_TRUE(request_peer_context_.cancelled);
}
TEST_F(URLLoaderClientImplTest, Defer) {
network::ResourceResponseHead response_head;
network::URLLoaderCompletionStatus status;
url_loader_client_->OnReceiveResponse(response_head, nullptr);
url_loader_client_->OnComplete(status);
EXPECT_FALSE(request_peer_context_.received_response);
EXPECT_FALSE(request_peer_context_.complete);
dispatcher_->SetDefersLoading(request_id_, true);
base::RunLoop().RunUntilIdle();
EXPECT_FALSE(request_peer_context_.received_response);
EXPECT_FALSE(request_peer_context_.complete);
dispatcher_->SetDefersLoading(request_id_, false);
EXPECT_FALSE(request_peer_context_.received_response);
EXPECT_FALSE(request_peer_context_.complete);
base::RunLoop().RunUntilIdle();
EXPECT_TRUE(request_peer_context_.received_response);
EXPECT_TRUE(request_peer_context_.complete);
}
TEST_F(URLLoaderClientImplTest, DeferWithResponseBody) {
network::ResourceResponseHead response_head;
network::URLLoaderCompletionStatus status;
url_loader_client_->OnReceiveResponse(response_head, nullptr);
mojo::DataPipe data_pipe(DataPipeOptions());
uint32_t size = 5;
MojoResult result = data_pipe.producer_handle->WriteData(
"hello", &size, MOJO_WRITE_DATA_FLAG_NONE);
ASSERT_EQ(MOJO_RESULT_OK, result);
EXPECT_EQ(5u, size);
data_pipe.producer_handle.reset();
url_loader_client_->OnStartLoadingResponseBody(
std::move(data_pipe.consumer_handle));
url_loader_client_->OnComplete(status);
EXPECT_FALSE(request_peer_context_.received_response);
EXPECT_FALSE(request_peer_context_.complete);
EXPECT_EQ("", request_peer_context_.data);
dispatcher_->SetDefersLoading(request_id_, true);
base::RunLoop().RunUntilIdle();
EXPECT_FALSE(request_peer_context_.received_response);
EXPECT_FALSE(request_peer_context_.complete);
EXPECT_EQ("", request_peer_context_.data);
dispatcher_->SetDefersLoading(request_id_, false);
EXPECT_FALSE(request_peer_context_.received_response);
EXPECT_FALSE(request_peer_context_.complete);
EXPECT_EQ("", request_peer_context_.data);
base::RunLoop().RunUntilIdle();
EXPECT_TRUE(request_peer_context_.received_response);
EXPECT_TRUE(request_peer_context_.complete);
EXPECT_EQ("hello", request_peer_context_.data);
}
// As "transfer size update" message is handled specially in the implementation,
// we have a separate test.
TEST_F(URLLoaderClientImplTest, DeferWithTransferSizeUpdated) {
network::ResourceResponseHead response_head;
network::URLLoaderCompletionStatus status;
url_loader_client_->OnReceiveResponse(response_head, nullptr);
mojo::DataPipe data_pipe(DataPipeOptions());
uint32_t size = 5;
MojoResult result = data_pipe.producer_handle->WriteData(
"hello", &size, MOJO_WRITE_DATA_FLAG_NONE);
ASSERT_EQ(MOJO_RESULT_OK, result);
EXPECT_EQ(5u, size);
data_pipe.producer_handle.reset();
url_loader_client_->OnStartLoadingResponseBody(
std::move(data_pipe.consumer_handle));
url_loader_client_->OnTransferSizeUpdated(4);
url_loader_client_->OnComplete(status);
EXPECT_FALSE(request_peer_context_.received_response);
EXPECT_FALSE(request_peer_context_.complete);
EXPECT_EQ("", request_peer_context_.data);
EXPECT_EQ(0, request_peer_context_.total_encoded_data_length);
dispatcher_->SetDefersLoading(request_id_, true);
base::RunLoop().RunUntilIdle();
EXPECT_FALSE(request_peer_context_.received_response);
EXPECT_FALSE(request_peer_context_.complete);
EXPECT_EQ("", request_peer_context_.data);
EXPECT_EQ(0, request_peer_context_.total_encoded_data_length);
dispatcher_->SetDefersLoading(request_id_, false);
EXPECT_FALSE(request_peer_context_.received_response);
EXPECT_FALSE(request_peer_context_.complete);
EXPECT_EQ("", request_peer_context_.data);
EXPECT_EQ(0, request_peer_context_.total_encoded_data_length);
base::RunLoop().RunUntilIdle();
EXPECT_TRUE(request_peer_context_.received_response);
EXPECT_TRUE(request_peer_context_.complete);
EXPECT_EQ("hello", request_peer_context_.data);
EXPECT_EQ(4, request_peer_context_.total_encoded_data_length);
}
TEST_F(URLLoaderClientImplTest, SetDeferredDuringFlushingDeferredMessage) {
request_peer_context_.defer_on_redirect = true;
net::RedirectInfo redirect_info;
network::ResourceResponseHead response_head;
network::URLLoaderCompletionStatus status;
url_loader_client_->OnReceiveRedirect(redirect_info, response_head);
url_loader_client_->OnReceiveResponse(response_head, nullptr);
mojo::DataPipe data_pipe(DataPipeOptions());
uint32_t size = 5;
MojoResult result = data_pipe.producer_handle->WriteData(
"hello", &size, MOJO_WRITE_DATA_FLAG_NONE);
ASSERT_EQ(MOJO_RESULT_OK, result);
EXPECT_EQ(5u, size);
data_pipe.producer_handle.reset();
url_loader_client_->OnStartLoadingResponseBody(
std::move(data_pipe.consumer_handle));
url_loader_client_->OnTransferSizeUpdated(4);
url_loader_client_->OnComplete(status);
EXPECT_EQ(0, request_peer_context_.seen_redirects);
EXPECT_FALSE(request_peer_context_.received_response);
EXPECT_FALSE(request_peer_context_.complete);
EXPECT_EQ("", request_peer_context_.data);
EXPECT_EQ(0, request_peer_context_.total_encoded_data_length);
dispatcher_->SetDefersLoading(request_id_, true);
base::RunLoop().RunUntilIdle();
EXPECT_EQ(0, request_peer_context_.seen_redirects);
EXPECT_FALSE(request_peer_context_.received_response);
EXPECT_FALSE(request_peer_context_.complete);
EXPECT_EQ("", request_peer_context_.data);
EXPECT_EQ(0, request_peer_context_.total_encoded_data_length);
dispatcher_->SetDefersLoading(request_id_, false);
EXPECT_EQ(0, request_peer_context_.seen_redirects);
EXPECT_FALSE(request_peer_context_.received_response);
EXPECT_FALSE(request_peer_context_.complete);
EXPECT_EQ("", request_peer_context_.data);
EXPECT_EQ(0, request_peer_context_.total_encoded_data_length);
base::RunLoop().RunUntilIdle();
EXPECT_EQ(1, request_peer_context_.seen_redirects);
EXPECT_FALSE(request_peer_context_.received_response);
EXPECT_FALSE(request_peer_context_.complete);
EXPECT_EQ("", request_peer_context_.data);
EXPECT_EQ(0, request_peer_context_.total_encoded_data_length);
EXPECT_FALSE(request_peer_context_.cancelled);
dispatcher_->SetDefersLoading(request_id_, false);
base::RunLoop().RunUntilIdle();
EXPECT_EQ(1, request_peer_context_.seen_redirects);
EXPECT_TRUE(request_peer_context_.received_response);
EXPECT_TRUE(request_peer_context_.complete);
EXPECT_EQ("hello", request_peer_context_.data);
EXPECT_EQ(4, request_peer_context_.total_encoded_data_length);
EXPECT_FALSE(request_peer_context_.cancelled);
}
TEST_F(URLLoaderClientImplTest,
SetDeferredDuringFlushingDeferredMessageOnTransferSizeUpdated) {
request_peer_context_.defer_on_transfer_size_updated = true;
network::ResourceResponseHead response_head;
network::URLLoaderCompletionStatus status;
url_loader_client_->OnReceiveResponse(response_head, nullptr);
url_loader_client_->OnTransferSizeUpdated(4);
url_loader_client_->OnComplete(status);
EXPECT_FALSE(request_peer_context_.received_response);
EXPECT_FALSE(request_peer_context_.complete);
EXPECT_EQ(0, request_peer_context_.total_encoded_data_length);
dispatcher_->SetDefersLoading(request_id_, true);
base::RunLoop().RunUntilIdle();
EXPECT_FALSE(request_peer_context_.received_response);
EXPECT_FALSE(request_peer_context_.complete);
EXPECT_EQ(0, request_peer_context_.total_encoded_data_length);
dispatcher_->SetDefersLoading(request_id_, false);
EXPECT_FALSE(request_peer_context_.received_response);
EXPECT_FALSE(request_peer_context_.complete);
EXPECT_EQ(0, request_peer_context_.total_encoded_data_length);
base::RunLoop().RunUntilIdle();
EXPECT_TRUE(request_peer_context_.received_response);
EXPECT_FALSE(request_peer_context_.complete);
EXPECT_EQ(4, request_peer_context_.total_encoded_data_length);
EXPECT_FALSE(request_peer_context_.cancelled);
dispatcher_->SetDefersLoading(request_id_, false);
base::RunLoop().RunUntilIdle();
EXPECT_TRUE(request_peer_context_.received_response);
EXPECT_TRUE(request_peer_context_.complete);
EXPECT_EQ(4, request_peer_context_.total_encoded_data_length);
EXPECT_FALSE(request_peer_context_.cancelled);
}
TEST_F(URLLoaderClientImplTest, CancelOnReceiveDataWhileFlushing) {
request_peer_context_.cancel_on_receive_data = true;
dispatcher_->SetDefersLoading(request_id_, true);
network::ResourceResponseHead response_head;
network::URLLoaderCompletionStatus status;
mojo::DataPipe data_pipe(DataPipeOptions());
uint32_t size = 5;
MojoResult result = data_pipe.producer_handle->WriteData(
"hello", &size, MOJO_WRITE_DATA_FLAG_NONE);
ASSERT_EQ(MOJO_RESULT_OK, result);
EXPECT_EQ(5u, size);
url_loader_client_->OnReceiveResponse(response_head, nullptr);
url_loader_client_->OnStartLoadingResponseBody(
std::move(data_pipe.consumer_handle));
url_loader_client_->OnComplete(status);
base::RunLoop().RunUntilIdle();
EXPECT_FALSE(request_peer_context_.received_response);
EXPECT_EQ("", request_peer_context_.data);
EXPECT_FALSE(request_peer_context_.complete);
EXPECT_FALSE(request_peer_context_.cancelled);
dispatcher_->SetDefersLoading(request_id_, false);
EXPECT_FALSE(request_peer_context_.received_response);
EXPECT_EQ("", request_peer_context_.data);
EXPECT_FALSE(request_peer_context_.complete);
EXPECT_FALSE(request_peer_context_.cancelled);
base::RunLoop().RunUntilIdle();
EXPECT_TRUE(request_peer_context_.received_response);
EXPECT_EQ("hello", request_peer_context_.data);
EXPECT_FALSE(request_peer_context_.complete);
EXPECT_TRUE(request_peer_context_.cancelled);
}
} // namespace content
| 38.00726 | 93 | 0.798682 |
427dadf50206b481428f745d6378efe7af5a3e14 | 1,896 | cpp | C++ | source/Matrix.cpp | cburggie/matrixemu | 1ec74e26f2a201caf5577eabd57c0ab5ad83d94f | [
"MIT"
] | null | null | null | source/Matrix.cpp | cburggie/matrixemu | 1ec74e26f2a201caf5577eabd57c0ab5ad83d94f | [
"MIT"
] | null | null | null | source/Matrix.cpp | cburggie/matrixemu | 1ec74e26f2a201caf5577eabd57c0ab5ad83d94f | [
"MIT"
] | null | null | null | //namespace matrixemu
#include <Terminal.h> //class Terminal
#include <Column.h> //class Column
#include <Linker.h> //class Linker<T>
#include <Matrix.h> //Implementing this
//namespace std
#include <cstdlib> //rand()
using namespace matrixemu;
Matrix::Matrix()
{
terminal = new Terminal();
columns = new Linker<Column>();
}
Matrix::~Matrix()
{
if (terminal) delete terminal;
if (columns) delete columns;
}
void Matrix::run(int frames)
{
//we run until we've rendered enough frames or our terminal member has
//detected a quit signal from the user.
//we clear the screen when we're done and exit.
setupColors();
int i, spawnpoint = 0;
for (i = 0; i < frames; i++)
{
if (i == spawnpoint)
{
addNewColumn();
spawnpoint += 1 + (rand() % 5);
}
drawFrame(i);
terminal->pause(25); //25 ms pause or 40 fps
if (terminal->done()) break;
}
terminal->blank();
terminal->draw();
}
void Matrix::setupColors()
{
int r[8], g[8], b[8], i;
for (i = 0; i < 8; i++)
{
r[i] = 0;
g[i] = 125 * i;
b[i] = 0;
}
terminal->makePalette(8,r,g,b);
}
void Matrix::addNewColumn()
{
//init new column;
int xpos, speed, length;
xpos = rand() % terminal->getWidth();
speed = 1 + (rand() % 10);
length = 1 + (rand() % 50);
Column * column = new Column(terminal, xpos);
if (!column)
{
return;
}
column->setSpeed(speed);
column->setLength(length);
//init new link and add to list
Linker<Column> * link = new Linker<Column>(column);
if (!link)
{
delete column;
return;
}
link->append(columns);
}
void Matrix::drawFrame(int timestamp)
{
Linker<Column> * node = columns->next();
Linker<Column> * tmp;
terminal->blank();
while (node != columns)
{
tmp = node->next();
node->get()->draw(timestamp);
//delete node if it's offscreen now
if (node->get()->offscreen())
{
delete node;
}
node = tmp;
}
terminal->draw();
}
| 16.205128 | 71 | 0.617616 |
427ee3368d8d95736ded6ebd83e6d7aaf7f3496f | 61,687 | hpp | C++ | include/bf_rt/bf_rt_table.hpp | mestery/p4-dpdk-target | 9e7bafa442d3e008749f9ee0e1364bc5e9acfc13 | [
"Apache-2.0"
] | 17 | 2021-10-21T17:55:24.000Z | 2022-03-11T11:04:33.000Z | include/bf_rt/bf_rt_table.hpp | mestery/p4-dpdk-target | 9e7bafa442d3e008749f9ee0e1364bc5e9acfc13 | [
"Apache-2.0"
] | 9 | 2021-12-20T10:24:50.000Z | 2022-03-21T17:42:13.000Z | include/bf_rt/bf_rt_table.hpp | mestery/p4-dpdk-target | 9e7bafa442d3e008749f9ee0e1364bc5e9acfc13 | [
"Apache-2.0"
] | 7 | 2021-11-02T22:08:04.000Z | 2022-03-09T23:26:03.000Z | /*
* Copyright(c) 2021 Intel Corporation.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/** @file bf_rt_table.hpp
*
* @brief Contains BF-RT Table APIs
*/
#ifndef _BF_RT_TABLE_HPP
#define _BF_RT_TABLE_HPP
#include <string>
#include <cstring>
#include <vector>
#include <map>
#include <memory>
#include <set>
#include <unordered_map>
#include <bf_rt/bf_rt_session.hpp>
#include <bf_rt/bf_rt_table_data.hpp>
#include <bf_rt/bf_rt_table_key.hpp>
#include <bf_rt/bf_rt_table_attributes.hpp>
#include <bf_rt/bf_rt_table_operations.hpp>
namespace bfrt {
// Forward declarations
enum class TableAttributesIdleTableMode;
/**
* @brief Class for Annotations. Contains 2 strings to uniquely identify an
* annotation. These annotations can be on a Table, Action, Key or Data Field
*
* Possible list of annotations are below. This list is not exhaustive since
* pragmas can be annotations too like alpm_partition ones which will vary
* according to the params given ->
* 1. ("$bfrt_field_class","register_data") If a Data field is a register data.
* Register data fields are to be set using one value but while
* tableEntryGet, this field returns a vector(one value for each field)
* 2. ("$bfrt_port_type_class","dev_port") If the data field is a dev_port.
* 3. ("$bfrt_port_type_class","port_hdl_conn_id") If the data field is a port
* handle conn ID.
* 4. ("$bfrt_port_type_class","port_hdl_chnl_id") If the data field is a port
* handle channel ID.
* 5. ("$bfrt_port_type_class","port_name") If the data field is a port name.
* 6. ("$bfrt_port_type_class","fp_port") If the data field is a front panel
* port.
* 7. ("isFieldSlice","true") If a Data field is a slice of bigger field.
* 8. ("@defaultonly","") If an action is to be default only
* 9. ("$bfrt_field_imp_level", "level") Importance level of a field. All
*fields
* start off with an importance level of 1
*/
class Annotation {
public:
Annotation(std::string name, std::string value) : name_(name), value_(value) {
full_name_ = name_ + "." + value_;
};
bool operator<(const Annotation &other) const;
bool operator==(const Annotation &other) const;
bool operator==(const std::string &other_str) const;
bf_status_t fullNameGet(std::string *fullName) const;
const std::string name_{""};
const std::string value_{""};
struct Less {
bool operator()(const Annotation &lhs, const Annotation &rhs) const {
return lhs < rhs;
}
};
private:
std::string full_name_{""};
};
/**
* @brief We wrap the annotation in a reference wrapper because we want to send
* the actual object to the API user and not a copy.
*/
using AnnotationSet =
std::set<std::reference_wrapper<const Annotation>, Annotation::Less>;
/**
* @brief Class to contain metadata of Table Objs like Data and Key Fields,
* and perform functions like EntryAdd, AttributeSet, OperationsExecute etc<br>
* <B>Creation: </B> Cannot be created. can only be queried from \ref
* bfrt::BfRtInfo
*/
class BfRtTable {
public:
/**
* @brief Enum of Flags needed for Table Get Request
* (Deprecated. Please use generic flag support)
*/
enum class BfRtTableGetFlag {
/** Read from hw */
GET_FROM_HW,
/** Read from sw value */
GET_FROM_SW
};
/**
* @brief Enum of Flags needed for Table Modify Incremental Request
* (Deprecated. Please use generic flag support)
*/
enum class BfRtTableModIncFlag {
/** Flag to add the given data incrementally to the
existing table entry */
MOD_INC_ADD = 0,
/** Flag to delete the given data from the
existing table entry */
MOD_INC_DELETE = 1
};
/**
* @brief Table types. Users are discouraged from using this especially when
* creating table-agnostic generic applications like a CLI or RPC server
*/
enum class TableType {
/** Match action table*/
MATCH_DIRECT = 0,
/** Match action table with actions of the table implemented using an
"ActionProfile" */
MATCH_INDIRECT = 1,
/** Match action table with actions of the table implemented using an
"ActionSelector"*/
MATCH_INDIRECT_SELECTOR = 2,
/** Action Profile table*/
ACTION_PROFILE = 3,
/** Action Selector table*/
SELECTOR = 4,
/** Counter table*/
COUNTER = 5,
/** Meter table*/
METER = 6,
/** Register table*/
REGISTER = 7,
/** Port Metadata table.*/
PORT_METADATA = 11,
/** Port Configuration */
PORT_CFG = 15,
/** Port Stats */
PORT_STAT = 16,
/** Port Hdl to Dev_port Conversion table */
PORT_HDL_INFO = 17,
/** Front panel Idx to Dev_port Conversion table */
PORT_FRONT_PANEL_IDX_INFO = 18,
/** Port Str to Dev_port Conversion table */
PORT_STR_INFO = 19,
/** Mirror configuration table */
MIRROR_CFG = 30,
/** Device Config Table */
DEV_CFG = 36,
/** Debug Counters table */
DBG_CNT = 57,
/** Logical table debug debug counters table */
LOG_DBG_CNT = 58,
/** Register param table */
REG_PARAM = 64,
/** Action Selector Get Member table */
SELECTOR_GET_MEMBER = 69,
INVALID = 76
};
/**
* @brief enum of table APIs available
*/
enum class TableApi {
/** Entry Add. Most common API. Applicable to most tables*/
ADD = 0,
/** Entry Modify. Applicable to most tables*/
MODIFY = 1,
/** Entry Modify incremental. Useful in cases where the data is an
array and only one element needs to be changed.*/
MODIFY_INC = 2,
/** Entry Delete. Not applicable for some tables like counter,
register, meter*/
DELETE = 3,
/** Clear. Only applicable for tables which have DELETE right now*/
CLEAR = 4,
/** Default Entry Set. Only applicable for Match
action tables, direct or indirect. If table has
const default action, then this would fail*/
DEFAULT_ENTRY_SET = 5,
/** Default Entry Reset. Only applicable for Match
action tables, direct or indirect. Idempotent*/
DEFAULT_ENTRY_RESET = 6,
/** Default Entry Get. Only applicable for Match
action tables, direct or indirect.*/
DEFAULT_ENTRY_GET = 7,
/** Entry Get. Applicable to most tables.*/
GET = 8,
/** Entry Get First. Applicable to most tables.*/
GET_FIRST = 9,
/** Entry Get Next n entries. Applicable for most tables*/
GET_NEXT_N = 10,
/** Get Usage. get the current usage of the tables. Not applicable
for some tables like counter, register, meter */
USAGE_GET = 11,
/** Get entry by handle instead of key. */
GET_BY_HANDLE = 12,
/** Get entry key by handle. */
KEY_GET = 13,
/** Get entry handle from key. */
HANDLE_GET = 14,
/** Invalid not supported API. */
INVALID_API = 15
};
/**
* @brief Vector of pair of Key and Data. The key and data need to be
* allocated
* and pushed in the vector before being passed in to the appropriate Get API.
*/
using keyDataPairs = std::vector<std::pair<BfRtTableKey *, BfRtTableData *>>;
virtual ~BfRtTable() = default;
//// Table APIs
/**
* @name Table APIs
* @{
*/
/**
* @name Old flags wrapper section
* @{
*/
/**
* @brief Add an entry to the table
* @deprecated Please use function version with new flags argument.
*
* @param[in] session Session Object
* @param[in] dev_tgt Device target
* @param[in] key Entry Key
* @param[in] data Entry Data
*
* @return Status of the API call
*/
virtual bf_status_t tableEntryAdd(const BfRtSession &session,
const bf_rt_target_t &dev_tgt,
const BfRtTableKey &key,
const BfRtTableData &data) const = 0;
/**
* @brief Modify an existing entry of the table
* @deprecated Please use function version with new flags argument.
*
* @param[in] session Session Object
* @param[in] dev_tgt Device target
* @param[in] key Entry Key
* @param[in] data Entry Data
*
* @return Status of the API call
*/
virtual bf_status_t tableEntryMod(const BfRtSession &session,
const bf_rt_target_t &dev_tgt,
const BfRtTableKey &key,
const BfRtTableData &data) const = 0;
/**
* @brief Modify only a part of an existing entry of the table.
* - Either add or delete the given data to the existing entry.
* @deprecated Please use function version with new flags argument.
*
* @param[in] session Session Object
* @param[in] dev_tgt Device target
* @param[in] key Entry Key
* @param[in] data Entry Data
* @param[in] flag Modify inc flag (ADD or DEL)
*
* @return Status of the API call
*/
virtual bf_status_t tableEntryModInc(
const BfRtSession &session,
const bf_rt_target_t &dev_tgt,
const BfRtTableKey &key,
const BfRtTableData &data,
const BfRtTable::BfRtTableModIncFlag &flag) const = 0;
/**
* @brief Delete an entry of the table
* @deprecated Please use function version with new flags argument.
*
* @param[in] session Session Object
* @param[in] dev_tgt Device target
* @param[in] key Entry Key
*
* @return Status of the API call
*/
virtual bf_status_t tableEntryDel(const BfRtSession &session,
const bf_rt_target_t &dev_tgt,
const BfRtTableKey &key) const = 0;
/**
* @brief Clear a table. Delete all entries.
* @deprecated Please use function version with new flags argument.
*
* @param[in] session Session Object
* @param[in] dev_tgt Device target
*
* @return Status of the API call
*/
virtual bf_status_t tableClear(const BfRtSession &session,
const bf_rt_target_t &dev_tgt) const = 0;
/**
* @brief Set the default Entry of the table
* @deprecated Please use function version with new flags argument.
*
* @details There can be a P4 defined default entry with parameters. This API
* modifies any existing default entry to the one passed in here. Note that
* this API is idempotent and should be called either when modifying an
* existing default entry or to program one newly. There could be a particular
* action which is designated as a default-only action. In that case, an error
* is returned if the action id of the data object passed in here is different
* from the designated default action.
*
* @param[in] session Session Object
* @param[in] dev_tgt Device target
* @param[in] data Entry Data
*
* @return Status of the API call
*/
virtual bf_status_t tableDefaultEntrySet(const BfRtSession &session,
const bf_rt_target_t &dev_tgt,
const BfRtTableData &data) const = 0;
/**
* @brief Reset the default Entry of the table
* @deprecated Please use function version with new flags argument.
*
* @details The default entry of the table is reset to the P4 specified
* default action with parameters, if it exists, else its reset to a "no-op"
*
* @param[in] session Session Object
* @param[in] dev_tgt Device target
*
* @return Status of the API call
*/
virtual bf_status_t tableDefaultEntryReset(
const BfRtSession &session, const bf_rt_target_t &dev_tgt) const = 0;
/**
* @brief Get the default Entry of the table
* @deprecated Please use function version with new flags argument.
*
* @details The default entry returned will be the one programmed or the P4
* defined one, if it exists. Note that, when the entry is obtained from
* software, the P4 defined default entry will not be available if the default
* entry was not programmed ever. However, when the entry is obtained from
* hardware, the P4 defined default entry will be returned even if the default
* entry was not programmed ever.
*
* @param[in] session Session Object
* @param[in] dev_tgt Device target
* @param[in] flag Get Flags
* @param[inout] data Entry Data, if not empty will be used to filter
* returned fields
*
* @return Status of the API call
*/
virtual bf_status_t tableDefaultEntryGet(
const BfRtSession &session,
const bf_rt_target_t &dev_tgt,
const BfRtTable::BfRtTableGetFlag &flag,
BfRtTableData *data) const = 0;
/**
* @brief Get an entry from the table
* @deprecated Please use function version with new flags argument.
*
* @param[in] session Session Object
* @param[in] dev_tgt Device target
* @param[in] key Entry Key
* @param[in] flag Get Flags
* @param[inout] data Entry Data, if not empty will be used to filter
* returned fields
*
* @return Status of the API call
*/
virtual bf_status_t tableEntryGet(const BfRtSession &session,
const bf_rt_target_t &dev_tgt,
const BfRtTableKey &key,
const BfRtTable::BfRtTableGetFlag &flag,
BfRtTableData *data) const = 0;
/**
* @brief Get an entry from the table by handle
* @deprecated Please use function version with new flags argument.
*
* @param[in] session Session Object
* @param[in] dev_tgt Device target
* @param[in] flag Get Flags
* @param[in] entry_handle Handle to the entry
* @param[out] key Entry Key
* @param[inout] data Entry Data, if not empty will be used to filter
* returned fields
*
* @return Status of the API call
*/
virtual bf_status_t tableEntryGet(const BfRtSession &session,
const bf_rt_target_t &dev_tgt,
const BfRtTable::BfRtTableGetFlag &flag,
const bf_rt_handle_t &entry_handle,
BfRtTableKey *key,
BfRtTableData *data) const = 0;
/**
* @brief Get an entry key from the table by handle
* @deprecated Please use function version with new flags argument.
*
* @param[in] session Session Object
* @param[in] dev_tgt Device target
* @param[in] entry_handle Handle to the entry
* @param[out] entry_tgt Target device for specified entry handle,
* may not match dev_tgt values
* @param[out] key Entry Key
*
* @return Status of the API call
*/
virtual bf_status_t tableEntryKeyGet(const BfRtSession &session,
const bf_rt_target_t &dev_tgt,
const bf_rt_handle_t &entry_handle,
bf_rt_target_t *entry_tgt,
BfRtTableKey *key) const = 0;
/**
* @brief Get an entry handle from the table
* @deprecated Please use function version with new flags argument.
*
* @param[in] session Session Object
* @param[in] dev_tgt Device target
* @param[in] key Entry Key
* @param[out] entry_handle Handle to the entry
*
* @return Status of the API call
*/
virtual bf_status_t tableEntryHandleGet(
const BfRtSession &session,
const bf_rt_target_t &dev_tgt,
const BfRtTableKey &key,
bf_rt_handle_t *entry_handle) const = 0;
/**
* @brief Get the first entry of the table
* @deprecated Please use function version with new flags argument.
*
* @param[in] session Session Object
* @param[in] dev_tgt Device target
* @param[in] flag Get Flags
* @param[out] key Entry Key
* @param[inout] data Entry Data, if not empty will be used to filter
* returned fields
*
* @return Status of the API call
*/
virtual bf_status_t tableEntryGetFirst(
const BfRtSession &session,
const bf_rt_target_t &dev_tgt,
const BfRtTable::BfRtTableGetFlag &flag,
BfRtTableKey *key,
BfRtTableData *data) const = 0;
/**
* @brief Get next N entries of the table following the entry that is
* specificed by key.
* If the N queried for is greater than the actual entries, then
* all the entries present are returned.
* N must be greater than zero.
* @deprecated Please use function version with new flags argument.
*
* @param[in] session Session Object
* @param[in] dev_tgt Device target
* @param[in] key Entry Key from which N entries are queried
* @param[in] n Number of entries queried 'N'
* @param[in] flag Get Flags
* @param[out] key_data_pairs Vector of N Pairs(key, data). This vector needs
* to have N entries before the API call is made, else error is returned
* @param[out] num_returned Actual number of entries returned
*
* @return Status of the API call
*/
virtual bf_status_t tableEntryGetNext_n(
const BfRtSession &session,
const bf_rt_target_t &dev_tgt,
const BfRtTableKey &key,
const uint32_t &n,
const BfRtTable::BfRtTableGetFlag &flag,
keyDataPairs *key_data_pairs,
uint32_t *num_returned) const = 0;
/**
* @brief Current Usage of the table
* @deprecated Please use function version with new flags argument.
*
* @param[in] session Session Object
* @param[in] dev_tgt Device target
* @param[in] flag Get Flags
* @param[out] count Table usage
*
* @return Status of the API call
*/
virtual bf_status_t tableUsageGet(const BfRtSession &session,
const bf_rt_target_t &dev_tgt,
const BfRtTable::BfRtTableGetFlag &flag,
uint32_t *count) const = 0;
/**
* @brief The maximum size of the table. Note that this size might
* be different than present in bf-rt.json especially for Match Action
* Tables. This is because sometimes MATs might reserve some space for
* atomic modfies and hence might be 1 or 2 < json size
* @deprecated Please use function version with new flags argument.
*
* @param[in] session Session Object
* @param[in] dev_tgt Device target
* @param[out] size Number of total available entries
*
* @return Status of the API call
*/
virtual bf_status_t tableSizeGet(const BfRtSession &session,
const bf_rt_target_t &dev_tgt,
size_t *size) const = 0;
/** @} */ // End of old flags wrapper section */
/**
* @brief Add an entry to the table
*
* @param[in] session Session Object
* @param[in] dev_tgt Device target
* @param[in] flags Call flags
* @param[in] key Entry Key
* @param[in] data Entry Data
*
* @return Status of the API call
*/
virtual bf_status_t tableEntryAdd(const BfRtSession &session,
const bf_rt_target_t &dev_tgt,
const uint64_t &flags,
const BfRtTableKey &key,
const BfRtTableData &data) const = 0;
/**
* @brief Modify an existing entry of the table
*
* @param[in] session Session Object
* @param[in] dev_tgt Device target
* @param[in] flags Call flags
* @param[in] key Entry Key
* @param[in] data Entry Data
*
* @return Status of the API call
*/
virtual bf_status_t tableEntryMod(const BfRtSession &session,
const bf_rt_target_t &dev_tgt,
const uint64_t &flags,
const BfRtTableKey &key,
const BfRtTableData &data) const = 0;
/**
* @brief Modify only a part of an existing entry of the table.
* - Either add or delete the given data to the existing entry.
*
* @param[in] session Session Object
* @param[in] dev_tgt Device target
* @param[in] flags Call flags
* @param[in] key Entry Key
* @param[in] data Entry Data
* @param[in] flag Modify inc flag (ADD or DEL)
*
* @return Status of the API call
*/
virtual bf_status_t tableEntryModInc(const BfRtSession &session,
const bf_rt_target_t &dev_tgt,
const uint64_t &flags,
const BfRtTableKey &key,
const BfRtTableData &data) const = 0;
/**
* @brief Delete an entry of the table
*
* @param[in] session Session Object
* @param[in] dev_tgt Device target
* @param[in] flags Call flags
* @param[in] key Entry Key
*
* @return Status of the API call
*/
virtual bf_status_t tableEntryDel(const BfRtSession &session,
const bf_rt_target_t &dev_tgt,
const uint64_t &flags,
const BfRtTableKey &key) const = 0;
/**
* @brief Clear a table. Delete all entries. This API also resets default
* entry if present and is not const default. If table has always present
* entries like Counter table, then this table resets all the entries
* instead.
*
* @param[in] session Session Object
* @param[in] dev_tgt Device target
* @param[in] flags Call flags
*
* @return Status of the API call
*/
virtual bf_status_t tableClear(const BfRtSession &session,
const bf_rt_target_t &dev_tgt,
const uint64_t &flags) const = 0;
/**
* @brief Set the default Entry of the table
*
* @details There can be a P4 defined default entry with parameters. This API
* modifies any existing default entry to the one passed in here. Note that
* this API is idempotent and should be called either when modifying an
* existing default entry or to program one newly. There could be a particular
* action which is designated as a default-only action. In that case, an error
* is returned if the action id of the data object passed in here is different
* from the designated default action.
*
* @param[in] session Session Object
* @param[in] dev_tgt Device target
* @param[in] flags Call flags
* @param[in] data Entry Data
*
* @return Status of the API call
*/
virtual bf_status_t tableDefaultEntrySet(const BfRtSession &session,
const bf_rt_target_t &dev_tgt,
const uint64_t &flags,
const BfRtTableData &data) const = 0;
/**
* @brief Reset the default Entry of the table
*
* @details The default entry of the table is reset to the P4 specified
* default action with parameters, if it exists, else its reset to a "no-op"
*
* @param[in] session Session Object
* @param[in] dev_tgt Device target
* @param[in] flags Call flags
*
* @return Status of the API call
*/
virtual bf_status_t tableDefaultEntryReset(const BfRtSession &session,
const bf_rt_target_t &dev_tgt,
const uint64_t &flags) const = 0;
/**
* @brief Get the default Entry of the table
*
* @details The default entry returned will be the one programmed or the P4
* defined one, if it exists. Note that, when the entry is obtained from
* software, the P4 defined default entry will not be available if the default
* entry was not programmed ever. However, when the entry is obtained from
* hardware, the P4 defined default entry will be returned even if the default
* entry was not programmed ever.
*
* @param[in] session Session Object
* @param[in] dev_tgt Device target
* @param[in] flags Call flags
* @param[inout] data Entry Data, if not empty will be used to filter
* returned fields
*
* @return Status of the API call
*/
virtual bf_status_t tableDefaultEntryGet(const BfRtSession &session,
const bf_rt_target_t &dev_tgt,
const uint64_t &flags,
BfRtTableData *data) const = 0;
/**
* @brief Get an entry from the table
*
* @param[in] session Session Object
* @param[in] dev_tgt Device target
* @param[in] flags Call flags
* @param[in] key Entry Key
* @param[inout] data Entry Data, if not empty will be used to filter
* returned fields
*
* @return Status of the API call
*/
virtual bf_status_t tableEntryGet(const BfRtSession &session,
const bf_rt_target_t &dev_tgt,
const uint64_t &flags,
const BfRtTableKey &key,
BfRtTableData *data) const = 0;
/**
* @brief Get an entry from the table by handle
*
* @param[in] session Session Object
* @param[in] dev_tgt Device target
* @param[in] flags Call flags
* @param[in] entry_handle Handle to the entry
* @param[out] key Entry Key
* @param[inout] data Entry Data, if not empty will be used to filter
* returned fields
*
* @return Status of the API call
*/
virtual bf_status_t tableEntryGet(const BfRtSession &session,
const bf_rt_target_t &dev_tgt,
const uint64_t &flags,
const bf_rt_handle_t &entry_handle,
BfRtTableKey *key,
BfRtTableData *data) const = 0;
/**
* @brief Get an entry key from the table by handle
*
* @param[in] session Session Object
* @param[in] dev_tgt Device target
* @param[in] flags Call flags
* @param[in] entry_handle Handle to the entry
* @param[out] entry_tgt Target device for specified entry handle,
* may not match dev_tgt values
* @param[out] key Entry Key
*
* @return Status of the API call
*/
virtual bf_status_t tableEntryKeyGet(const BfRtSession &session,
const bf_rt_target_t &dev_tgt,
const uint64_t &flags,
const bf_rt_handle_t &entry_handle,
bf_rt_target_t *entry_tgt,
BfRtTableKey *key) const = 0;
/**
* @brief Get an entry handle from the table
*
* @param[in] session Session Object
* @param[in] dev_tgt Device target
* @param[in] flags Call flags
* @param[in] key Entry Key
* @param[out] entry_handle Handle to the entry
*
* @return Status of the API call
*/
virtual bf_status_t tableEntryHandleGet(
const BfRtSession &session,
const bf_rt_target_t &dev_tgt,
const uint64_t &flags,
const BfRtTableKey &key,
bf_rt_handle_t *entry_handle) const = 0;
/**
* @brief Get the first entry of the table
*
* @param[in] session Session Object
* @param[in] dev_tgt Device target
* @param[in] flags Call flags
* @param[out] key Entry Key
* @param[inout] data Entry Data, if not empty will be used to filter
* returned fields
*
* @return Status of the API call
*/
virtual bf_status_t tableEntryGetFirst(const BfRtSession &session,
const bf_rt_target_t &dev_tgt,
const uint64_t &flags,
BfRtTableKey *key,
BfRtTableData *data) const = 0;
/**
* @brief Get next N entries of the table following the entry that is
* specificed by key.
* If the N queried for is greater than the actual entries, then
* all the entries present are returned.
* N must be greater than zero.
*
* @param[in] session Session Object
* @param[in] dev_tgt Device target
* @param[in] flags Call flags
* @param[in] key Entry Key from which N entries are queried
* @param[in] n Number of entries queried 'N'
* @param[out] key_data_pairs Vector of N Pairs(key, data). This vector needs
* to have N entries before the API call is made, else error is returned
* @param[out] num_returned Actual number of entries returned
*
* @return Status of the API call
*/
virtual bf_status_t tableEntryGetNext_n(const BfRtSession &session,
const bf_rt_target_t &dev_tgt,
const uint64_t &flags,
const BfRtTableKey &key,
const uint32_t &n,
keyDataPairs *key_data_pairs,
uint32_t *num_returned) const = 0;
/**
* @brief Current Usage of the table
*
* @param[in] session Session Object
* @param[in] dev_tgt Device target
* @param[in] flags Call flags
* @param[out] count Table usage
*
* @return Status of the API call
*/
virtual bf_status_t tableUsageGet(const BfRtSession &session,
const bf_rt_target_t &dev_tgt,
const uint64_t &flags,
uint32_t *count) const = 0;
/**
* @brief The maximum size of the table. Note that this size might
* be different than present in bf-rt.json especially for Match Action
* Tables. This is because sometimes MATs might reserve some space for
* atomic modfies and hence might be 1 or 2 < json size
*
* @param[in] session Session Object
* @param[in] dev_tgt Device target
* @param[in] flags Call flags
* @param[out] size Number of total available entries
*
* @return Status of the API call
*/
virtual bf_status_t tableSizeGet(const BfRtSession &session,
const bf_rt_target_t &dev_tgt,
const uint64_t &flags,
size_t *size) const = 0;
/***** End of APIs with flags *******/
/**
* @brief Get name of the table
*
* @param[out] name Name of the table
*
* @return Status of the API call
*/
virtual bf_status_t tableNameGet(std::string *name) const = 0;
/**
* @brief Get ID of the table
*
* @param[out] id ID of the table
*
* @return Status of the API call
*/
virtual bf_status_t tableIdGet(bf_rt_id_t *id) const = 0;
/**
* @brief The type of the table
*
* @param[out] table_type Type of the table
*
* @return Status of the API call
*/
virtual bf_status_t tableTypeGet(BfRtTable::TableType *table_type) const = 0;
/**
* @brief Get whether this table has a const default action
*
* @param[out] has_const_default_action If default action is const
*
* @return Status of the API call
*/
virtual bf_status_t tableHasConstDefaultAction(
bool *has_const_default_action) const = 0;
/**
* @brief Get whether this table is a const table
*
* @param[out] is_const If table is const
*
* @return Status of the API call
*/
virtual bf_status_t tableIsConst(bool *is_const) const = 0;
/**
* @brief Get a set of annotations on a Table
*
* @param[out] annotations Set of annotations on a Table
*
* @return Status of the API call
*/
virtual bf_status_t tableAnnotationsGet(AnnotationSet *annotations) const = 0;
using TableApiSet = std::set<std::reference_wrapper<const TableApi>>;
/**
* @brief Get a set of APIs which are supported by this table.
*
* @param[out] tableApiset The set of APIs which are supported by this table
*
* @return Status of the API call
*/
virtual bf_status_t tableApiSupportedGet(TableApiSet *tableApis) const = 0;
/** @} */ // End of group Table
//// Key APIs
/**
* @name Key APIs
* @{
*/
/**
* @brief Allocate key for the table
*
* @param[out] key_ret Key object returned
*
* @return Status of the API call
*/
virtual bf_status_t keyAllocate(
std::unique_ptr<BfRtTableKey> *key_ret) const = 0;
/**
* @brief Get a vector of Key field IDs
*
* @param[out] id Vector of Key field IDs
*
* @return Status of the API call
*/
virtual bf_status_t keyFieldIdListGet(std::vector<bf_rt_id_t> *id) const = 0;
/**
* @brief Get field type of Key Field
*
* @param[in] field_id Field ID
* @param[out] field_type Field Type (Exact/Ternary/LPM/Range)
*
* @return Status of the API call
*/
virtual bf_status_t keyFieldTypeGet(const bf_rt_id_t &field_id,
KeyFieldType *field_type) const = 0;
/**
* @brief Get data type of Key Field
*
* @param[in] field_id Field ID
* @param[out] data_type Field Type (uint64, float, string)
*
* @return Status of the API call
*/
virtual bf_status_t keyFieldDataTypeGet(const bf_rt_id_t &field_id,
DataType *data_type) const = 0;
/**
* @brief Get field ID of Key Field from name
*
* @param[in] name Key Field name
* @param[out] field_id Field ID
*
* @return Status of the API call
*/
virtual bf_status_t keyFieldIdGet(const std::string &name,
bf_rt_id_t *field_id) const = 0;
/**
* @brief Get field size
*
* @param[in] field_id Field ID
* @param[out] size Field Size in bits
*
* @return Status of the API call
*/
virtual bf_status_t keyFieldSizeGet(const bf_rt_id_t &field_id,
size_t *size) const = 0;
/**
* @brief Get whether Key Field is of type ptr or not. If the field is
* of ptr type, then only ptr sets/gets are applicable on the field. Else
* both the ptr versions and the uint64_t versions work
*
* @param[in] field_id Field ID
* @param[out] is_ptr Boolean type indicating whether Field is of type ptr
*
* @return Status of the API call
*/
virtual bf_status_t keyFieldIsPtrGet(const bf_rt_id_t &field_id,
bool *is_ptr) const = 0;
/**
* @brief Get name of field
*
* @param[in] field_id Field ID
* @param[out] name Field name
*
* @return Status of the API call
*/
virtual bf_status_t keyFieldNameGet(const bf_rt_id_t &field_id,
std::string *name) const = 0;
/**
* @brief Reset the key object associated with the table
*
* @param[inout] Pointer to a key object, previously allocated using
* keyAllocate on the table.
*
* @return Status of the API call. Error is returned if the key object is not
*associated with the table.
*/
virtual bf_status_t keyReset(BfRtTableKey *key) const = 0;
/**
* @brief Get a list of all the allowed values that a particular field can
* have. This API is only for fields with string type. If the returned
* vector is empty, it indicates that the allowed choices have not been
* published in bfrt json
*
* @param[in] field_id Field ID
* @param[out] choices Vector of const references of the values that are
* allowed for this field
*
* @return Status of the API call
*/
virtual bf_status_t keyFieldAllowedChoicesGet(
const bf_rt_id_t &field_id,
std::vector<std::reference_wrapper<const std::string>> *choices)
const = 0;
/** @} */ // End of group Key
//// Data APIs
/**
* @name Data APIs
* There are 2 base versions of every Data API. One, which takes in an
* action_id and another which doesn't. If action_id is specified it will
* always be set.
*
* @{
*/
/**
* @brief Allocate Data Object for the table
*
* @param[out] data_ret Data Object returned
*
* @return Status of the API call
*/
virtual bf_status_t dataAllocate(
std::unique_ptr<BfRtTableData> *data_ret) const = 0;
/**
* @brief Allocate Data Object for the table
*
* @param[in] action_id Action ID
* @param[out] data_ret Data Object returned
*
* @return Status of the API call
*/
virtual bf_status_t dataAllocate(
const bf_rt_id_t &action_id,
std::unique_ptr<BfRtTableData> *data_ret) const = 0;
/**
* @brief Data Allocate with a list of field-ids. This allocates the data
* object for
* the list of field-ids. The field-ids passed must be valid for this table.
* The Data Object then entertains APIs to read/write only those set of fields
*
* @param[in] fields Vector of field IDs
* @param[out] data_ret Data Object returned
*
* @return Status of the API call
*/
virtual bf_status_t dataAllocate(
const std::vector<bf_rt_id_t> &fields,
std::unique_ptr<BfRtTableData> *data_ret) const = 0;
/**
* @brief Data Allocate with a list of field-ids. This allocates the data
* object for
* the list of field-ids. The field-ids passed must be valid for this table.
* The Data Object then entertains APIs to read/write only those set of fields
*
* @param[in] fields Vector of field IDs
* @param[in] action_id Action ID
* @param[out] data_ret Data Object returned
*
* @return Status of the API call
*/
virtual bf_status_t dataAllocate(
const std::vector<bf_rt_id_t> &fields,
const bf_rt_id_t &action_id,
std::unique_ptr<BfRtTableData> *data_ret) const = 0;
/**
* @brief Data Allocate for a container field ID. Container ID
* is field ID of a container field. If container ID doesn't
* exist, then the API will fail
*
* @param[in] container_id Field ID of container
* @param[out] data_ret Data Object returned
*
* @return Status of the API call
*/
virtual bf_status_t dataAllocateContainer(
const bf_rt_id_t &container_id,
std::unique_ptr<BfRtTableData> *data_ret) const = 0;
/**
* @brief Data Allocate for a container field ID. Container ID
* is field ID of a container field. If container ID doesn't
* exist for the action ID, the API will fail
*
* @param[in] container_id Field ID of container
* @param[in] action_id Action ID
* @param[out] data_ret Data Object returned
*
* @return Status of the API call
*/
virtual bf_status_t dataAllocateContainer(
const bf_rt_id_t &container_id,
const bf_rt_id_t &action_id,
std::unique_ptr<BfRtTableData> *data_ret) const = 0;
/**
* @brief Data Allocate for a container field ID. Container ID
* is field ID of a container field. If container ID doesn't
* exist, then the API will fail. The field ID list should
* contain fields only pertaining to the container for mod/
* get
*
* @param[in] container_id Field ID of container
* @param[in] fields Vector of field IDs
* @param[out] data_ret Data Object returned
*
* @return Status of the API call
*/
virtual bf_status_t dataAllocateContainer(
const bf_rt_id_t &container_id,
const std::vector<bf_rt_id_t> &fields,
std::unique_ptr<BfRtTableData> *data_ret) const = 0;
/**
* @brief Data Allocate for a container field ID. Container ID
* is field ID of a container field. If container ID doesn't
* exist in the action ID, then the API will fail.
* The field ID list should
* contain fields only pertaining to the container for mod/
* get
*
* @param[in] container_id Field ID of container
* @param[in] fields Vector of field IDs
* @param[in] action_id Action ID
* @param[out] data_ret Data Object returned
*
* @return Status of the API call
*/
virtual bf_status_t dataAllocateContainer(
const bf_rt_id_t &container_id,
const std::vector<bf_rt_id_t> &fields,
const bf_rt_id_t &action_id,
std::unique_ptr<BfRtTableData> *data_ret) const = 0;
/**
* @brief Get vector of DataField IDs. Only applicable for tables
* without Action IDs
*
* @param[out] id Vector of IDs
*
* @return Status of the API call
*/
virtual bf_status_t dataFieldIdListGet(std::vector<bf_rt_id_t> *id) const = 0;
/**
* @brief Get vector of DataField IDs for a particular action. If action
* doesn't exist, then common fields list is returned.
*
* @param[in] action_id Action ID
* @param[out] id Vector of IDs
*
* @return Status of the API call
*/
virtual bf_status_t dataFieldIdListGet(const bf_rt_id_t &action_id,
std::vector<bf_rt_id_t> *id) const = 0;
/**
* @brief Get vector of DataField IDs for a container's field id.
*
* @param[in] field Field ID of container
* @param[out] id Vector of IDs
*
* @return Status of the API call
*/
virtual bf_status_t containerDataFieldIdListGet(
const bf_rt_id_t &field_id, std::vector<bf_rt_id_t> *id) const = 0;
/**
* @brief Get the field ID of a Data Field from a name.
*
* @param[in] name Name of a Data field
* @param[out] field_id Field ID
*
* @return Status of the API call
*/
virtual bf_status_t dataFieldIdGet(const std::string &name,
bf_rt_id_t *field_id) const = 0;
/**
* @brief Get the field ID of a Data Field from a name
*
* @param[in] name Name of a Data field
* @param[in] action_id Action ID
* @param[out] field_id Field ID
*
* @return Status of the API call
*/
virtual bf_status_t dataFieldIdGet(const std::string &name,
const bf_rt_id_t &action_id,
bf_rt_id_t *field_id) const = 0;
/**
* @brief Get the Size of a field.
* For container fields this function will return number
* of elements inside the container.
*
* @param[in] field_id Field ID
* @param[out] size Size of the field in bits
*
* @return Status of the API call
*/
virtual bf_status_t dataFieldSizeGet(const bf_rt_id_t &field_id,
size_t *size) const = 0;
/**
* @brief Get the Size of a field.
*
* @param[in] field_id Field ID
* @param[in] action_id Action ID
* @param[out] size Size of the field in bits
*
* @return Status of the API call
*/
virtual bf_status_t dataFieldSizeGet(const bf_rt_id_t &field_id,
const bf_rt_id_t &action_id,
size_t *size) const = 0;
/**
* @brief Get whether a field is a ptr type.
* Only the ptr versions of setValue/getValue will work on fields
* for which this API returns true
*
* @param[in] field_id Field ID
* @param[out] is_ptr Boolean value indicating if it is ptr type
*
* @return Status of the API call
*/
virtual bf_status_t dataFieldIsPtrGet(const bf_rt_id_t &field_id,
bool *is_ptr) const = 0;
/**
* @brief Get whether a field is a ptr type.
* Only the ptr versions of setValue/getValue will work on fields
* for which this API returns true
*
* @param[in] field_id Field ID
* @param[in] action_id Action ID
* @param[out] is_ptr Boolean value indicating if it is ptr type
*
* @return Status of the API call
*/
virtual bf_status_t dataFieldIsPtrGet(const bf_rt_id_t &field_id,
const bf_rt_id_t &action_id,
bool *is_ptr) const = 0;
/**
* @brief Get whether a field is mandatory.
*
* @param[in] field_id Field ID
* @param[out] is_mandatory Boolean value indicating if it is mandatory
*
* @return Status of the API call
*/
virtual bf_status_t dataFieldMandatoryGet(const bf_rt_id_t &field_id,
bool *is_mandatory) const = 0;
/**
* @brief Get whether a field is mandatory.
*
* @param[in] field_id Field ID
* @param[in] action_id Action ID
* @param[out] is_mandatory Boolean value indicating if it is mandatory
*
* @return Status of the API call
*/
virtual bf_status_t dataFieldMandatoryGet(const bf_rt_id_t &field_id,
const bf_rt_id_t &action_id,
bool *is_mandatory) const = 0;
/**
* @brief Get whether a field is ReadOnly.
*
* @param[in] field_id Field ID
* @param[out] is_read_only Boolean value indicating if it is ReadOnly
*
* @return Status of the API call
*/
virtual bf_status_t dataFieldReadOnlyGet(const bf_rt_id_t &field_id,
bool *is_read_only) const = 0;
/**
* @brief Get the IDs of oneof siblings of a field. If a field is part of a
* oneof , for example, consider $ACTION_MEMBER_ID and $SELECTOR_GROUP_ID. then
* this API will return [field_ID($ACTION_MEMBER_ID)] for $SELECTOR_GROUP_ID.
*
*
* @param[in] field_id Field ID
* @param[out] oneof_siblings Set containing field IDs of oneof siblings
*
* @return Status of the API call
*/
virtual bf_status_t dataFieldOneofSiblingsGet(
const bf_rt_id_t &field_id,
const bf_rt_id_t &action_id,
std::set<bf_rt_id_t> *oneof_siblings) const = 0;
/**
* @brief Get the IDs of oneof siblings of a field. If a field is part of a
* oneof , for example, consider $ACTION_MEMBER_ID and $SELECTOR_GROUP_ID. then
* this API will return [field_ID($ACTION_MEMBER_ID)] for $SELECTOR_GROUP_ID.
*
*
* @param[in] field_id Field ID
* @param[out] oneof_siblings Set containing field IDs of oneof siblings
*
* @return Status of the API call
*/
virtual bf_status_t dataFieldOneofSiblingsGet(
const bf_rt_id_t &field_id,
std::set<bf_rt_id_t> *oneof_siblings) const = 0;
/**
* @brief Get whether a field is ReadOnly.
*
* @param[in] field_id Field ID
* @param[in] action_id Action ID
* @param[out] is_read_only Boolean value indicating if it is ReadOnly
*
* @return Status of the API call
*/
virtual bf_status_t dataFieldReadOnlyGet(const bf_rt_id_t &field_id,
const bf_rt_id_t &action_id,
bool *is_read_only) const = 0;
/**
* @brief Get the Name of a field.
*
* @param[in] field_id Field ID
* @param[out] name Name of the field
*
* @return Status of the API call
*/
virtual bf_status_t dataFieldNameGet(const bf_rt_id_t &field_id,
std::string *name) const = 0;
/**
* @brief Get the Name of a field
*
* @param[in] field_id Field ID
* @param[in] action_id Action ID
* @param[out] name Name of the field
*
* @return Status of the API call
*/
virtual bf_status_t dataFieldNameGet(const bf_rt_id_t &field_id,
const bf_rt_id_t &action_id,
std::string *name) const = 0;
/**
* @brief Get the Data type of a field (INT/BOOL/ENUM/INT_ARR/BOOL_ARR)
*
* @param[in] field_id Field ID
* @param[out] type Data type of a data field
*
* @return Status of the API call
*/
virtual bf_status_t dataFieldDataTypeGet(const bf_rt_id_t &field_id,
DataType *type) const = 0;
/**
* @brief Get the Data type of a field (INT/BOOL/ENUM/INT_ARR/BOOL_ARR)
*
* @param[in] field_id Field ID
* @param[in] action_id Action ID
* @param[out] type Data type of a data field
*
* @return Status of the API call
*/
virtual bf_status_t dataFieldDataTypeGet(const bf_rt_id_t &field_id,
const bf_rt_id_t &action_id,
DataType *type) const = 0;
/**
* @brief Reset the data object previously allocated using dataAllocate on the
* table
*
* @details Calling this API resets the action-id in the object to an
* invalid value. Typically this needs to be done when doing an entry get,
* since the caller does not know the action-id associated with the entry.
* Using the data object for an entry add on a table where action-id is
* applicable will result in an error.
*
* @param[in/out] data Pointer to the data object allocated using dataAllocate
* on the table.
*
* @return Status of the API call. An error is returned if the data object is
* not associated with the table
*/
virtual bf_status_t dataReset(BfRtTableData *data) const = 0;
/**
* @brief Reset the data object previously allocated using dataAllocate on the
* table
*
* @details Calling this API sets the action-id in the object to the
* passed in value.
*
* @param[in] action_id new action id of the object
* the table.
* @param[in/out] Pointer to the data object allocated using dataAllocate on
* the table.
*
* @return Status of the API call. An error is returned if the data object is
* not associated with the table or if action-id is not applicable on the
* table.
*/
virtual bf_status_t dataReset(const bf_rt_id_t &action_id,
BfRtTableData *data) const = 0;
/**
* @brief Reset the data object previously allocated using dataAllocate on the
*table
*
* @details Calling this API resets the action-id in the object to an
* invalid value. Typically this needs to be done when doing an entry get,
* since the caller does not know the action-id associated with the entry.
* Using the data object for an entry add on a table where action-id is
* applicable will result in an error. The data object will contain the passed
* in vector of field-ids active. This is typically done when reading an
* entry's fields. Note that, the fields passed in must be common data fields
* across all action-ids (common data fields, such as direct counter/direct
* meter etc), for tables on which action-id is applicable.
*
* @param[in] fields Vector of field-ids that are to be activated in the data
* object the table.
* @param[in/out] Pointer to the data object allocated using dataAllocate on
* the table.
*
* @return Status of the API call. An error is returned if the data object is
* not associated with the table, or if any field-id is action-specific, for
* tables on which action-id is applicable..
*/
virtual bf_status_t dataReset(const std::vector<bf_rt_id_t> &fields,
BfRtTableData *data) const = 0;
/**
* @brief Reset the data object previously allocated using dataAllocate on the
* table
*
* @details Calling this API sets the action-id in the object to the
* passed in value and the list of fields passed in will be active in the data
* object. The list of fields passed in must belong to the passed in action-id
* or common across all action-ids associated with the table.
*
* @param[in] fields Vector of field-ids that are to be activated in the data
* object the table.
* @param[in] action_id new action id of the object
* the table.
* @param[in/out] Pointer to the data object allocated using dataAllocate on
* the table.
*
* @return Status of the API call. An error is returned if the data object is
* not associated with the table or if action-id is not applicable on the
* table.
*/
virtual bf_status_t dataReset(const std::vector<bf_rt_id_t> &fields,
const bf_rt_id_t &action_id,
BfRtTableData *data) const = 0;
/**
* @brief Get a list of all the allowed values that a particular field can
* have. This API is only for fields with string type. If the returned
* vector is empty, it indicates that the allowed choices have not been
* published in bfrt json
*
* @param[in] field_id Field ID
* @param[out] choices Vector of const references of the values that are
* allowed for this field
*
* @return Status of the API call
*/
virtual bf_status_t dataFieldAllowedChoicesGet(
const bf_rt_id_t &field_id,
std::vector<std::reference_wrapper<const std::string>> *choices)
const = 0;
/**
* @brief Get a list of all the allowed values that a particular field can
* have. This API is only for fields with string type. If the returned
* vector is empty, it indicates that the allowed choices have not been
* published in bfrt json
*
* @param[in] field_id Field ID
* @param[in] action_id Action ID
* @param[out] choices Vector of const references of the values that are
* allowed for this field
*
* @return Status of the API call
*/
virtual bf_status_t dataFieldAllowedChoicesGet(
const bf_rt_id_t &field_id,
const bf_rt_id_t &action_id,
std::vector<std::reference_wrapper<const std::string>> *choices)
const = 0;
/**
* @brief Get a set of annotations on a data field
*
* @param[in] field_id Field ID
* @param[out] annotations Set of annotations on a data field
*
* @return Status of the API call
*/
virtual bf_status_t dataFieldAnnotationsGet(
const bf_rt_id_t &field_id, AnnotationSet *annotations) const = 0;
/**
* @brief Get a set of annotations on a data field
*
* @param[in] field_id Field ID
* @param[in] action_id Action ID
* @param[out] annotations Set of annotations on a data field
*
* @return Status of the API call
*/
virtual bf_status_t dataFieldAnnotationsGet(
const bf_rt_id_t &field_id,
const bf_rt_id_t &action_id,
AnnotationSet *annotations) const = 0;
/** @} */ // End of group Data
// Action ID APIs
/**
* @name Action ID APIs
* @{
*/
/**
* @brief Get Action ID from Name
*
* @param[in] name Action Name
* @param[out] action_id Action ID
*
* @return Status of the API call
*/
virtual bf_status_t actionIdGet(const std::string &name,
bf_rt_id_t *action_id) const = 0;
/**
* @brief Get Action Name
*
* @param[in] action_id Action ID
* @param[out] name Action Name
*
* @return Status of the API call
*/
virtual bf_status_t actionNameGet(const bf_rt_id_t &action_id,
std::string *name) const = 0;
/**
* @brief Get vector of Action IDs
*
* @param[out] action_id Vector of Action IDs
*
* @return Status of the API call
*/
virtual bf_status_t actionIdListGet(
std::vector<bf_rt_id_t> *action_id) const = 0;
/**
* @brief Are Action IDs applicable for this table
*
* @retval True : If Action ID applicable
* @retval False : If not
*
*/
virtual bool actionIdApplicable() const = 0;
/**
* @brief Get a set of annotations for this action.
*
* @param[in] action_id Action ID
* @param[out] annotations Set of annotations
*
* @return Status of the API call
*/
virtual bf_status_t actionAnnotationsGet(
const bf_rt_id_t &action_id, AnnotationSet *annotations) const = 0;
/** @} */ // End of group Action IDs
// table attribute APIs
/**
* @name Attribute APIs
* @{
*/
/**
* @brief Allocate Attribute object of the table.
*
* @param[in] type Type of the attribute
* @param[out] attr Attribute object returned
*
* @return Status of the API call
*/
virtual bf_status_t attributeAllocate(
const TableAttributesType &type,
std::unique_ptr<BfRtTableAttributes> *attr) const = 0;
/**
* @brief Allocate Attribute object of the table. This API
* is to be used when idle_table attribute is being set
*
* @param[in] type Type of the attribute
* @param[in] idle_table_type Idle table type (POLL/NOTIFY)
* @param[out] attr Attribute object returned
*
* @return Status of the API call
*/
virtual bf_status_t attributeAllocate(
const TableAttributesType &type,
const TableAttributesIdleTableMode &idle_table_type,
std::unique_ptr<BfRtTableAttributes> *attr) const = 0;
/**
* @brief Reset Attribute object of the table.
*
* @param[in] type Type of the attribute
* @param[out] attr Attribute object returned
*
* @return Status of the API call
*/
virtual bf_status_t attributeReset(
const TableAttributesType &type,
std::unique_ptr<BfRtTableAttributes> *attr) const = 0;
/**
* @brief Reset Attribute type and the Idle Table Mode
*
* @param[in] type Type of the attribute
* @param[in] idle_table_type Idle table type (POLL/NOTIFY)
* @param[out] attr Attribute object returned
*
* @return Status of the API call
*/
virtual bf_status_t attributeReset(
const TableAttributesType &type,
const TableAttributesIdleTableMode &idle_table_type,
std::unique_ptr<BfRtTableAttributes> *attr) const = 0;
/**
* @name Old flags wrapper section
* @{
*/
/**
* @brief Apply an Attribute from an Attribute Object on the
* table. Before using this API, the Attribute object needs to
* be allocated and all the necessary values need to
* be set on the Attribute object
* @deprecated Please use function version with new flags argument.
*
* @param[in] session Session Object
* @param[in] dev_tgt Device Target
* @param[in] tableAttributes Attribute Object
*
* @return Status of the API call
*/
virtual bf_status_t tableAttributesSet(
const BfRtSession &session,
const bf_rt_target_t &dev_tgt,
const BfRtTableAttributes &tableAttributes) const = 0;
/**
* @brief Get the current Attributes set on the table. The attribute
* object passed in as input param needs to be allocated first with
* the required attribute type.
* @deprecated Please use function version with new flags argument.
*
* @param[in] session Session Object
* @param[in] dev_tgt Device Target
* @param[out] tableAttributes Attribute Object
*
* @return Status of the API call
*/
virtual bf_status_t tableAttributesGet(
const BfRtSession &session,
const bf_rt_target_t &dev_tgt,
BfRtTableAttributes *tableAttributes) const = 0;
/** @} */ // End of old flags wrapper section */
/**
* @brief Apply an Attribute from an Attribute Object on the
* table. Before using this API, the Attribute object needs to
* be allocated and all the necessary values need to
* be set on the Attribute object
*
* @param[in] session Session Object
* @param[in] dev_tgt Device Target
* @param[in] flags Call flags
* @param[in] tableAttributes Attribute Object
*
* @return Status of the API call
*/
virtual bf_status_t tableAttributesSet(
const BfRtSession &session,
const bf_rt_target_t &dev_tgt,
const uint64_t &flags,
const BfRtTableAttributes &tableAttributes) const = 0;
/**
* @brief Get the current Attributes set on the table. The attribute
* object passed in as input param needs to be allocated first with
* the required attribute type.
*
* @param[in] session Session Object
* @param[in] dev_tgt Device Target
* @param[in] flags Call flags
* @param[out] tableAttributes Attribute Object
*
* @return Status of the API call
*/
virtual bf_status_t tableAttributesGet(
const BfRtSession &session,
const bf_rt_target_t &dev_tgt,
const uint64_t &flags,
BfRtTableAttributes *tableAttributes) const = 0;
/**
* @brief Get the set of supported attributes
*
* @param[out] type_set Set of the supported Attributes
*
* @return Status of the API call
*/
virtual bf_status_t tableAttributesSupported(
std::set<TableAttributesType> *type_set) const = 0;
/** @} */ // End of group Attributes
// table operations APIs
/**
* @name Operations APIs
* @{
*/
/**
* @brief Allocate Operations object
*
* @param[in] type Operations type
* @param[out] table_ops Operations Object returned
*
* @return Status of the API call
*/
virtual bf_status_t operationsAllocate(
const TableOperationsType &type,
std::unique_ptr<BfRtTableOperations> *table_ops) const = 0;
/**
* @brief Get set of supported Operations
*
* @param[out] type_set Set of supported Operations
*
* @return Status of the API call
*/
virtual bf_status_t tableOperationsSupported(
std::set<TableOperationsType> *type_set) const = 0;
/**
* @brief Execute Operations on a table. User
* needs to allocate operation object with correct
* type and then pass it to this API
*
* @param[in] tableOperations Operations Object
*
* @return Status of the API call
*/
virtual bf_status_t tableOperationsExecute(
const BfRtTableOperations &tableOperations) const = 0;
/** @} */ // End of group Operations
};
} // bfrt
#endif // _BF_RT_TABLE_HPP
| 34.462011 | 80 | 0.630262 |
428076b9e4ff076bd95fb24def4b4ac59b016772 | 2,905 | inl | C++ | Engine/Core/Headers/Molten/Renderer/Shader/Visual/VisualShaderConstant.inl | jimmiebergmann/CurseEngine | 74a0502e36327f893c8e4f3e7cbe5b9d38fbe194 | [
"MIT"
] | 2 | 2019-11-11T21:17:14.000Z | 2019-11-11T22:07:26.000Z | Engine/Core/Headers/Molten/Renderer/Shader/Visual/VisualShaderConstant.inl | jimmiebergmann/CurseEngine | 74a0502e36327f893c8e4f3e7cbe5b9d38fbe194 | [
"MIT"
] | null | null | null | Engine/Core/Headers/Molten/Renderer/Shader/Visual/VisualShaderConstant.inl | jimmiebergmann/CurseEngine | 74a0502e36327f893c8e4f3e7cbe5b9d38fbe194 | [
"MIT"
] | 1 | 2020-04-05T03:50:57.000Z | 2020-04-05T03:50:57.000Z | /*
* MIT License
*
* Copyright (c) 2021 Jimmie Bergmann
*
* 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.
*
*/
namespace Molten::Shader::Visual
{
// Constant implementations.
template<typename TDataType>
OutputPin<TDataType>& Constant<TDataType>::GetOutput()
{
return m_output;
}
template<typename TDataType>
const OutputPin<TDataType>& Constant<TDataType>::GetOutput() const
{
return m_output;
}
template<typename TDataType>
VariableDataType Constant<TDataType>::GetDataType() const
{
return VariableTrait<TDataType>::dataType;
}
template<typename TDataType>
size_t Constant<TDataType>::GetOutputPinCount() const
{
return 1;
}
template<typename TDataType>
Pin* Constant<TDataType>::GetOutputPin(const size_t index)
{
if (index >= 1)
{
return nullptr;
}
return &m_output;
}
template<typename TDataType>
const Pin* Constant<TDataType>::GetOutputPin(const size_t index) const
{
if (index >= 1)
{
return nullptr;
}
return &m_output;
}
template<typename TDataType>
std::vector<Pin*> Constant<TDataType>::GetOutputPins()
{
return { &m_output };
}
template<typename TDataType>
std::vector<const Pin*> Constant<TDataType>::GetOutputPins() const
{
return { &m_output };
}
template<typename TDataType>
const TDataType& Constant<TDataType>::GetValue() const
{
return m_value;
}
template<typename TDataType>
void Constant<TDataType>::SetValue(const TDataType& value)
{
m_value = value;
}
template<typename TDataType>
Constant<TDataType>::Constant(Script& script, const TDataType& value) :
ConstantBase(script),
m_value(value),
m_output(*this)
{}
} | 28.203883 | 80 | 0.67642 |
4282699a05745276022b2dfd0b68112ee07565d8 | 2,255 | cpp | C++ | src/Hola_Common/src/Base/ShaderCompiler.cpp | dfnzhc/Hola | d0fd46e9966baafd03c994e49efaa3dd8057309e | [
"MIT"
] | null | null | null | src/Hola_Common/src/Base/ShaderCompiler.cpp | dfnzhc/Hola | d0fd46e9966baafd03c994e49efaa3dd8057309e | [
"MIT"
] | null | null | null | src/Hola_Common/src/Base/ShaderCompiler.cpp | dfnzhc/Hola | d0fd46e9966baafd03c994e49efaa3dd8057309e | [
"MIT"
] | null | null | null | #include "stdafx.h"
#include "ShaderCompiler.h"
#include "Misc/Misc.h"
//--------------------------------------------------------------------------------------
// 哈希一串源代码,并在它的 #include 文件中递归
//--------------------------------------------------------------------------------------
size_t HashShaderString(const char *pRootDir, const char *pShader, size_t hash)
{
hash = Hash(pShader, strlen(pShader), hash);
const char *pch = pShader;
while (*pch != 0)
{
if (*pch == '/') // parse comments
{
pch++;
if (*pch != 0 && *pch == '/')
{
pch++;
while (*pch != 0 && *pch != '\n')
pch++;
}
else if (*pch != 0 && *pch == '*')
{
pch++;
while ( (*pch != 0 && *pch != '*') && (*(pch+1) != 0 && *(pch+1) != '/'))
pch++;
}
}
else if (*pch == '#') // parse #include
{
pch++;
const char include[] = "include";
int i = 0;
while ((*pch!= 0) && *pch == include[i])
{
pch++;
i++;
}
if (i == strlen(include))
{
while (*pch != 0 && *pch == ' ')
pch++;
if (*pch != 0 && *pch == '\"')
{
pch++;
const char *pName = pch;
while (*pch != 0 && *pch != '\"')
pch++;
char includeName[1024];
strcpy_s<1024>(includeName, pRootDir);
strncat_s<1024>(includeName, pName, pch - pName);
pch++;
char *pShaderCode = NULL;
if (ReadFile(includeName, &pShaderCode, NULL, false))
{
hash = HashShaderString(pRootDir, pShaderCode, hash);
free(pShaderCode);
}
}
}
}
else
{
pch++;
}
}
return hash;
} | 29.285714 | 89 | 0.2949 |
4285112808835de0c0cd70175a6e99999ba1b8b8 | 1,852 | cpp | C++ | modules/task_2/vodeneev_m_broadcast/ops_mpi.cpp | Vodeneev/pp_2020_autumn_math | 9b7e5ec56e09474c9880810a6124e3e416bb7e16 | [
"BSD-3-Clause"
] | null | null | null | modules/task_2/vodeneev_m_broadcast/ops_mpi.cpp | Vodeneev/pp_2020_autumn_math | 9b7e5ec56e09474c9880810a6124e3e416bb7e16 | [
"BSD-3-Clause"
] | null | null | null | modules/task_2/vodeneev_m_broadcast/ops_mpi.cpp | Vodeneev/pp_2020_autumn_math | 9b7e5ec56e09474c9880810a6124e3e416bb7e16 | [
"BSD-3-Clause"
] | null | null | null | // Copyright 2020 Mikhail Vodeneev
#include <mpi.h>
#include <math.h>
#include <random>
#include <ctime>
#include <vector>
#include <algorithm>
#include "../../../modules/test_tasks/test_mpi/ops_mpi.h"
int Bcast(void* buffer, int count,
MPI_Datatype datatype, int root, MPI_Comm comm) {
int size, rank;
MPI_Comm_size(MPI_COMM_WORLD, &size);
MPI_Comm_rank(MPI_COMM_WORLD, &rank);
if (root > size) {
printf("Error");
return 1;
}
if ((size == 1) && (root != 0)) {
printf("Error");
return 1;
}
if (root != 0) {
if (rank == root) {
MPI_Send(buffer, count, datatype, 0, 0, MPI_COMM_WORLD);
} else if (rank == 0) {
MPI_Status status;
MPI_Recv(buffer, count, datatype, root, 0, MPI_COMM_WORLD, &status);
}
}
if ((size == 1) && (root != 0)) {
printf("Error");
return 1;
}
if (size == 1) {
return 0;
}
if (size == 2) {
if (rank == 0) {
MPI_Send(buffer, count, datatype, 1, 0, MPI_COMM_WORLD);
} else {
MPI_Status status;
MPI_Recv(buffer, count, datatype, 0, 0, MPI_COMM_WORLD, &status);
}
return 0;
}
if (rank == 0) {
MPI_Send(buffer, count, datatype, 1, 0, MPI_COMM_WORLD);
MPI_Send(buffer, count, datatype, 2, 0, MPI_COMM_WORLD);
} else {
MPI_Status status;
MPI_Recv(buffer, count, datatype,
(rank - 1) / 2, 0, MPI_COMM_WORLD, &status);
if (2 * rank + 1 < size) {
MPI_Send(buffer, count, datatype,
2 * rank + 1, 0, MPI_COMM_WORLD);
}
if (2 * rank + 2 < size) {
MPI_Send(buffer, count, datatype, 2 * rank + 2, 0, MPI_COMM_WORLD);
}
}
return 0;
}
| 25.369863 | 80 | 0.513499 |
42875ddf68b8e6e231f1c34c497127cff79de585 | 3,214 | hpp | C++ | src/Engine/Renderer/Renderers/DebugRender.hpp | david49az/Radium-Engine | 2600039e5c0658057b8b35f79222a332feceb026 | [
"Apache-2.0"
] | 1 | 2021-02-03T17:47:04.000Z | 2021-02-03T17:47:04.000Z | src/Engine/Renderer/Renderers/DebugRender.hpp | david49az/Radium-Engine | 2600039e5c0658057b8b35f79222a332feceb026 | [
"Apache-2.0"
] | null | null | null | src/Engine/Renderer/Renderers/DebugRender.hpp | david49az/Radium-Engine | 2600039e5c0658057b8b35f79222a332feceb026 | [
"Apache-2.0"
] | null | null | null | #pragma once
#include <Engine/RaEngine.hpp>
#include <memory>
#include <vector>
#include <Core/Containers/VectorArray.hpp>
#include <Core/Types.hpp>
#include <Core/Utils/Color.hpp>
#include <Core/Utils/Singleton.hpp>
namespace Ra {
namespace Engine {
class ShaderProgram;
class AttribArrayDisplayable;
} // namespace Engine
} // namespace Ra
namespace Ra {
namespace Engine {
/** This allow to draw debug objects.
* @todo : port this to a more Radium-style code
*/
class RA_ENGINE_API DebugRender final
{
RA_SINGLETON_INTERFACE( DebugRender );
public:
DebugRender();
~DebugRender();
void initialize();
void render( const Core::Matrix4& view, const Core::Matrix4& proj );
void
addLine( const Core::Vector3& from, const Core::Vector3& to, const Core::Utils::Color& color );
void addPoint( const Core::Vector3& p, const Core::Utils::Color& color );
void addPoints( const Core::Vector3Array& p, const Core::Utils::Color& color );
void addPoints( const Core::Vector3Array& p, const Core::Vector4Array& colors );
void addMesh( const std::shared_ptr<AttribArrayDisplayable>& mesh,
const Core::Transform& transform = Core::Transform::Identity() );
// Shortcuts
void addCross( const Core::Vector3& position, Scalar size, const Core::Utils::Color& color );
void addSphere( const Core::Vector3& center, Scalar radius, const Core::Utils::Color& color );
void addCircle( const Core::Vector3& center,
const Core::Vector3& normal,
Scalar radius,
const Core::Utils::Color& color );
void addFrame( const Core::Transform& transform, Scalar size );
void addTriangle( const Core::Vector3& p0,
const Core::Vector3& p1,
const Core::Vector3& p2,
const Core::Utils::Color& color );
void addAABB( const Core::Aabb& box, const Core::Utils::Color& color );
void addOBB( const Core::Aabb& box,
const Core::Transform& transform,
const Core::Utils::Color& color );
private:
struct Line {
Line( const Core::Vector3& la, const Core::Vector3& lb, const Core::Utils::Color& lcol ) :
a {la}, b {lb}, col {lcol} {}
Core::Vector3 a, b;
Core::Utils::Color col;
};
struct Point {
Core::Vector3 p;
Core::Vector3 c;
};
struct DbgMesh {
std::shared_ptr<AttribArrayDisplayable> mesh;
Core::Transform transform;
};
void renderLines( const Core::Matrix4f& view, const Core::Matrix4f& proj );
void renderPoints( const Core::Matrix4f& view, const Core::Matrix4f& proj );
void renderMeshes( const Core::Matrix4f& view, const Core::Matrix4f& proj );
private:
// these shaders are owned by the manager, just keep a raw copy, since the
// manager is available during whole execution.
const ShaderProgram* m_lineProg {nullptr};
const ShaderProgram* m_pointProg {nullptr};
const ShaderProgram* m_meshProg {nullptr};
std::vector<Line> m_lines;
std::vector<DbgMesh> m_meshes;
std::vector<Point> m_points;
};
} // namespace Engine
} // namespace Ra
| 30.903846 | 99 | 0.645924 |
42890423d5897e251f75e70707da5a09267a9f97 | 332 | cpp | C++ | Codechef/C++/Solubility (SOLBLTY).cpp | abdzitter/Daily-Coding-DS-ALGO-Practice | 26ddbf7a3673608039a07d26d812fce31b69871a | [
"MIT"
] | 289 | 2021-05-15T22:56:03.000Z | 2022-03-28T23:13:25.000Z | Codechef/C++/Solubility (SOLBLTY).cpp | abdzitter/Daily-Coding-DS-ALGO-Practice | 26ddbf7a3673608039a07d26d812fce31b69871a | [
"MIT"
] | 1,812 | 2021-05-09T13:49:58.000Z | 2022-01-15T19:27:17.000Z | Codechef/C++/Solubility (SOLBLTY).cpp | abdzitter/Daily-Coding-DS-ALGO-Practice | 26ddbf7a3673608039a07d26d812fce31b69871a | [
"MIT"
] | 663 | 2021-05-09T16:57:58.000Z | 2022-03-27T14:15:07.000Z | #include <bits/stdc++.h>
using namespace std;
#define int long long int
#define endl "\n"
int32_t main()
{
int t;
cin >> t;
while (t--)
{
int p, x, y;
cin >> p >> x >> y;
int ans = 0;
ans = x + (100 - p) * y;
ans = ans * 10;
cout << ans << endl;
}
return 0;
} | 16.6 | 32 | 0.430723 |
4289fc2aa5fd2402e2a86bec3fa4524c70cf973e | 4,556 | cpp | C++ | rtc_stack/utils/Worker.cpp | anjisuan783/media_lib | c09c7d48f495a803df79e39cf837bbcb1320ceb8 | [
"MIT"
] | 9 | 2022-01-07T03:10:45.000Z | 2022-03-31T03:29:02.000Z | rtc_stack/utils/Worker.cpp | anjisuan783/mia | c09c7d48f495a803df79e39cf837bbcb1320ceb8 | [
"MIT"
] | 16 | 2021-12-17T08:32:57.000Z | 2022-03-10T06:16:14.000Z | rtc_stack/utils/Worker.cpp | anjisuan783/media_lib | c09c7d48f495a803df79e39cf837bbcb1320ceb8 | [
"MIT"
] | 1 | 2022-02-21T15:47:21.000Z | 2022-02-21T15:47:21.000Z | #include "./Worker.h"
#include <algorithm>
#include <memory>
#include "myrtc/api/default_task_queue_factory.h"
#include "myrtc/rtc_base/to_queued_task.h"
namespace wa {
bool ScheduledTaskReference::isCancelled() {
return cancelled_;
}
void ScheduledTaskReference::cancel() {
cancelled_ = true;
}
////////////////////////////////////////////////////////////////////////////////
//Worker
////////////////////////////////////////////////////////////////////////////////
Worker::Worker(webrtc::TaskQueueFactory* factory, int id, std::shared_ptr<Clock> the_clock)
: factory_(factory),
id_(id),
clock_{the_clock}
{ }
void Worker::task(Task t) {
task_queue_->PostTask(webrtc::ToQueuedTask(std::forward<Task>(t)));
}
void Worker::task(Task t, const rtc::Location& r) {
task_queue_->PostTask(webrtc::ToQueuedTask(std::forward<Task>(t), r));
}
void Worker::start(const std::string& name) {
auto promise = std::make_shared<std::promise<void>>();
start(promise, name);
promise->get_future().wait();
}
void Worker::start(std::shared_ptr<std::promise<void>> start_promise,
const std::string& name) {
auto pQueue = factory_->CreateTaskQueue(name,
webrtc::TaskQueueFactory::Priority::NORMAL);
task_queue_base_ = pQueue.get();
task_queue_ = std::move(std::make_unique<rtc::TaskQueue>(std::move(pQueue)));
task_queue_->PostTask([start_promise] {
start_promise->set_value();
});
}
void Worker::close() {
closed_ = true;
task_queue_ = nullptr;
task_queue_base_ = nullptr;
}
std::shared_ptr<ScheduledTaskReference>
Worker::scheduleFromNow(Task t, duration delta) {
rtc::Location l;
return scheduleFromNow(std::forward<Task>(t), delta, l);
}
std::shared_ptr<ScheduledTaskReference>
Worker::scheduleFromNow(Task t, duration delta, const rtc::Location& l) {
auto id = std::make_shared<ScheduledTaskReference>();
task_queue_->PostDelayedTask(
webrtc::ToQueuedTask(std::forward<std::function<void()>>(
[f = std::forward<Task>(t), id]() {
if (!id->isCancelled()) {
f();
}
}), l),
ClockUtils::durationToMs(delta));
return id;
}
void Worker::scheduleEvery(ScheduledTask f, duration period) {
rtc::Location l;
scheduleEvery(std::forward<ScheduledTask>(f), period, period, l);
}
void Worker::scheduleEvery(ScheduledTask f,
duration period, const rtc::Location& l) {
scheduleEvery(std::forward<ScheduledTask>(f), period, period, l);
}
void Worker::scheduleEvery(ScheduledTask&& t,
duration period, duration next_delay, const rtc::Location& location) {
time_point start = clock_->now();
scheduleFromNow([this_ptr = shared_from_this(),
start, period, next_delay,
f = std::forward<ScheduledTask>(t), clock = clock_, location]() {
if (f()) {
duration clock_skew = clock->now() - start - next_delay;
duration delay = std::max(period - clock_skew, duration(0));
this_ptr->scheduleEvery(
std::forward<ScheduledTask>(const_cast<ScheduledTask&>(f)),
period, delay, location);
}
}, next_delay, location);
}
void Worker::unschedule(std::shared_ptr<ScheduledTaskReference> id) {
id->cancel();
}
////////////////////////////////////////////////////////////////////////////////
//ThreadPool
////////////////////////////////////////////////////////////////////////////////
static std::unique_ptr<webrtc::TaskQueueFactory> g_task_queue_factory =
webrtc::CreateDefaultTaskQueueFactory();
ThreadPool::ThreadPool(unsigned int num_workers) {
workers_.reserve(num_workers);
for (unsigned int index = 0; index < num_workers; ++index) {
workers_.push_back(
std::make_shared<Worker>(g_task_queue_factory.get(), index));
}
}
ThreadPool::~ThreadPool() {
close();
}
std::shared_ptr<Worker> ThreadPool::getLessUsedWorker() {
std::shared_ptr<Worker> chosen_worker = workers_.front();
for (auto worker : workers_) {
if (chosen_worker.use_count() > worker.use_count()) {
chosen_worker = worker;
}
}
return chosen_worker;
}
void ThreadPool::start(const std::string& name) {
std::vector<std::shared_ptr<std::promise<void>>> promises(workers_.size());
int index = 0;
for (auto worker : workers_) {
promises[index] = std::make_shared<std::promise<void>>();
worker->start(promises[index++], name);
}
for (auto promise : promises) {
promise->get_future().wait();
}
}
void ThreadPool::close() {
for (auto worker : workers_) {
worker->close();
}
}
} //namespace wa
| 28.298137 | 92 | 0.628402 |
428b536e834ccef6abc90d9128f9c7ae8b192e75 | 15,383 | cpp | C++ | test/unit_tests/test_duration.cpp | slavslav/sydevs | 3106c38d327be652638bd8bd75dbe02c938800e5 | [
"Apache-2.0"
] | 26 | 2018-04-24T23:47:58.000Z | 2021-05-27T16:56:27.000Z | test/unit_tests/test_duration.cpp | slavslav/sydevs | 3106c38d327be652638bd8bd75dbe02c938800e5 | [
"Apache-2.0"
] | 2 | 2018-08-13T23:49:55.000Z | 2020-03-27T21:09:47.000Z | test/unit_tests/test_duration.cpp | slavslav/sydevs | 3106c38d327be652638bd8bd75dbe02c938800e5 | [
"Apache-2.0"
] | 9 | 2018-08-29T20:12:31.000Z | 2021-06-09T12:08:51.000Z | #include <catch2/catch.hpp>
#include <sydevs/core/string_builder.h>
#include <sydevs/core/quantity.h>
namespace sydevs {
TEST_CASE("test duration constructors")
{
CHECK(!duration().valid());
CHECK(duration(0).multiplier() == 0);
CHECK(duration(0).precision() == unit);
CHECK(duration(100).multiplier() == 100);
CHECK(duration(100).precision() == unit);
CHECK(duration(-100).multiplier() == -100);
CHECK(duration(-100).precision() == unit);
CHECK(duration(100, nano).multiplier() == 100);
CHECK(duration(100, nano).precision() == nano);
CHECK(duration(-100, nano).multiplier() == -100);
CHECK(duration(-100, nano).precision() == nano);
CHECK(duration(quantity_limit - 1).multiplier() == quantity_limit - 1);
CHECK(duration(quantity_limit - 1).finite());
CHECK(!duration(quantity_limit).finite());
CHECK(!duration(quantity_limit + 1).finite());
CHECK(duration(1 - quantity_limit).multiplier() == 1 - quantity_limit);
CHECK(duration(1 - quantity_limit).finite());
CHECK(!duration(quantity_limit).finite());
CHECK(!duration(-1 - quantity_limit).finite());
}
TEST_CASE("test duration literals")
{
CHECK(0_s == duration(0));
CHECK((0_s).multiplier() == 0);
CHECK((0_s).precision() == unit);
CHECK(0_us == duration(0));
CHECK((0_us).multiplier() == 0);
CHECK((0_us).precision() == micro);
CHECK(0_Ms == duration(0));
CHECK((0_Ms).multiplier() == 0);
CHECK((0_Ms).precision() == mega);
CHECK(1_s == duration(1, unit));
CHECK(1_min == duration(60, unit));
CHECK(1_hr == duration(3600, unit));
CHECK(1_day == duration(86400, unit));
CHECK(1_yr == duration(31536000, unit));
CHECK(1_ys == duration(1, yocto));
CHECK(1_zs == duration(1, zepto));
CHECK(1_as == duration(1, atto));
CHECK(1_fs == duration(1, femto));
CHECK(1_ps == duration(1, pico));
CHECK(1_ns == duration(1, nano));
CHECK(1_us == duration(1, micro));
CHECK(1_ms == duration(1, milli));
CHECK(1_s == duration(1, unit));
CHECK(1_ks == duration(1, kilo));
CHECK(1_Ms == duration(1, mega));
CHECK(1_Gs == duration(1, giga));
CHECK(1_Ts == duration(1, tera));
CHECK(1_Ps == duration(1, peta));
CHECK(1_Es == duration(1, exa));
CHECK(1_Zs == duration(1, zetta));
CHECK(1_Ys == duration(1, yotta));
CHECK(5_min == duration(300, unit));
CHECK(7_day == duration(604800, unit));
CHECK(999999999999999_s == duration(999999999999999, unit));
CHECK(999999999999999_us == duration(999999999999999, micro));
CHECK(1000000000000000_s == duration::inf());
CHECK(1000000000000000_us == duration::inf());
CHECK(-999999999999999_s == duration(-999999999999999, unit));
CHECK(-999999999999999_us == duration(-999999999999999, micro));
CHECK(-1000000000000000_s == -duration::inf());
CHECK(-1000000000000000_us == -duration::inf());
}
TEST_CASE("test non-operator duration methods with duration return values")
{
CHECK((5_s).refined().multiplier() == 5000000000000);
CHECK((5_s).refined().precision() == pico);
CHECK((5_s).refined().fixed() == false);
CHECK((5_s).coarsened().multiplier() == 5);
CHECK((5_s).coarsened().precision() == unit);
CHECK((5_s).coarsened().fixed() == false);
CHECK((5_s).refined().coarsened().multiplier() == 5);
CHECK((5_s).refined().coarsened().precision() == unit);
CHECK((5_s).refined().coarsened().fixed() == false);
CHECK((5_s).fixed_at(nano).multiplier() == 5000000000);
CHECK((5_s).fixed_at(nano).precision() == nano);
CHECK((5_s).fixed_at(nano).fixed() == true);
CHECK((83000_us).fixed_at(milli).multiplier() == 83);
CHECK((83000_us).fixed_at(milli).precision() == milli);
CHECK((83000_us).fixed_at(milli).fixed() == true);
CHECK((83123_us).fixed_at(milli).multiplier() == 83);
CHECK((83123_us).fixed_at(milli).precision() == milli);
CHECK((83123_us).fixed_at(milli).fixed() == true);
CHECK((5_s).rescaled(nano).multiplier() == 5000000000);
CHECK((5_s).rescaled(nano).precision() == nano);
CHECK((5_s).rescaled(nano).fixed() == false);
CHECK((83000_us).rescaled(milli).multiplier() == 83);
CHECK((83000_us).rescaled(milli).precision() == milli);
CHECK((83000_us).rescaled(milli).fixed() == false);
CHECK((83123_us).rescaled(milli).multiplier() == 83);
CHECK((83123_us).rescaled(milli).precision() == milli);
CHECK((83123_us).rescaled(milli).fixed() == false);
CHECK((83000_us).fixed_at(milli).unfixed().multiplier() == 83);
CHECK((83000_us).fixed_at(milli).unfixed().precision() == milli);
CHECK((83000_us).fixed_at(milli).unfixed().fixed() == false);
CHECK((83123_us).fixed_at(milli).unfixed().multiplier() == 83);
CHECK((83123_us).fixed_at(milli).unfixed().precision() == milli);
CHECK((83123_us).fixed_at(milli).unfixed().fixed() == false);
}
TEST_CASE("test duration base-1000 floating-point addition")
{
CHECK((3_hr + 45_s) == 10845_s);
CHECK((3_hr + 45_s).precision() == unit);
CHECK((3_hr + 45_s).refined() == 10845000000000_ns);
CHECK((3_hr + 45_s).refined().precision() == nano);
CHECK((3_hr + 45_s).coarsened() == 10845_s);
CHECK((3_hr + 45_s).coarsened().precision() == unit);
CHECK((3_hr + 45_s).refined().coarsened() == 10845_s);
CHECK((3_hr + 45_s).refined().coarsened().precision() == unit);
CHECK(((1_s).rescaled(milli) + (1_s).rescaled(micro)) == 2000000_us);
CHECK(((1_s).rescaled(milli) + (1_s).rescaled(micro)).precision() == micro);
CHECK(!((1_s).fixed_at(milli) + (1_s).fixed_at(micro)).valid());
CHECK(((47_ms).rescaled(pico) + 1_yr) == 31536000047000_us);
CHECK(((47_ms).rescaled(pico) + 1_yr).precision() == micro);
CHECK(((47_ms).rescaled(femto) + 1_yr) == 31536000047000_us);
CHECK(((47_ms).rescaled(femto) + 1_yr).precision() == micro);
CHECK((47_ms).rescaled(atto) == +duration::inf());
CHECK(((47_ms).rescaled(atto) + 1_yr) == +duration::inf());
CHECK((1_yr + (47_ms).rescaled(atto)) == +duration::inf());
CHECK(((47_us).rescaled(atto) + 1_yr) == 31536000000047_us);
CHECK(((47_us).rescaled(atto) + 1_yr).precision() == micro);
CHECK((1_yr + (47_us).rescaled(atto)) == 31536000000047_us);
CHECK((1_yr + (47_us).rescaled(atto)).precision() == micro);
CHECK((500000000000000_Ms + 500000000000000_Ms) == 1000000000000_Gs);
CHECK((500000000000000_Ms + 500000000000000_Ms).precision() == giga);
CHECK(((500000000000000_Ms).fixed_at(mega) + (500000000000000_Ms).fixed_at(mega)) == +duration::inf());
CHECK(((500000000000000_Ms).fixed_at(mega) + (500000000000000_Ms).fixed_at(mega)).precision() == unit);
}
TEST_CASE("test duration negation base-1000 floating-point subtraction")
{
CHECK(-1_min == -60_s);
CHECK((-1_min).precision() == unit);
CHECK((5_min - 1_hr) == -3300_s);
CHECK((5_min - 1_hr).precision() == unit);
CHECK(((47_ms).rescaled(atto) - 1_yr) == +duration::inf());
CHECK((1_yr - (47_ms).rescaled(atto)) == -duration::inf());
CHECK(((47_us).rescaled(atto) - 1_yr) == -31535999999953_us);
CHECK(((47_us).rescaled(atto) - 1_yr).precision() == micro);
CHECK((1_yr - (47_us).rescaled(atto)) == +31535999999953_us);
CHECK((1_yr - (47_us).rescaled(atto)).precision() == micro);
CHECK((-duration::inf()) == -duration::inf());
CHECK(!(duration::inf() - duration::inf()).valid());
CHECK((1_s - 1_s).precision() == unit);
CHECK((1_ms - 1_ms).precision() == milli);
CHECK((1_us - 1_us).precision() == micro);
CHECK((1_ks - 1_ks).precision() == kilo);
}
TEST_CASE("test duration multiplication by number")
{
CHECK((1_hr*3) == 10800_s);
CHECK((1_hr*3).precision() == unit);
CHECK((3*1_hr) == 10800_s);
CHECK((3*1_hr).precision() == unit);
CHECK((1_hr*1000000000000000.0) == 3600000000000_Ms);
CHECK((1_hr*1000000000000000.0).precision() == mega);
CHECK((1_hr*0.000000000000001) == 3600000000000_ys);
CHECK((1_hr*0.000000000000001).precision() == yocto);
CHECK(((1_hr).fixed_at(unit)*3) == 10800_s);
CHECK(((1_hr).fixed_at(unit)*3).precision() == unit);
CHECK(((1_hr).fixed_at(unit)*1000000000000000.0) == +duration::inf());
CHECK(((1_hr).fixed_at(unit)*0.000000000000001) == 0_s);
CHECK(((1_hr).fixed_at(unit)*0.000000000000001).precision() == unit);
}
TEST_CASE("test duration division by number")
{
CHECK((1_hr/3) == 1200_s);
CHECK((1_hr/3).precision() == unit);
CHECK((1_hr/1000000000000000.0) == 3600_fs);
CHECK((1_hr/1000000000000000.0).precision() == femto);
CHECK((1_hr/0.000000000000001) == 3600000000000_Ms);
CHECK((1_hr/0.000000000000001).precision() == mega);
CHECK(((1_hr).fixed_at(unit)/3) == 1200_s);
CHECK(((1_hr).fixed_at(unit)/3).precision() == unit);
CHECK(((1_hr).fixed_at(unit)/1000000000000000.0) == 0_s);
CHECK(((1_hr).fixed_at(unit)/1000000000000000.0).precision() == unit);
CHECK(((1_hr).fixed_at(unit)/0.000000000000001) == +duration::inf());
}
TEST_CASE("test duration-duration division")
{
CHECK((1_hr/1_min) == 60);
CHECK((1_hr/2_s) == 1800);
CHECK((1_min/1_hr) == Approx(0.0166667));
CHECK((5_s/1_ns) == Approx(5e+09));
CHECK((1_ns/1_s) == Approx(1e-09));
}
TEST_CASE("test duration-duration comparisons")
{
CHECK((1_ns == 1_s) == false);
CHECK((1_s == 1_ns) == false);
CHECK((1_ns == 1_ns) == true);
CHECK((1_ns != 1_s) == true);
CHECK((1_s != 1_ns) == true);
CHECK((1_ns != 1_ns) == false);
CHECK((1_ns < 1_s) == true);
CHECK((1_s < 1_ns) == false);
CHECK((1_ns < 1_ns) == false);
CHECK((1_ns > 1_s) == false);
CHECK((1_s > 1_ns) == true);
CHECK((1_ns > 1_ns) == false);
CHECK((1_ns <= 1_s) == true);
CHECK((1_s <= 1_ns) == false);
CHECK((1_ns <= 1_ns) == true);
CHECK((1_ns >= 1_s) == false);
CHECK((1_s >= 1_ns) == true);
CHECK((1_ns >= 1_ns) == true);
}
TEST_CASE("test duration add/subtract/multiply/divide assignment operations")
{
auto dt = 1_hr;
SECTION("add assignment") {
CHECK((dt += 1_min) == 3660_s);
CHECK(dt == 3660_s);
CHECK(dt.precision() == unit);
}
SECTION("subtract assignment") {
CHECK((dt -= 1_min) == 3540_s);
CHECK(dt == 3540_s);
CHECK(dt.precision() == unit);
}
SECTION("multiply assignment") {
CHECK((dt *= 3.14159) == 11309724_ms);
CHECK(dt == 11309724_ms);
CHECK(dt.precision() == milli);
}
SECTION("divide assignment") {
CHECK((dt /= 4) == 900_s);
CHECK(dt == 900_s);
CHECK(dt.precision() == unit);
}
}
TEST_CASE("test max_duration")
{
CHECK(duration::max(unit) == 999999999999999_s);
CHECK(duration::max(yocto) == 999999999999999_ys);
}
TEST_CASE("test duration addition and subtraction with both fixed and unfixed operands")
{
CHECK(((1_s).fixed_at(micro) + (1_s).rescaled(nano)) == 2000000_us);
CHECK(((1_s).fixed_at(micro) + (1_s).rescaled(nano)).precision() == micro);
CHECK(((1_s).fixed_at(nano) + (1_s).rescaled(micro)) == 2000000000_ns);
CHECK(((1_s).fixed_at(nano) + (1_s).rescaled(micro)).precision() == nano);
CHECK(((1_s).rescaled(micro) + (1_s).fixed_at(nano)) == 2000000000_ns);
CHECK(((1_s).rescaled(micro) + (1_s).fixed_at(nano)).precision() == nano);
CHECK(((1_s).rescaled(nano) + (1_s).fixed_at(micro)) == 2000000_us);
CHECK(((1_s).rescaled(nano) + (1_s).fixed_at(micro)).precision() == micro);
CHECK(((2_s).fixed_at(micro) - (1_s).rescaled(nano)) == 1000000_us);
CHECK(((2_s).fixed_at(micro) - (1_s).rescaled(nano)).precision() == micro);
CHECK(((2_s).fixed_at(nano) - (1_s).rescaled(micro)) == 1000000000_ns);
CHECK(((2_s).fixed_at(nano) - (1_s).rescaled(micro)).precision() == nano);
CHECK(((2_s).rescaled(micro) - (1_s).fixed_at(nano)) == 1000000000_ns);
CHECK(((2_s).rescaled(micro) - (1_s).fixed_at(nano)).precision() == nano);
CHECK(((2_s).rescaled(nano) - (1_s).fixed_at(micro)) == 1000000_us);
CHECK(((2_s).rescaled(nano) - (1_s).fixed_at(micro)).precision() == micro);
}
TEST_CASE("test duration with assorted operations")
{
CHECK((string_builder() << (2_s).fixed_at(unit) + (3_s).fixed_at(unit)).str() == "5_s");
CHECK((string_builder() << (2_s).fixed_at(unit) - (3_s).fixed_at(unit)).str() == "-1_s");
CHECK((string_builder() << 5*(100_s).fixed_at(unit)).str() == "500_s");
CHECK((string_builder() << (1.0/5.0)*(100_s).fixed_at(unit)).str() == "20_s");
CHECK((string_builder() << (100_s).fixed_at(unit)*(1.0/5.0)).str() == "20_s");
CHECK((string_builder() << (100_s).fixed_at(unit)/5.0).str() == "20_s");
CHECK((string_builder() << (100_s).fixed_at(unit)/8.0).str() == "13_s");
CHECK(2_s > 1000_ms);
CHECK(2_s < 3000_ms);
CHECK(-8_ps < -7_ps);
CHECK(1_s == 1000_ms);
CHECK(1_s == 1000000_us);
CHECK(1000_ms == 1000000_us);
CHECK(((500_ms).fixed_at(milli) + (500_ms).fixed_at(milli)) == 1_s);
CHECK((string_builder() << (500_ms).fixed_at(milli) + (500_ms).fixed_at(milli)).str() == "1000_ms");
CHECK((string_builder() << (999999999999999_Ms).fixed_at(mega) + (1_Ms).fixed_at(mega)).str() == "duration::inf()");
CHECK((string_builder() << -1000000*(1000000000_fs).fixed_at(femto)).str() == "-duration::inf()");
CHECK((string_builder() << 3_s + 475_ms).str() == "3475_ms");
CHECK((string_builder() << 1_ks + 1_us).str() == "1000000001_us");
CHECK((string_builder() << 500_ps - 1_ns).str() == "-500_ps");
CHECK((string_builder() << (1.0/3.0)*(1_s)).str() == "333333333333333_fs");
CHECK((string_builder() << (1.0/3.0)*(1000_ms)).str() == "333333333333333_fs");
CHECK((string_builder() << 1000_ms/3.0).str() == "333333333333333_fs");
CHECK((string_builder() << (1.0/3.0)*(1000000_us)).str() == "333333333333333_fs");
CHECK((string_builder() << (999999999999999_Ms) + (1_Ms)).str() == "1000000000000_Gs");
CHECK((string_builder() << -1000000*(1000000000_fs)).str() == "-1000000000000_ps");
CHECK((10_ms/250_us) == Approx(40.0));
CHECK(((-100_s)/900_s) == Approx(-1.0/9.0));
CHECK(((123_ms)/1_s) == Approx(0.123));
CHECK(((123_ms)/1_ms) == 123);
CHECK(((123_ms)/0_s) == std::numeric_limits<float64>::infinity());
CHECK(duration::inf().precision() == unit);
CHECK(-duration::inf().precision() == unit);
CHECK(duration(0, unit).precision() == unit);
CHECK(duration(0, milli).precision() == milli);
CHECK(duration(0, micro).precision() == micro);
CHECK((string_builder() << (1_min + 40_s).fixed_at(micro)/8.0).str() == "12500000_us");
CHECK((string_builder() << (1_min + 40_s).fixed_at(milli)/8.0).str() == "12500_ms");
CHECK((string_builder() << (1_min + 40_s).fixed_at(unit)/8.0).str() == "13_s");
CHECK((string_builder() << (1_min + 40_s).rescaled(micro)/8.0).str() == "12500000_us");
CHECK((string_builder() << (1_min + 40_s).rescaled(milli)/8.0).str() == "12500_ms");
CHECK((string_builder() << (1_min + 40_s).rescaled(unit)/8.0).str() == "12500_ms");
CHECK((string_builder() << (4_s + 10_ms)).str() == "4010_ms");
CHECK((string_builder() << (4_s + 10_ms)/4).str() == "1002500_us");
CHECK((string_builder() << (4_s + 10_ms).fixed_at(milli)/4).str() == "1003_ms");
CHECK((string_builder() << (4_s + 10_ms).fixed_at(micro)/4).str() == "1002500_us");
}
} // namespace
| 45.646884 | 120 | 0.62075 |
429707e171dda3277947c6ae92f83456590edfbc | 29,271 | cc | C++ | src/JobMaker.cc | ganibc/btcpool | 360c90900922edab95c4759e8da7158dd12382b5 | [
"MIT"
] | 1 | 2018-05-29T13:13:47.000Z | 2018-05-29T13:13:47.000Z | src/JobMaker.cc | ganibc/btcpool | 360c90900922edab95c4759e8da7158dd12382b5 | [
"MIT"
] | null | null | null | src/JobMaker.cc | ganibc/btcpool | 360c90900922edab95c4759e8da7158dd12382b5 | [
"MIT"
] | 1 | 2019-02-28T06:20:07.000Z | 2019-02-28T06:20:07.000Z | /*
The MIT License (MIT)
Copyright (c) [2016] [BTC.COM]
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
*/
#include "JobMaker.h"
#include <iostream>
#include <stdlib.h>
#include <glog/logging.h>
#include <librdkafka/rdkafka.h>
#include <hash.h>
#include <script/script.h>
#include <uint256.h>
#include <util.h>
#include <utilstrencodings.h>
#ifdef INCLUDE_BTC_KEY_IO_H //
#include <key_io.h> // IsValidDestinationString for bch is not in this file.
#endif
#include "utilities_js.hpp"
#include "Utils.h"
#include "BitcoinUtils.h"
/////////////////////////////////// JobMaker /////////////////////////////////
JobMaker::JobMaker(shared_ptr<JobMakerHandler> handler,
const string &kafkaBrokers,
const string& zookeeperBrokers) : handler_(handler),
running_(true),
zkLocker_(zookeeperBrokers.c_str()),
kafkaBrokers_(kafkaBrokers),
kafkaProducer_(kafkaBrokers.c_str(), handler->def().jobTopic_.c_str(), RD_KAFKA_PARTITION_UA)
{
}
JobMaker::~JobMaker() {
}
void JobMaker::stop() {
if (!running_) {
return;
}
running_ = false;
LOG(INFO) << "stop jobmaker";
}
bool JobMaker::init() {
/* get lock from zookeeper */
try {
if (handler_->def().zookeeperLockPath_.empty()) {
LOG(ERROR) << "zookeeper lock path is empty!";
return false;
}
zkLocker_.getLock(handler_->def().zookeeperLockPath_.c_str());
} catch(const ZookeeperException &zooex) {
LOG(ERROR) << zooex.what();
return false;
}
/* setup kafka producer */
{
map<string, string> options;
// set to 1 (0 is an illegal value here), deliver msg as soon as possible.
options["queue.buffering.max.ms"] = "1";
if (!kafkaProducer_.setup(&options)) {
LOG(ERROR) << "kafka producer setup failure";
return false;
}
if (!kafkaProducer_.checkAlive()) {
LOG(ERROR) << "kafka producer is NOT alive";
return false;
}
}
/* setup kafka consumers */
if (!handler_->initConsumerHandlers(kafkaBrokers_, kafkaConsumerHandlers_)) {
return false;
}
return true;
}
void JobMaker::consumeKafkaMsg(rd_kafka_message_t *rkmessage, JobMakerConsumerHandler &consumerHandler)
{
// check error
if (rkmessage->err)
{
if (rkmessage->err == RD_KAFKA_RESP_ERR__PARTITION_EOF)
{
// Reached the end of the topic+partition queue on the broker.
return;
}
LOG(ERROR) << "consume error for topic " << rd_kafka_topic_name(rkmessage->rkt)
<< "[" << rkmessage->partition << "] offset " << rkmessage->offset
<< ": " << rd_kafka_message_errstr(rkmessage);
if (rkmessage->err == RD_KAFKA_RESP_ERR__UNKNOWN_PARTITION ||
rkmessage->err == RD_KAFKA_RESP_ERR__UNKNOWN_TOPIC)
{
LOG(FATAL) << "consume fatal";
stop();
}
return;
}
// set json string
LOG(INFO) << "received " << consumerHandler.kafkaTopic_ << " message len: " << rkmessage->len;
string msg((const char *)rkmessage->payload, rkmessage->len);
if (consumerHandler.messageProcessor_(msg)) {
LOG(INFO) << "handleMsg returns true, new stratum job";
produceStratumJob();
}
}
void JobMaker::produceStratumJob() {
const string jobMsg = handler_->makeStratumJobMsg();
if (!jobMsg.empty()) {
LOG(INFO) << "new " << handler_->def().jobTopic_ << " job: " << jobMsg;
kafkaProducer_.produce(jobMsg.data(), jobMsg.size());
}
lastJobTime_ = time(nullptr);
// save send timestamp to file, for monitor system
if (!handler_->def().fileLastJobTime_.empty()) {
// TODO: fix Y2K38 issue
writeTime2File(handler_->def().fileLastJobTime_.c_str(), (uint32_t)lastJobTime_);
}
}
void JobMaker::runThreadKafkaConsume(JobMakerConsumerHandler &consumerHandler) {
const int32_t timeoutMs = 1000;
while (running_) {
rd_kafka_message_t *rkmessage;
rkmessage = consumerHandler.kafkaConsumer_->consumer(timeoutMs);
if (rkmessage == nullptr) /* timeout */ {
continue;
}
consumeKafkaMsg(rkmessage, consumerHandler);
/* Return message to rdkafka */
rd_kafka_message_destroy(rkmessage);
// Don't add any sleep() here.
// Kafka will not skip any message during your sleep(), you will received
// all messages from your beginning offset to the latest in any case.
// So sleep() will cause unexpected delay before consumer a new message.
// If the producer's speed is faster than the sleep() here, the consumption
// will be delayed permanently and the latest message will never be received.
// At the same time, there is not a busy waiting.
// KafkaConsumer::consumer(timeoutMs) will return after `timeoutMs` millisecond
// if no new messages. You can increase `timeoutMs` if you want.
}
}
void JobMaker::run() {
// running consumer threads
for (JobMakerConsumerHandler &consumerhandler : kafkaConsumerHandlers_)
{
kafkaConsumerWorkers_.push_back(std::make_shared<thread>(std::bind(&JobMaker::runThreadKafkaConsume, this, consumerhandler)));
}
// produce stratum job regularly
// the stratum job producing will also be triggered by consumer threads
while (running_) {
sleep(1);
if (time(nullptr) - lastJobTime_ > handler_->def().jobInterval_) {
produceStratumJob();
}
}
// wait consumer threads exit
for (auto pWorker : kafkaConsumerWorkers_) {
if (pWorker->joinable()) {
LOG(INFO) << "wait for worker " << pWorker->get_id() << "exiting";
pWorker->join();
LOG(INFO) << "worker exited";
}
}
}
////////////////////////////////GwJobMakerHandler//////////////////////////////////
bool GwJobMakerHandler::initConsumerHandlers(const string &kafkaBrokers, vector<JobMakerConsumerHandler> &handlers)
{
JobMakerConsumerHandler handler = {
/* kafkaTopic_ = */ def_.rawGwTopic_,
/* kafkaConsumer_ = */ std::make_shared<KafkaConsumer>(kafkaBrokers.c_str(), def_.rawGwTopic_.c_str(), 0/* partition */),
/* messageProcessor_ = */ std::bind(&GwJobMakerHandler::processMsg, this, std::placeholders::_1)
};
// init kafka consumer
{
map<string, string> consumerOptions;
consumerOptions["fetch.wait.max.ms"] = "5";
if (!handler.kafkaConsumer_->setup(RD_KAFKA_OFFSET_TAIL(1), &consumerOptions)) {
LOG(ERROR) << "kafka consumer " << def_.rawGwTopic_ << " setup failure";
return false;
}
if (!handler.kafkaConsumer_->checkAlive()) {
LOG(FATAL) << "kafka consumer " << def_.rawGwTopic_ << " is NOT alive";
return false;
}
}
handlers.push_back(handler);
return true;
}
////////////////////////////////JobMakerHandlerEth//////////////////////////////////
bool JobMakerHandlerEth::processMsg(const string &msg)
{
shared_ptr<RskWork> rskWork = make_shared<RskWorkEth>();
if (rskWork->initFromGw(msg))
{
previousRskWork_ = currentRskWork_;
currentRskWork_ = rskWork;
DLOG(INFO) << "currentRskBlockJson: " << msg;
}
else {
LOG(ERROR) << "eth initFromGw failed " << msg;
return false;
}
clearTimeoutMsg();
if (nullptr == previousRskWork_ && nullptr == currentRskWork_) {
LOG(ERROR) << "no current work" << msg;
return false;
}
//first job
if (nullptr == previousRskWork_ && currentRskWork_ != nullptr)
return true;
// Check if header changes so the new workpackage is really new
return currentRskWork_->getBlockHash() != previousRskWork_->getBlockHash();
}
void JobMakerHandlerEth::clearTimeoutMsg() {
const uint32_t now = time(nullptr);
if(currentRskWork_ != nullptr && currentRskWork_->getCreatedAt() + def_.maxJobDelay_ < now)
currentRskWork_ = nullptr;
if(previousRskWork_ != nullptr && previousRskWork_->getCreatedAt() + def_.maxJobDelay_ < now)
previousRskWork_ = nullptr;
}
string JobMakerHandlerEth::makeStratumJobMsg()
{
if (nullptr == currentRskWork_)
return "";
if (0 == currentRskWork_->getRpcAddress().length())
return "";
RskWorkEth *currentRskBlockJson = dynamic_cast<RskWorkEth*>(currentRskWork_.get());
if (nullptr == currentRskBlockJson)
return "";
const string request = "{\"jsonrpc\":\"2.0\",\"method\":\"eth_getBlockByNumber\",\"params\":[\"pending\", false],\"id\":2}";
string response;
bool res = bitcoindRpcCall(currentRskBlockJson->getRpcAddress().c_str(), currentRskBlockJson->getRpcUserPwd().c_str(), request.c_str(), response);
if (!res)
LOG(ERROR) << "get pending block failed";
StratumJobEth sjob;
if (!sjob.initFromGw(*currentRskBlockJson, response)) {
LOG(ERROR) << "init stratum job message from gw str fail";
return "";
}
return sjob.serializeToJson();
}
////////////////////////////////JobMakerHandlerSia//////////////////////////////////
JobMakerHandlerSia::JobMakerHandlerSia() : time_(0)
{
}
bool JobMakerHandlerSia::processMsg(const string &msg)
{
JsonNode j;
if (!JsonNode::parse(msg.c_str(), msg.c_str() + msg.length(), j))
{
LOG(ERROR) << "deserialize sia work failed " << msg;
return false;
}
if (!validate(j))
return false;
string header = j["hHash"].str();
if (header == header_)
return false;
header_ = move(header);
time_ = j["created_at_ts"].uint32();
return processMsg(j);
}
bool JobMakerHandlerSia::processMsg(JsonNode &j)
{
target_ = j["target"].str();
return true;
}
bool JobMakerHandlerSia::validate(JsonNode &j)
{
// check fields are valid
if (j.type() != Utilities::JS::type::Obj ||
j["created_at_ts"].type() != Utilities::JS::type::Int ||
j["rpcAddress"].type() != Utilities::JS::type::Str ||
j["rpcUserPwd"].type() != Utilities::JS::type::Str ||
j["target"].type() != Utilities::JS::type::Str ||
j["hHash"].type() != Utilities::JS::type::Str) {
LOG(ERROR) << "work format not expected";
return false;
}
// check timestamp
if (j["created_at_ts"].uint32() + def_.maxJobDelay_ < time(nullptr))
{
LOG(ERROR) << "too old sia work: " << date("%F %T", j["created_at_ts"].uint32());
return false;
}
return true;
}
string JobMakerHandlerSia::makeStratumJobMsg()
{
if (0 == header_.size() ||
0 == target_.size())
return "";
const string jobIdStr = Strings::Format("%08x%08x", (uint32_t)time(nullptr), djb2(header_.c_str()));
assert(jobIdStr.length() == 16);
size_t pos;
uint64 jobId = stoull(jobIdStr, &pos, 16);
return Strings::Format("{\"created_at_ts\":%u"
",\"jobId\":%" PRIu64 ""
",\"target\":\"%s\""
",\"hHash\":\"%s\""
"}",
time_,
jobId,
target_.c_str(),
header_.c_str());
}
///////////////////////////////////JobMakerHandlerBytom//////////////////////////////////
bool JobMakerHandlerBytom::processMsg(JsonNode &j)
{
seed_ = j["sHash"].str();
return true;
}
bool JobMakerHandlerBytom::validate(JsonNode &j)
{
// check fields are valid
if (j.type() != Utilities::JS::type::Obj ||
j["created_at_ts"].type() != Utilities::JS::type::Int ||
j["rpcAddress"].type() != Utilities::JS::type::Str ||
j["rpcUserPwd"].type() != Utilities::JS::type::Str ||
j["hHash"].type() != Utilities::JS::type::Str) {
LOG(ERROR) << "work format not expected";
return false;
}
// check timestamp
if (j["created_at_ts"].uint32() + def_.maxJobDelay_ < time(nullptr))
{
LOG(ERROR) << "too old bytom work: " << date("%F %T", j["created_at_ts"].uint32());
return false;
}
return true;
}
string JobMakerHandlerBytom::makeStratumJobMsg()
{
if (0 == header_.size() ||
0 == seed_.size())
return "";
const string jobIdStr = Strings::Format("%08x%08x", (uint32_t)time(nullptr), djb2(header_.c_str()));
assert(jobIdStr.length() == 16);
size_t pos;
uint64 jobId = stoull(jobIdStr, &pos, 16);
return Strings::Format("{\"created_at_ts\":%u"
",\"jobId\":%" PRIu64 ""
",\"sHash\":\"%s\""
",\"hHash\":\"%s\""
"}",
time_,
jobId,
seed_.c_str(),
header_.c_str());
}
////////////////////////////////JobMakerHandlerBitcoin//////////////////////////////////
JobMakerHandlerBitcoin::JobMakerHandlerBitcoin() :
currBestHeight_(0), lastJobSendTime_(0),
isLastJobEmptyBlock_(false),
previousRskWork_(nullptr), currentRskWork_(nullptr),
isRskUpdate_(false)
{
}
bool JobMakerHandlerBitcoin::init(const GbtJobMakerDefinition &def) {
def_ = def;
// select chain
if (def_.testnet_) {
SelectParams(CBaseChainParams::TESTNET);
LOG(WARNING) << "using bitcoin testnet3";
} else {
SelectParams(CBaseChainParams::MAIN);
}
LOG(INFO) << "Block Version: " << std::hex << def_.blockVersion_;
LOG(INFO) << "Coinbase Info: " << def_.coinbaseInfo_;
LOG(INFO) << "Payout Address: " << def_.payoutAddr_;
// check pool payout address
if (!IsValidDestinationString(def_.payoutAddr_)) {
LOG(ERROR) << "invalid pool payout address";
return false;
}
poolPayoutAddr_ = DecodeDestination(def_.payoutAddr_);
// notify policy for RSK
RskWork::setIsCleanJob(def_.rskNotifyPolicy_ != 0);
return true;
}
bool JobMakerHandlerBitcoin::initConsumerHandlers(const string &kafkaBrokers, vector<JobMakerConsumerHandler> &handlers) {
const int32_t consumeLatestN = 20;
//
// consumer for RawGbt, offset: latest N messages
//
{
kafkaRawGbtConsumer_ = std::make_shared<KafkaConsumer>(kafkaBrokers.c_str(), def_.rawGbtTopic_.c_str(), 0/* partition */);
map<string, string> consumerOptions;
consumerOptions["fetch.wait.max.ms"] = "5";
if (!kafkaRawGbtConsumer_->setup(RD_KAFKA_OFFSET_TAIL(consumeLatestN), &consumerOptions)) {
LOG(ERROR) << "kafka consumer rawgbt setup failure";
return false;
}
if (!kafkaRawGbtConsumer_->checkAlive()) {
LOG(ERROR) << "kafka consumer rawgbt is NOT alive";
return false;
}
handlers.push_back({
def_.rawGbtTopic_,
kafkaRawGbtConsumer_,
std::bind(&JobMakerHandlerBitcoin::processRawGbtMsg, this, std::placeholders::_1)
});
}
//
// consumer for aux block
//
{
kafkaAuxPowConsumer_ = std::make_shared<KafkaConsumer>(kafkaBrokers.c_str(), def_.auxPowTopic_.c_str(), 0/* partition */);
map<string, string> consumerOptions;
consumerOptions["fetch.wait.max.ms"] = "5";
if (!kafkaAuxPowConsumer_->setup(RD_KAFKA_OFFSET_TAIL(1), &consumerOptions)) {
LOG(ERROR) << "kafka consumer aux pow setup failure";
return false;
}
if (!kafkaAuxPowConsumer_->checkAlive()) {
LOG(ERROR) << "kafka consumer aux pow is NOT alive";
return false;
}
handlers.push_back({
def_.auxPowTopic_,
kafkaAuxPowConsumer_,
std::bind(&JobMakerHandlerBitcoin::processAuxPowMsg, this, std::placeholders::_1)
});
}
//
// consumer for RSK messages
//
{
kafkaRskGwConsumer_ = std::make_shared<KafkaConsumer>(kafkaBrokers.c_str(), def_.rskRawGwTopic_.c_str(), 0/* partition */);
map<string, string> consumerOptions;
consumerOptions["fetch.wait.max.ms"] = "5";
if (!kafkaRskGwConsumer_->setup(RD_KAFKA_OFFSET_TAIL(1), &consumerOptions)) {
LOG(ERROR) << "kafka consumer rawgw block setup failure";
return false;
}
if (!kafkaRskGwConsumer_->checkAlive()) {
LOG(ERROR) << "kafka consumer rawgw block is NOT alive";
return false;
}
handlers.push_back({
def_.rskRawGwTopic_,
kafkaRskGwConsumer_,
std::bind(&JobMakerHandlerBitcoin::processRskGwMsg, this, std::placeholders::_1)
});
}
// sleep 3 seconds, wait for the latest N messages transfer from broker to client
sleep(3);
/* pre-consume some messages for initialization */
//
// consume the latest AuxPow message
//
{
rd_kafka_message_t *rkmessage;
rkmessage = kafkaAuxPowConsumer_->consumer(1000/* timeout ms */);
if (rkmessage != nullptr && !rkmessage->err) {
string msg((const char *)rkmessage->payload, rkmessage->len);
processAuxPowMsg(msg);
rd_kafka_message_destroy(rkmessage);
}
}
//
// consume the latest RSK getwork message
//
{
rd_kafka_message_t *rkmessage;
rkmessage = kafkaRskGwConsumer_->consumer(1000/* timeout ms */);
if (rkmessage != nullptr && !rkmessage->err) {
string msg((const char *)rkmessage->payload, rkmessage->len);
processRskGwMsg(msg);
rd_kafka_message_destroy(rkmessage);
}
}
//
// consume the latest N RawGbt messages
//
LOG(INFO) << "consume latest rawgbt messages from kafka...";
for (int32_t i = 0; i < consumeLatestN; i++) {
rd_kafka_message_t *rkmessage;
rkmessage = kafkaRawGbtConsumer_->consumer(5000/* timeout ms */);
if (rkmessage == nullptr || rkmessage->err) {
break;
}
string msg((const char *)rkmessage->payload, rkmessage->len);
processRawGbtMsg(msg);
rd_kafka_message_destroy(rkmessage);
}
LOG(INFO) << "consume latest rawgbt messages done";
return true;
}
bool JobMakerHandlerBitcoin::addRawGbt(const string &msg) {
JsonNode r;
if (!JsonNode::parse(msg.c_str(), msg.c_str() + msg.size(), r)) {
LOG(ERROR) << "parse rawgbt message to json fail";
return false;
}
if (r["created_at_ts"].type() != Utilities::JS::type::Int ||
r["block_template_base64"].type() != Utilities::JS::type::Str ||
r["gbthash"].type() != Utilities::JS::type::Str) {
LOG(ERROR) << "invalid rawgbt: missing fields";
return false;
}
const uint256 gbtHash = uint256S(r["gbthash"].str());
for (const auto &itr : lastestGbtHash_) {
if (gbtHash == itr) {
LOG(ERROR) << "duplicate gbt hash: " << gbtHash.ToString();
return false;
}
}
const uint32_t gbtTime = r["created_at_ts"].uint32();
const int64_t timeDiff = (int64_t)time(nullptr) - (int64_t)gbtTime;
if (labs(timeDiff) >= 60) {
LOG(WARNING) << "rawgbt diff time is more than 60, ignore it";
return false; // time diff too large, there must be some problems, so ignore it
}
if (labs(timeDiff) >= 3) {
LOG(WARNING) << "rawgbt diff time is too large: " << timeDiff << " seconds";
}
const string gbt = DecodeBase64(r["block_template_base64"].str());
assert(gbt.length() > 64); // valid gbt string's len at least 64 bytes
JsonNode nodeGbt;
if (!JsonNode::parse(gbt.c_str(), gbt.c_str() + gbt.length(), nodeGbt)) {
LOG(ERROR) << "parse gbt message to json fail";
return false;
}
assert(nodeGbt["result"]["height"].type() == Utilities::JS::type::Int);
const uint32_t height = nodeGbt["result"]["height"].uint32();
assert(nodeGbt["result"]["transactions"].type() == Utilities::JS::type::Array);
const bool isEmptyBlock = nodeGbt["result"]["transactions"].array().size() == 0;
{
ScopeLock sl(lock_);
if (!rawgbtMap_.empty()) {
const uint64_t bestKey = rawgbtMap_.rbegin()->first;
const uint32_t bestTime = gbtKeyGetTime(bestKey);
const uint32_t bestHeight = gbtKeyGetHeight(bestKey);
const bool bestIsEmpty = gbtKeyIsEmptyBlock(bestKey);
// To prevent the job's block height ups and downs
// when the block height of two bitcoind is not synchronized.
// The block height downs must past twice the time of stratumJobInterval_
// without the higher height GBT received.
if (height < bestHeight && !bestIsEmpty &&
gbtTime - bestTime < 2 * def_.jobInterval_) {
LOG(WARNING) << "skip low height GBT. height: " << height
<< ", best height: " << bestHeight
<< ", elapsed time after best GBT: " << (gbtTime - bestTime) << "s";
return false;
}
}
const uint64_t key = makeGbtKey(gbtTime, isEmptyBlock, height);
if (rawgbtMap_.find(key) == rawgbtMap_.end()) {
rawgbtMap_.insert(std::make_pair(key, gbt));
} else {
LOG(ERROR) << "key already exist in rawgbtMap: " << key;
}
}
lastestGbtHash_.push_back(gbtHash);
while (lastestGbtHash_.size() > 20) {
lastestGbtHash_.pop_front();
}
LOG(INFO) << "add rawgbt, height: "<< height << ", gbthash: "
<< r["gbthash"].str().substr(0, 16) << "..., gbtTime(UTC): " << date("%F %T", gbtTime)
<< ", isEmpty:" << isEmptyBlock;
return true;
}
bool JobMakerHandlerBitcoin::findBestRawGbt(bool isRskUpdate, string &bestRawGbt) {
static uint64_t lastSendBestKey = 0;
ScopeLock sl(lock_);
// clean expired gbt first
clearTimeoutGbt();
clearTimeoutRskGw();
if (rawgbtMap_.size() == 0) {
LOG(WARNING) << "RawGbt Map is empty";
return false;
}
bool isFindNewHeight = false;
bool needUpdateEmptyBlockJob = false;
// rawgbtMap_ is sorted gbt by (timestamp + height + emptyFlag),
// so the last item is the newest/best item.
// @see makeGbtKey()
const uint64_t bestKey = rawgbtMap_.rbegin()->first;
const uint32_t bestHeight = gbtKeyGetHeight(bestKey);
const bool currentGbtIsEmpty = gbtKeyIsEmptyBlock(bestKey);
// if last job is an empty block job, we need to
// send a new non-empty job as quick as possible.
if (bestHeight == currBestHeight_ && isLastJobEmptyBlock_ && !currentGbtIsEmpty) {
needUpdateEmptyBlockJob = true;
LOG(INFO) << "--------update last empty block job--------";
}
if (!needUpdateEmptyBlockJob && !isRskUpdate && bestKey == lastSendBestKey) {
LOG(WARNING) << "bestKey is the same as last one: " << lastSendBestKey;
return false;
}
// The height cannot reduce in normal.
// However, if there is indeed a height reduce,
// isReachTimeout() will allow the new job sending.
if (bestHeight > currBestHeight_) {
LOG(INFO) << ">>>> found new best height: " << bestHeight
<< ", curr: " << currBestHeight_ << " <<<<";
isFindNewHeight = true;
}
if (isFindNewHeight || needUpdateEmptyBlockJob || isRskUpdate || isReachTimeout()) {
lastSendBestKey = bestKey;
currBestHeight_ = bestHeight;
bestRawGbt = rawgbtMap_.rbegin()->second.c_str();
return true;
}
return false;
}
bool JobMakerHandlerBitcoin::isReachTimeout() {
uint32_t intervalSeconds = def_.jobInterval_;
if (lastJobSendTime_ + intervalSeconds <= time(nullptr)) {
return true;
}
return false;
}
void JobMakerHandlerBitcoin::clearTimeoutGbt() {
// Maps (and sets) are sorted, so the first element is the smallest,
// and the last element is the largest.
const uint32_t ts_now = time(nullptr);
for (auto itr = rawgbtMap_.begin(); itr != rawgbtMap_.end(); ) {
const uint32_t ts = gbtKeyGetTime(itr->first);
const bool isEmpty = gbtKeyIsEmptyBlock(itr->first);
const uint32_t height = gbtKeyGetHeight(itr->first);
// gbt expired time
const uint32_t expiredTime = ts + (isEmpty ? def_.emptyGbtLifeTime_ : def_.gbtLifeTime_);
if (expiredTime > ts_now) {
// not expired
++itr;
} else {
// remove expired gbt
LOG(INFO) << "remove timeout rawgbt: " << date("%F %T", ts) << "|" << ts <<
", height:" << height << ", isEmptyBlock:" << (isEmpty ? 1 : 0);
// c++11: returns an iterator to the next element in the map
itr = rawgbtMap_.erase(itr);
}
}
}
void JobMakerHandlerBitcoin::clearTimeoutRskGw() {
RskWork currentRskWork;
RskWork previousRskWork;
{
ScopeLock sl(rskWorkAccessLock_);
if (previousRskWork_ == nullptr || currentRskWork_ == nullptr) {
return;
}
const uint32_t ts_now = time(nullptr);
currentRskWork = *currentRskWork_;
if(currentRskWork.getCreatedAt() + 120u < ts_now) {
delete currentRskWork_;
currentRskWork_ = nullptr;
}
previousRskWork = *previousRskWork_;
if(previousRskWork.getCreatedAt() + 120u < ts_now) {
delete previousRskWork_;
previousRskWork_ = nullptr;
}
}
}
bool JobMakerHandlerBitcoin::triggerRskUpdate() {
RskWork currentRskWork;
RskWork previousRskWork;
{
ScopeLock sl(rskWorkAccessLock_);
if (previousRskWork_ == nullptr || currentRskWork_ == nullptr) {
return false;
}
currentRskWork = *currentRskWork_;
previousRskWork = *previousRskWork_;
}
bool notify_flag_update = def_.rskNotifyPolicy_ == 1 && currentRskWork.getNotifyFlag();
bool different_block_hashUpdate = def_.rskNotifyPolicy_ == 2 &&
(currentRskWork.getBlockHash() !=
previousRskWork.getBlockHash());
return notify_flag_update || different_block_hashUpdate;
}
bool JobMakerHandlerBitcoin::processRawGbtMsg(const string &msg) {
return addRawGbt(msg);
}
bool JobMakerHandlerBitcoin::processAuxPowMsg(const string &msg) {
// set json string
{
ScopeLock sl(auxJsonLock_);
latestAuxPowJson_ = msg;
DLOG(INFO) << "latestAuxPowJson: " << latestAuxPowJson_;
}
// auxpow message will nerver triggered a stratum job updating
return false;
}
bool JobMakerHandlerBitcoin::processRskGwMsg(const string &rawGetWork) {
// set json string
{
ScopeLock sl(rskWorkAccessLock_);
RskWork *rskWork = new RskWork();
if(rskWork->initFromGw(rawGetWork)) {
if (previousRskWork_ != nullptr) {
delete previousRskWork_;
previousRskWork_ = nullptr;
}
previousRskWork_ = currentRskWork_;
currentRskWork_ = rskWork;
DLOG(INFO) << "currentRskBlockJson: " << rawGetWork;
} else {
delete rskWork;
}
}
isRskUpdate_ = triggerRskUpdate();
return isRskUpdate_;
}
string JobMakerHandlerBitcoin::makeStratumJob(const string &gbt) {
string latestAuxPowJson;
{
ScopeLock sl(auxJsonLock_);
latestAuxPowJson = latestAuxPowJson_;
}
RskWork currentRskBlockJson;
{
ScopeLock sl(rskWorkAccessLock_);
if (currentRskWork_ != nullptr) {
currentRskBlockJson = *currentRskWork_;
}
}
StratumJob sjob;
if (!sjob.initFromGbt(gbt.c_str(), def_.coinbaseInfo_,
poolPayoutAddr_,
def_.blockVersion_,
latestAuxPowJson,
currentRskBlockJson)) {
LOG(ERROR) << "init stratum job message from gbt str fail";
return "";
}
const string jobMsg = sjob.serializeToJson();
// set last send time
// TODO: fix Y2K38 issue
lastJobSendTime_ = (uint32_t)time(nullptr);
// is an empty block job
isLastJobEmptyBlock_ = sjob.isEmptyBlock();
LOG(INFO) << "--------producer stratum job, jobId: " << sjob.jobId_
<< ", height: " << sjob.height_ << "--------";
LOG(INFO) << "sjob: " << jobMsg;
return jobMsg;
}
string JobMakerHandlerBitcoin::makeStratumJobMsg() {
string bestRawGbt;
if (!findBestRawGbt(isRskUpdate_, bestRawGbt)) {
return "";
}
isRskUpdate_ = false;
return makeStratumJob(bestRawGbt);
}
uint64_t JobMakerHandlerBitcoin::makeGbtKey(uint32_t gbtTime, bool isEmptyBlock, uint32_t height) {
assert(height < 0x7FFFFFFFU);
//
// gbtKey:
// -----------------------------------------------------------------------------------------
// | 32 bits | 31 bits | 1 bit |
// | xxxxxxxx xxxxxxxx xxxxxxxx xxxxxxxx | xxxxxxx xxxxxxxx xxxxxxxx xxxxxxxx | x |
// | gbtTime | height | nonEmptyFlag |
// -----------------------------------------------------------------------------------------
// use nonEmptyFlag (aka: !isEmptyBlock) so the key of a non-empty block
// will large than the key of an empty block.
//
return (((uint64_t)gbtTime) << 32) | (((uint64_t)height) << 1) | ((uint64_t)(!isEmptyBlock));
}
uint32_t JobMakerHandlerBitcoin::gbtKeyGetTime(uint64_t gbtKey) {
return (uint32_t)(gbtKey >> 32);
}
uint32_t JobMakerHandlerBitcoin::gbtKeyGetHeight(uint64_t gbtKey) {
return (uint32_t)((gbtKey >> 1) & 0x7FFFFFFFULL);
}
bool JobMakerHandlerBitcoin::gbtKeyIsEmptyBlock(uint64_t gbtKey) {
return !((bool)(gbtKey & 1ULL));
}
| 30.909187 | 148 | 0.633084 |
429bea5784defe29e1b8e7814008c928eec35630 | 532 | cpp | C++ | COURSE_WHITE/WEEK_2/FUNCTION/Maximizator/main.cpp | diekaltesonne/c-plus-plus-modern-development | d569bd20465e76aab97111bcd316cd02ebca41dd | [
"MIT"
] | null | null | null | COURSE_WHITE/WEEK_2/FUNCTION/Maximizator/main.cpp | diekaltesonne/c-plus-plus-modern-development | d569bd20465e76aab97111bcd316cd02ebca41dd | [
"MIT"
] | null | null | null | COURSE_WHITE/WEEK_2/FUNCTION/Maximizator/main.cpp | diekaltesonne/c-plus-plus-modern-development | d569bd20465e76aab97111bcd316cd02ebca41dd | [
"MIT"
] | null | null | null | #include <iostream>
using namespace std;
/*
*Напишите функцию UpdateIfGreater, которая принимает два целочисленных аргумента: first и second.
*Если first оказался больше second, Ваша функция должна записывать в second значение параметра first.
* При этом указанная функция не должна ничего возвращать, а изменение параметра second должно быть видно на вызывающей стороне.
*/
//void UpdateIfgreater(int & a, int& b );
int main()
{
return 0;
}
void UpdateIfGreater(int a, int& b) {
if (a > b) {
b = a;
}
}
| 24.181818 | 128 | 0.714286 |
429c0337af9ee2e19757a54743cf6b36927c872e | 3,014 | cc | C++ | trace/trace2timeline.cc | Rozelin-dc/malloc_challenge | 148f39f378cbd3ca8a7a2acb953d3789cdb85bb1 | [
"MIT"
] | 4 | 2021-06-19T15:03:01.000Z | 2022-01-30T23:05:09.000Z | trace/trace2timeline.cc | Rozelin-dc/malloc_challenge | 148f39f378cbd3ca8a7a2acb953d3789cdb85bb1 | [
"MIT"
] | null | null | null | trace/trace2timeline.cc | Rozelin-dc/malloc_challenge | 148f39f378cbd3ca8a7a2acb953d3789cdb85bb1 | [
"MIT"
] | 7 | 2021-06-11T11:07:39.000Z | 2021-06-17T17:27:49.000Z | #include <stdio.h>
#include <iostream>
#include <limits>
#include <unordered_map>
std::unordered_map<int64_t, int64_t> alloc_sizes;
int64_t peak_size = 0;
int64_t resident_size = 0;
int64_t allocation_size_accumlated = 0;
int64_t free_size_accumlated = 0;
FILE *trace_fp;
int64_t range_begin = std::numeric_limits<int64_t>::max();
int64_t range_end = std::numeric_limits<int64_t>::min();
/*
output trace format:
a <begin_addr> <end_addr>
f <begin_addr> <end_addr>
r <begin_addr> <end_addr>
*/
void trace_op(char op, int64_t addr, int64_t size) {
// Trace addr < 0x1'0000'0000LL ops only to ease visualization
fprintf(trace_fp, "%c %ld %ld\n", op, addr, size);
range_begin = std::min(range_begin, addr);
range_end = std::max(range_end, addr + size);
}
void record_alloc(int64_t addr, int64_t size) {
alloc_sizes.insert({addr, size});
resident_size += size;
allocation_size_accumlated += size;
peak_size = std::max(peak_size, resident_size);
trace_op('a', addr, size);
}
void record_free(int64_t addr) {
const auto &it = alloc_sizes.find(addr);
if (it == alloc_sizes.end()) {
printf("Addr 0x%lX is being freed but not allocated\n", addr);
return;
}
const int64_t size = (*it).second;
alloc_sizes.erase(it);
resident_size -= size;
free_size_accumlated += size;
trace_op('f', addr, size);
}
int main() {
char op;
int64_t addr;
int64_t count = 0;
int64_t last_resident_size = 0;
trace_fp = fopen("trace.txt", "wb");
if (!trace_fp) {
printf("Failed to open trace file");
exit(EXIT_FAILURE);
}
while (scanf(" %c %lX", &op, (uint64_t *)&addr) == 2) {
if (op == 'a') {
int64_t size;
if (scanf(" %lX", (uint64_t *)&size) != 1) {
printf("Failed to read size for alloc");
exit(EXIT_FAILURE);
}
record_alloc(addr, size);
} else if (op == 'r') {
int64_t size, old_addr;
if (scanf(" %lX %lX", (uint64_t *)&size, (uint64_t *)&old_addr) != 2) {
printf("Failed to read size and old_addr for realloc");
exit(EXIT_FAILURE);
}
// free
if (old_addr) {
record_free(old_addr);
}
record_alloc(addr, size);
} else if (op == 'f') {
record_free(addr);
} else {
printf("Unknown op: %c at count %ld\n", op, count);
exit(EXIT_FAILURE);
}
printf("%ld\t%ld\t%ld\t%ld\t%ld\n", count, resident_size,
allocation_size_accumlated, resident_size - last_resident_size,
free_size_accumlated);
last_resident_size = resident_size;
count++;
}
fprintf(stderr, "count: %ld\n", count);
fprintf(stderr, "peak_size: %ld\n", peak_size);
fprintf(stderr, "resident_size at last: %ld\n", resident_size);
fprintf(stderr, "allocation_size_accumlated: %ld\n",
allocation_size_accumlated);
fprintf(stderr, "range_begin: %ld\n",
range_begin);
fprintf(stderr, "range_end: %ld\n",
range_end);
fprintf(stderr, "range_size: %ld\n",
range_end - range_begin);
return 0;
}
| 28.433962 | 77 | 0.640345 |
429d0615f39c89daee4ce5a114d49518a0210c93 | 2,191 | cpp | C++ | code/core/chattablabel.cpp | detrax/gobby | 21160017e1f7ffe1123d80acadac88a22bd7f838 | [
"ISC"
] | 542 | 2015-01-03T21:43:38.000Z | 2022-03-26T11:43:54.000Z | code/core/chattablabel.cpp | detrax/gobby | 21160017e1f7ffe1123d80acadac88a22bd7f838 | [
"ISC"
] | 116 | 2015-01-14T08:08:43.000Z | 2021-08-03T19:24:46.000Z | code/core/chattablabel.cpp | detrax/gobby | 21160017e1f7ffe1123d80acadac88a22bd7f838 | [
"ISC"
] | 60 | 2015-01-03T21:43:42.000Z | 2022-03-19T12:04:52.000Z | /* Gobby - GTK-based collaborative text editor
* Copyright (C) 2008-2015 Armin Burgmeier <armin@arbur.net>
*
* Permission to use, copy, modify, and/or distribute this software for any
* purpose with or without fee is hereby granted, provided that the above
* copyright notice and this permission notice appear in all copies.
*
* THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
* WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
* ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
* WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
* ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
* OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
*/
#include "core/chattablabel.hpp"
Gobby::ChatTabLabel::ChatTabLabel(Folder& folder, ChatSessionView& view,
bool always_show_close_button):
TabLabel(folder, view,
always_show_close_button ?
"chat" :
"network-idle"),
m_always_show_close_button(always_show_close_button)
{
if(!m_always_show_close_button)
m_button.hide(); // Only show when disconnected
InfChatBuffer* buffer = INF_CHAT_BUFFER(
inf_session_get_buffer(INF_SESSION(view.get_session())));
m_add_message_handle = g_signal_connect_after(
G_OBJECT(buffer), "add-message",
G_CALLBACK(on_add_message_static), this);
}
Gobby::ChatTabLabel::~ChatTabLabel()
{
InfChatBuffer* buffer = INF_CHAT_BUFFER(
inf_session_get_buffer(INF_SESSION(m_view.get_session())));
g_signal_handler_disconnect(buffer, m_add_message_handle);
}
void Gobby::ChatTabLabel::on_notify_subscription_group()
{
InfSession* session = INF_SESSION(m_view.get_session());
if(inf_session_get_subscription_group(session) != NULL &&
!m_always_show_close_button)
{
m_button.hide();
}
else
{
m_button.show();
}
}
void Gobby::ChatTabLabel::on_changed(InfUser* author)
{
if(!m_changed)
{
InfSession* session = INF_SESSION(m_view.get_session());
if(inf_session_get_status(session) == INF_SESSION_RUNNING)
set_changed();
}
}
| 31.753623 | 75 | 0.74806 |
42a78b36f1ed4f5b61e6d008cc12cbd9eb5cb7b9 | 1,087 | cpp | C++ | C++/010_Regular_Expression_Matching.cpp | stephenkid/LeetCode-Sol | 8cb429652e0741ca4078b6de5f9eeaddcb8607a8 | [
"MIT"
] | 1,958 | 2015-01-30T01:19:03.000Z | 2022-03-17T03:34:47.000Z | src/main/cpp/010_Regular_Expression_Matching.cpp | TechnoBlogger14o3/LeetCode-Sol-Res | 04621f21a76fab29909c1fa04a37417257a88f63 | [
"MIT"
] | 135 | 2016-03-03T04:53:10.000Z | 2022-03-03T21:14:37.000Z | src/main/cpp/010_Regular_Expression_Matching.cpp | TechnoBlogger14o3/LeetCode-Sol-Res | 04621f21a76fab29909c1fa04a37417257a88f63 | [
"MIT"
] | 914 | 2015-01-27T22:27:22.000Z | 2022-03-05T04:25:10.000Z | //10. Regular Expression Matching
/*
'.' Matches any single character.
'*' Matches zero or more of the preceding element.
The matching should cover the entire input string (not partial).
The function prototype should be:
bool isMatch(const char *s, const char *p)
Some examples:
isMatch("aa","a") → false
isMatch("aa","aa") → true
isMatch("aaa","aa") → false
isMatch("aa", "a*") → true
isMatch("aa", ".*") → true
isMatch("ab", ".*") → true
isMatch("aab", "c*a*b") → true
Tag: Dynamic Programming, Backtracking, String
Author: Xinyu Liu
*/
#include <iostream>
#include <string>
using namespace std;
class Solution{
public:
bool isMatch(string s, string p){
if (p.empty()) return s.empty();
if (p[1] == '*')
return ((!s.empty() && (s[0] == p[0] || p[0] == '.') && isMatch(s.substr(1),p))|| isMatch(s,p.substr(2)));
else
return (!s.empty() && (s[0] == p[0] || p[0] == '.') && isMatch(s.substr(1),p.substr(1)));
}
};
void main(){
string s ("aaa");
string p ("a*");
Solution sol;
bool b = sol.isMatch(s,p);
}
| 22.183673 | 118 | 0.581417 |
42a8d987cbe42d8674866946c625ae148a31e200 | 730 | cpp | C++ | tests/data_structure/test_quad_tree.cpp | mitthy/TCC | 4c48eb11cafd50334c5faef93edc5f03bc7fc171 | [
"MIT"
] | null | null | null | tests/data_structure/test_quad_tree.cpp | mitthy/TCC | 4c48eb11cafd50334c5faef93edc5f03bc7fc171 | [
"MIT"
] | null | null | null | tests/data_structure/test_quad_tree.cpp | mitthy/TCC | 4c48eb11cafd50334c5faef93edc5f03bc7fc171 | [
"MIT"
] | null | null | null | #include "gtest/gtest.h"
#include "geometricks/data_structure/quad_tree.hpp"
#include <tuple>
#include <type_traits>
struct element_t {
int x, y, hw, hh;
};
namespace geometricks {
namespace rectangle_customization {
template<>
struct make_rectangle<element_t> {
static constexpr geometricks::rectangle
_( const element_t& value ) {
return { value.x, value.y, value.hw, value.hh };
}
};
}
}
TEST( TestQuadTree, TestCreation ) {
geometricks::quad_tree<std::tuple<int,int,int,int>> tree{ geometricks::rectangle{ -1000, -1000, 2000, 2000 } };
for( int i = 0; i < 256; ++i ) {
tree.insert( std::make_tuple( ( i + 5 ) * 2, ( i + 5 ) * 2, 10, 10 ) );
}
}
| 21.470588 | 113 | 0.610959 |
42a8e775526ada85918d187049907b4bfbaa8ac9 | 13,240 | hpp | C++ | src/xpcc/architecture/platform/cortex_m3/stm32/stm32f4/sdio/sdio_hal.hpp | walmis/xpcc | 1d87c4434530c6aeac923f57d379aeaf32e11e1e | [
"BSD-3-Clause"
] | null | null | null | src/xpcc/architecture/platform/cortex_m3/stm32/stm32f4/sdio/sdio_hal.hpp | walmis/xpcc | 1d87c4434530c6aeac923f57d379aeaf32e11e1e | [
"BSD-3-Clause"
] | null | null | null | src/xpcc/architecture/platform/cortex_m3/stm32/stm32f4/sdio/sdio_hal.hpp | walmis/xpcc | 1d87c4434530c6aeac923f57d379aeaf32e11e1e | [
"BSD-3-Clause"
] | null | null | null | /*
* sdio.hpp
*
* Created on: Apr 20, 2015
* Author: walmis
*/
#ifndef SRC_XPCC_ARCHITECTURE_PLATFORM_CORTEX_M3_STM32_STM32F4_SDIO_SDIO_HPP_
#define SRC_XPCC_ARCHITECTURE_PLATFORM_CORTEX_M3_STM32_STM32F4_SDIO_SDIO_HPP_
#include "../../../stm32.hpp"
namespace xpcc {
namespace stm32 {
/* ---------------------- SDIO registers bit mask ------------------------ */
/* --- CLKCR Register ---*/
/* CLKCR register clear mask */
#define CLKCR_CLEAR_MASK ((uint32_t)0xFFFF8100)
/* --- PWRCTRL Register ---*/
/* SDIO PWRCTRL Mask */
#define PWR_PWRCTRL_MASK ((uint32_t)0xFFFFFFFC)
/* --- DCTRL Register ---*/
/* SDIO DCTRL Clear Mask */
#define DCTRL_CLEAR_MASK ((uint32_t)0xFFFFFF08)
/* --- CMD Register ---*/
/* CMD Register clear mask */
#define CMD_CLEAR_MASK ((uint32_t)0xFFFFF800)
/* SDIO RESP Registers Address */
#define SDIO_RESP_ADDR ((uint32_t)(SDIO_BASE + 0x14))
/* ------------ SDIO registers bit address in the alias region ----------- */
#define SDIO_OFFSET (SDIO_BASE - PERIPH_BASE)
#define SDIO_CPSM_Disable ((uint32_t)0x00000000)
#define SDIO_CPSM_Enable ((uint32_t)0x00000400)
/* --- CLKCR Register ---*/
/* Alias word address of CLKEN bit */
#define CLKCR_OFFSET (SDIO_OFFSET + 0x04)
#define CLKEN_BitNumber 0x08
#define CLKCR_CLKEN_BB (PERIPH_BB_BASE + (CLKCR_OFFSET * 32) + (CLKEN_BitNumber * 4))
/* --- CMD Register ---*/
/* Alias word address of SDIOSUSPEND bit */
#define CMD_OFFSET (SDIO_OFFSET + 0x0C)
#define SDIOSUSPEND_BitNumber 0x0B
#define CMD_SDIOSUSPEND_BB (PERIPH_BB_BASE + (CMD_OFFSET * 32) + (SDIOSUSPEND_BitNumber * 4))
/* Alias word address of ENCMDCOMPL bit */
#define ENCMDCOMPL_BitNumber 0x0C
#define CMD_ENCMDCOMPL_BB (PERIPH_BB_BASE + (CMD_OFFSET * 32) + (ENCMDCOMPL_BitNumber * 4))
/* Alias word address of NIEN bit */
#define NIEN_BitNumber 0x0D
#define CMD_NIEN_BB (PERIPH_BB_BASE + (CMD_OFFSET * 32) + (NIEN_BitNumber * 4))
/* Alias word address of ATACMD bit */
#define ATACMD_BitNumber 0x0E
#define CMD_ATACMD_BB (PERIPH_BB_BASE + (CMD_OFFSET * 32) + (ATACMD_BitNumber * 4))
/* --- DCTRL Register ---*/
/* Alias word address of DMAEN bit */
#define DCTRL_OFFSET (SDIO_OFFSET + 0x2C)
#define DMAEN_BitNumber 0x03
#define DCTRL_DMAEN_BB (PERIPH_BB_BASE + (DCTRL_OFFSET * 32) + (DMAEN_BitNumber * 4))
/* Alias word address of RWSTART bit */
#define RWSTART_BitNumber 0x08
#define DCTRL_RWSTART_BB (PERIPH_BB_BASE + (DCTRL_OFFSET * 32) + (RWSTART_BitNumber * 4))
/* Alias word address of RWSTOP bit */
#define RWSTOP_BitNumber 0x09
#define DCTRL_RWSTOP_BB (PERIPH_BB_BASE + (DCTRL_OFFSET * 32) + (RWSTOP_BitNumber * 4))
/* Alias word address of RWMOD bit */
#define RWMOD_BitNumber 0x0A
#define DCTRL_RWMOD_BB (PERIPH_BB_BASE + (DCTRL_OFFSET * 32) + (RWMOD_BitNumber * 4))
/* Alias word address of SDIOEN bit */
#define SDIOEN_BitNumber 0x0B
#define DCTRL_SDIOEN_BB (PERIPH_BB_BASE + (DCTRL_OFFSET * 32) + (SDIOEN_BitNumber * 4))
class SDIO_HAL {
public:
enum class ClockEdge {
Rising = ((uint32_t) 0x00000000), Falling = ((uint32_t) 0x00002000)
};
enum class ClockFlags {
None = 0x00, Bypass = 0x400, PowerSave = 0x200
};
enum class BusWidth {
_1b = 0x00, _4b = 0x800, _8b = 0x1000
};
enum class HardwareFlowControl {
Disable = 0x00, Enable = 0x4000
};
enum class PowerState {
Off = 0x00, On = 0x03
};
/** @defgroup SDIO_Interrupt_sources
* @{
*/
enum Interrupt {
CCRCFAIL = ((uint32_t) 0x00000001),
DCRCFAIL = ((uint32_t) 0x00000002),
CTIMEOUT = ((uint32_t) 0x00000004),
DTIMEOUT = ((uint32_t) 0x00000008),
TXUNDERR = ((uint32_t) 0x00000010),
RXOVERR = ((uint32_t) 0x00000020),
CMDREND = ((uint32_t) 0x00000040),
CMDSENT = ((uint32_t) 0x00000080),
DATAEND = ((uint32_t) 0x00000100),
STBITERR = ((uint32_t) 0x00000200),
DBCKEND = ((uint32_t) 0x00000400),
CMDACT = ((uint32_t) 0x00000800),
TXACT = ((uint32_t) 0x00001000),
RXACT = ((uint32_t) 0x00002000),
TXFIFOHE = ((uint32_t) 0x00004000),
RXFIFOHF = ((uint32_t) 0x00008000),
TXFIFOF = ((uint32_t) 0x00010000),
RXFIFOF = ((uint32_t) 0x00020000),
TXFIFOE = ((uint32_t) 0x00040000),
RXFIFOE = ((uint32_t) 0x00080000),
TXDAVL = ((uint32_t) 0x00100000),
RXDAVL = ((uint32_t) 0x00200000),
SDIOIT = ((uint32_t) 0x00400000),
CEATAEND = ((uint32_t) 0x00800000)
};
#define IS_SDIO_IT(IT) ((((IT) & (uint32_t)0xFF000000) == 0x00) && ((IT) != (uint32_t)0x00))
/**
* @}
*/
/** @defgroup SDIO_Command_Index
* @{
*/
#define IS_SDIO_CMD_INDEX(INDEX) ((INDEX) < 0x40)
enum class ResponseType {
None = 0, Short = 0x40, Long = 0xC0
};
/** @defgroup SDIO_Wait_Interrupt_State
* @{
*/
enum class SDIOWait {
NoWait = 0,
WaitIT = 0x100,
WaitPend = 0x200
};
enum class CPSM {
Disable = 0x00, Enable = 0x400
};
enum class SDIOResp {
RESP1 = ((uint32_t) 0x00000000),
RESP2 = ((uint32_t) 0x00000004),
RESP3 = ((uint32_t) 0x00000008),
RESP4 = ((uint32_t) 0x0000000C)
};
enum class DataBlockSize {
_1b = ((uint32_t) 0x00000000),
_2b = ((uint32_t) 0x00000010),
_4b = ((uint32_t) 0x00000020),
_8b = ((uint32_t) 0x00000030),
_16b = ((uint32_t) 0x00000040),
_32b = ((uint32_t) 0x00000050),
_64b = ((uint32_t) 0x00000060),
_128b = ((uint32_t) 0x00000070),
_256b = ((uint32_t) 0x00000080),
_512b = ((uint32_t) 0x00000090),
_1024b = ((uint32_t) 0x000000A0),
_2048b = ((uint32_t) 0x000000B0),
_4096b = ((uint32_t) 0x000000C0),
_8192b = ((uint32_t) 0x000000D0),
_16384b = ((uint32_t) 0x000000E0)
};
enum class TransferDir {
ToCard = 0x00, ToSDIO = 0x02
};
enum class TransferMode {
Block = 0x0, Stream = 0x04
};
enum class DPSM {
Disable = 0, Enable = 1
};
enum ReadWaitMode {
CLK = 0x0, DATA2 = 0x01
};
static inline void init() {
RCC->APB2ENR |= RCC_APB2ENR_SDIOEN;
uint32_t tmpreg;
/* Get the SDIO CLKCR value */
tmpreg = SDIO->CLKCR;
/* Clear CLKDIV, PWRSAV, BYPASS, WIDBUS, NEGEDGE, HWFC_EN bits */
tmpreg &= CLKCR_CLEAR_MASK;
/* Set CLKDIV bits according to SDIO_ClockDiv value */
/* Set PWRSAV bit according to SDIO_ClockPowerSave value */
/* Set BYPASS bit according to SDIO_ClockBypass value */
/* Set WIDBUS bits according to SDIO_BusWide value */
/* Set NEGEDGE bits according to SDIO_ClockEdge value */
/* Set HWFC_EN bits according to SDIO_HardwareFlowControl value */
tmpreg |= (uint32_t) ClockFlags::None | (uint32_t) BusWidth::_1b
| (uint32_t) ClockEdge::Rising
| (uint32_t) HardwareFlowControl::Disable;
/* Write to SDIO CLKCR */
SDIO->CLKCR = tmpreg;
}
static inline void setClockFlags(ClockFlags flags) {
SDIO->CLKCR &= ~((1 << 9) | (1 << 10));
SDIO->CLKCR |= (uint32_t) flags;
}
static inline void setClockEdge(ClockEdge edge) {
SDIO->CLKCR &= ~((1 << 13));
SDIO->CLKCR |= (uint32_t) edge;
}
static inline void setClockDiv(uint8_t div) {
SDIO->CLKCR &= ~0xFF;
SDIO->CLKCR |= (uint32_t) div;
}
static inline void setBusWidth(BusWidth bw) {
SDIO->CLKCR &= ~((1 << 11) | (1 << 12));
SDIO->CLKCR |= (uint32_t) bw;
}
static inline void setHardwareFlowControl(HardwareFlowControl fc) {
SDIO->CLKCR &= ~((1 << 14));
SDIO->CLKCR |= (uint32_t) fc;
}
static inline void setClockState(bool state) {
*(__IO uint32_t *) CLKCR_CLKEN_BB = (uint32_t) state;
}
static inline void setPowerState(PowerState state = PowerState::On) {
SDIO->POWER = (uint32_t) state;
}
static inline PowerState getPowerState() {
return (PowerState) SDIO->POWER;
}
static inline void sendCommand(uint32_t argument, uint32_t cmdindex,
ResponseType resptype, SDIOWait wait = SDIOWait::NoWait) {
uint32_t tmpreg;
/*---------------------------- SDIO ARG Configuration ------------------------*/
/* Set the SDIO Argument value */
SDIO->ARG = argument;
/*---------------------------- SDIO CMD Configuration ------------------------*/
/* Get the SDIO CMD value */
tmpreg = SDIO->CMD;
/* Clear CMDINDEX, WAITRESP, WAITINT, WAITPEND, CPSMEN bits */
tmpreg &= CMD_CLEAR_MASK;
/* Set CMDINDEX bits according to SDIO_CmdIndex value */
/* Set WAITRESP bits according to SDIO_Response value */
/* Set WAITINT and WAITPEND bits according to SDIO_Wait value */
/* Set CPSMEN bits according to SDIO_CPSM value */
tmpreg |= ((uint32_t) cmdindex & SDIO_CMD_CMDINDEX) | ((uint32_t) resptype & SDIO_CMD_WAITRESP) | (uint32_t) wait
| SDIO_CPSM_Enable;
/* Write to SDIO CMD */
SDIO->CMD = tmpreg;
}
static inline uint8_t getCommandResponse() {
return (uint8_t) (SDIO->RESPCMD);
}
static inline uint32_t getResponse(SDIOResp resp) {
__IO uint32_t tmp = 0;
tmp = SDIO_RESP_ADDR + (uint32_t) resp;
return (*(__IO uint32_t *) tmp);
}
static inline void startDataTransaction(TransferDir dir, uint32_t length,
TransferMode mode = TransferMode::Block, DataBlockSize bs =
DataBlockSize::_512b, uint32_t timeout = 0xFFFFFFFF) {
uint32_t tmpreg;
/* Set the SDIO Data TimeOut value */
SDIO->DTIMER = timeout;
/*---------------------------- SDIO DLEN Configuration -----------------------*/
/* Set the SDIO DataLength value */
SDIO->DLEN = length;
/*---------------------------- SDIO DCTRL Configuration ----------------------*/
/* Get the SDIO DCTRL value */
tmpreg = SDIO->DCTRL;
/* Clear DEN, DTMODE, DTDIR and DBCKSIZE bits */
tmpreg &= DCTRL_CLEAR_MASK;
/* Set DEN bit according to SDIO_DPSM value */
/* Set DTMODE bit according to SDIO_TransferMode value */
/* Set DTDIR bit according to SDIO_TransferDir value */
/* Set DBCKSIZE bits according to SDIO_DataBlockSize value */
tmpreg |= (uint32_t) bs | (uint32_t) dir | (uint32_t) mode | 0x01;
/* Write to SDIO DCTRL */
SDIO->DCTRL = tmpreg;
}
static inline void resetDataPath() {
SDIO->DCTRL = 0;
}
static inline void resetCommandPath() {
SDIO->CMD = 0;
}
static inline uint32_t getDataCounter(void) {
return SDIO->DCOUNT;
}
static inline uint32_t readData(void) {
return SDIO->FIFO;
}
static inline void writeData(uint32_t Data) {
SDIO->FIFO = Data;
}
static inline uint32_t getFIFOCount(void) {
return SDIO->FIFOCNT;
}
/**
* @brief Starts the SD I/O Read Wait operation.
* @param NewState: new state of the Start SDIO Read Wait operation.
* This parameter can be: ENABLE or DISABLE.
* @retval None
*/
static inline void startSDIOReadWait(bool NewState) {
*(__IO uint32_t *) DCTRL_RWSTART_BB = (uint32_t) NewState;
}
/**
* @brief Stops the SD I/O Read Wait operation.
* @param NewState: new state of the Stop SDIO Read Wait operation.
* This parameter can be: ENABLE or DISABLE.
* @retval None
*/
static inline void stopSDIOReadWait(bool NewState) {
*(__IO uint32_t *) DCTRL_RWSTOP_BB = (uint32_t) NewState;
}
/**
* @brief Sets one of the two options of inserting read wait interval.
* @param SDIO_ReadWaitMode: SD I/O Read Wait operation mode.
* This parameter can be:
* @arg SDIO_ReadWaitMode_CLK: Read Wait control by stopping SDIOCLK
* @arg SDIO_ReadWaitMode_DATA2: Read Wait control using SDIO_DATA2
* @retval None
*/
static inline void setSDIOReadWaitMode(ReadWaitMode SDIO_ReadWaitMode) {
*(__IO uint32_t *) DCTRL_RWMOD_BB = (uint32_t) SDIO_ReadWaitMode;
}
/**
* @brief Enables or disables the SD I/O Mode Operation.
* @param NewState: new state of SDIO specific operation.
* This parameter can be: ENABLE or DISABLE.
* @retval None
*/
static inline void setSDIOOperation(bool NewState) {
*(__IO uint32_t *) DCTRL_SDIOEN_BB = (uint32_t) NewState;
}
/**
* @brief Enables or disables the SD I/O Mode suspend command sending.
* @param NewState: new state of the SD I/O Mode suspend command.
* This parameter can be: ENABLE or DISABLE.
* @retval None
*/
static inline void sendSDIOSuspendCmd(bool NewState) {
*(__IO uint32_t *) CMD_SDIOSUSPEND_BB = (uint32_t) NewState;
}
/**
* @brief Enables or disables the SDIO DMA request.
* @param NewState: new state of the selected SDIO DMA request.
* This parameter can be: ENABLE or DISABLE.
* @retval None
*/
static inline void DMACmd(bool enable) {
*(__IO uint32_t *) DCTRL_DMAEN_BB = (uint32_t) enable;
}
static inline void setInterruptMask(Interrupt it) {
SDIO->MASK = (uint32_t) it;
}
static inline void interruptConfig(Interrupt it, bool NewState) {
if (NewState) {
/* Enable the SDIO interrupts */
SDIO->MASK |= (uint32_t) it;
} else {
/* Disable the SDIO interrupts */
SDIO->MASK &= ~(uint32_t) it;
}
}
static inline uint32_t getInterruptFlags() {
return SDIO->STA;
}
static inline bool getInterruptStatus(Interrupt it) {
if ((SDIO->STA & (uint32_t) it)) {
return true;
} else {
return false;
}
}
static inline void clearInterrupt(Interrupt it) {
SDIO->ICR = (uint32_t) it;
}
};
ENUM_CLASS_FLAG(SDIO_HAL::Interrupt);
}
}
#endif /* SRC_XPCC_ARCHITECTURE_PLATFORM_CORTEX_M3_STM32_STM32F4_SDIO_SDIO_HPP_ */
| 28.908297 | 115 | 0.656193 |
42a9208251f39477bf054939e4474f914c29221c | 18,316 | cpp | C++ | rclcpp/src/rclcpp/time_source.cpp | RTI-BDI/rclcpp | c29a916429285362d4d8072b698b6c200d1d2a37 | [
"Apache-2.0"
] | 1 | 2022-02-28T21:29:12.000Z | 2022-02-28T21:29:12.000Z | rclcpp/src/rclcpp/time_source.cpp | stokekld/rclcpp | 025cd5ccc8202a52f7c7a3f037d8faf46f7dc3f3 | [
"Apache-2.0"
] | null | null | null | rclcpp/src/rclcpp/time_source.cpp | stokekld/rclcpp | 025cd5ccc8202a52f7c7a3f037d8faf46f7dc3f3 | [
"Apache-2.0"
] | null | null | null | // Copyright 2017 Open Source Robotics Foundation, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#include <memory>
#include <string>
#include <utility>
#include <vector>
#include "builtin_interfaces/msg/time.hpp"
#include "rcl/time.h"
#include "rclcpp/clock.hpp"
#include "rclcpp/exceptions.hpp"
#include "rclcpp/logging.hpp"
#include "rclcpp/node.hpp"
#include "rclcpp/parameter_client.hpp"
#include "rclcpp/parameter_events_filter.hpp"
#include "rclcpp/time.hpp"
#include "rclcpp/time_source.hpp"
namespace rclcpp
{
class ClocksState final
{
public:
ClocksState()
: logger_(rclcpp::get_logger("rclcpp"))
{
}
// An internal method to use in the clock callback that iterates and enables all clocks
void enable_ros_time()
{
if (ros_time_active_) {
// already enabled no-op
return;
}
// Local storage
ros_time_active_ = true;
// Update all attached clocks to zero or last recorded time
std::lock_guard<std::mutex> guard(clock_list_lock_);
auto time_msg = std::make_shared<builtin_interfaces::msg::Time>();
if (last_msg_set_) {
time_msg = std::make_shared<builtin_interfaces::msg::Time>(last_msg_set_->clock);
}
for (auto it = associated_clocks_.begin(); it != associated_clocks_.end(); ++it) {
set_clock(time_msg, true, *it);
}
}
// An internal method to use in the clock callback that iterates and disables all clocks
void disable_ros_time()
{
if (!ros_time_active_) {
// already disabled no-op
return;
}
// Local storage
ros_time_active_ = false;
// Update all attached clocks
std::lock_guard<std::mutex> guard(clock_list_lock_);
for (auto it = associated_clocks_.begin(); it != associated_clocks_.end(); ++it) {
auto msg = std::make_shared<builtin_interfaces::msg::Time>();
set_clock(msg, false, *it);
}
}
// Check if ROS time is active
bool is_ros_time_active() const
{
return ros_time_active_;
}
// Attach a clock
void attachClock(rclcpp::Clock::SharedPtr clock)
{
if (clock->get_clock_type() != RCL_ROS_TIME) {
throw std::invalid_argument("Cannot attach clock to a time source that's not a ROS clock");
}
std::lock_guard<std::mutex> guard(clock_list_lock_);
associated_clocks_.push_back(clock);
// Set the clock to zero unless there's a recently received message
auto time_msg = std::make_shared<builtin_interfaces::msg::Time>();
if (last_msg_set_) {
time_msg = std::make_shared<builtin_interfaces::msg::Time>(last_msg_set_->clock);
}
set_clock(time_msg, ros_time_active_, clock);
}
// Detach a clock
void detachClock(rclcpp::Clock::SharedPtr clock)
{
std::lock_guard<std::mutex> guard(clock_list_lock_);
auto result = std::find(associated_clocks_.begin(), associated_clocks_.end(), clock);
if (result != associated_clocks_.end()) {
associated_clocks_.erase(result);
} else {
RCLCPP_ERROR(logger_, "failed to remove clock");
}
}
// Internal helper function used inside iterators
static void set_clock(
const builtin_interfaces::msg::Time::SharedPtr msg,
bool set_ros_time_enabled,
rclcpp::Clock::SharedPtr clock)
{
std::lock_guard<std::mutex> clock_guard(clock->get_clock_mutex());
// Do change
if (!set_ros_time_enabled && clock->ros_time_is_active()) {
auto ret = rcl_disable_ros_time_override(clock->get_clock_handle());
if (ret != RCL_RET_OK) {
rclcpp::exceptions::throw_from_rcl_error(
ret, "Failed to disable ros_time_override_status");
}
} else if (set_ros_time_enabled && !clock->ros_time_is_active()) {
auto ret = rcl_enable_ros_time_override(clock->get_clock_handle());
if (ret != RCL_RET_OK) {
rclcpp::exceptions::throw_from_rcl_error(
ret, "Failed to enable ros_time_override_status");
}
}
auto ret = rcl_set_ros_time_override(
clock->get_clock_handle(),
rclcpp::Time(*msg).nanoseconds());
if (ret != RCL_RET_OK) {
rclcpp::exceptions::throw_from_rcl_error(
ret, "Failed to set ros_time_override_status");
}
}
// Internal helper function
void set_all_clocks(
const builtin_interfaces::msg::Time::SharedPtr msg,
bool set_ros_time_enabled)
{
std::lock_guard<std::mutex> guard(clock_list_lock_);
for (auto it = associated_clocks_.begin(); it != associated_clocks_.end(); ++it) {
set_clock(msg, set_ros_time_enabled, *it);
}
}
// Cache the last clock message received
void cache_last_msg(std::shared_ptr<const rosgraph_msgs::msg::Clock> msg)
{
last_msg_set_ = msg;
}
private:
// Store (and update on node attach) logger for logging.
Logger logger_;
// A lock to protect iterating the associated_clocks_ field.
std::mutex clock_list_lock_;
// A vector to store references to associated clocks.
std::vector<rclcpp::Clock::SharedPtr> associated_clocks_;
// Local storage of validity of ROS time
// This is needed when new clocks are added.
bool ros_time_active_{false};
// Last set message to be passed to newly registered clocks
std::shared_ptr<const rosgraph_msgs::msg::Clock> last_msg_set_;
};
class TimeSource::NodeState final
{
public:
NodeState(const rclcpp::QoS & qos, bool use_clock_thread)
: use_clock_thread_(use_clock_thread),
logger_(rclcpp::get_logger("rclcpp")),
qos_(qos)
{
}
~NodeState()
{
if (
node_base_ || node_topics_ || node_graph_ || node_services_ ||
node_logging_ || node_clock_ || node_parameters_)
{
detachNode();
}
}
// Check if a clock thread will be used
bool get_use_clock_thread()
{
return use_clock_thread_;
}
// Set whether a clock thread will be used
void set_use_clock_thread(bool use_clock_thread)
{
use_clock_thread_ = use_clock_thread;
}
// Check if the clock thread is joinable
bool clock_thread_is_joinable()
{
return clock_executor_thread_.joinable();
}
// Attach a node to this time source
void attachNode(
rclcpp::node_interfaces::NodeBaseInterface::SharedPtr node_base_interface,
rclcpp::node_interfaces::NodeTopicsInterface::SharedPtr node_topics_interface,
rclcpp::node_interfaces::NodeGraphInterface::SharedPtr node_graph_interface,
rclcpp::node_interfaces::NodeServicesInterface::SharedPtr node_services_interface,
rclcpp::node_interfaces::NodeLoggingInterface::SharedPtr node_logging_interface,
rclcpp::node_interfaces::NodeClockInterface::SharedPtr node_clock_interface,
rclcpp::node_interfaces::NodeParametersInterface::SharedPtr node_parameters_interface)
{
node_base_ = node_base_interface;
node_topics_ = node_topics_interface;
node_graph_ = node_graph_interface;
node_services_ = node_services_interface;
node_logging_ = node_logging_interface;
node_clock_ = node_clock_interface;
node_parameters_ = node_parameters_interface;
// TODO(tfoote): Update QOS
logger_ = node_logging_->get_logger();
// Though this defaults to false, it can be overridden by initial parameter values for the
// node, which may be given by the user at the node's construction or even by command-line
// arguments.
rclcpp::ParameterValue use_sim_time_param;
const std::string use_sim_time_name = "use_sim_time";
if (!node_parameters_->has_parameter(use_sim_time_name)) {
use_sim_time_param = node_parameters_->declare_parameter(
use_sim_time_name,
rclcpp::ParameterValue(false));
} else {
use_sim_time_param = node_parameters_->get_parameter(use_sim_time_name).get_parameter_value();
}
if (use_sim_time_param.get_type() == rclcpp::PARAMETER_BOOL) {
if (use_sim_time_param.get<bool>()) {
parameter_state_ = SET_TRUE;
clocks_state_.enable_ros_time();
create_clock_sub();
}
} else {
RCLCPP_ERROR(
logger_, "Invalid type '%s' for parameter 'use_sim_time', should be 'bool'",
rclcpp::to_string(use_sim_time_param.get_type()).c_str());
throw std::invalid_argument("Invalid type for parameter 'use_sim_time', should be 'bool'");
}
// TODO(tfoote) use parameters interface not subscribe to events via topic ticketed #609
parameter_subscription_ = rclcpp::AsyncParametersClient::on_parameter_event(
node_topics_,
[this](std::shared_ptr<const rcl_interfaces::msg::ParameterEvent> event) {
if (node_base_ != nullptr) {
this->on_parameter_event(event);
}
// Do nothing if node_base_ is nullptr because it means the TimeSource is now
// without an attached node
});
}
// Detach the attached node
void detachNode()
{
// destroy_clock_sub() *must* be first here, to ensure that the executor
// can't possibly call any of the callbacks as we are cleaning up.
destroy_clock_sub();
clocks_state_.disable_ros_time();
parameter_subscription_.reset();
node_base_.reset();
node_topics_.reset();
node_graph_.reset();
node_services_.reset();
node_logging_.reset();
node_clock_.reset();
node_parameters_.reset();
}
void attachClock(std::shared_ptr<rclcpp::Clock> clock)
{
clocks_state_.attachClock(std::move(clock));
}
void detachClock(std::shared_ptr<rclcpp::Clock> clock)
{
clocks_state_.detachClock(std::move(clock));
}
private:
ClocksState clocks_state_;
// Dedicated thread for clock subscription.
bool use_clock_thread_;
std::thread clock_executor_thread_;
// Preserve the node reference
rclcpp::node_interfaces::NodeBaseInterface::SharedPtr node_base_{nullptr};
rclcpp::node_interfaces::NodeTopicsInterface::SharedPtr node_topics_{nullptr};
rclcpp::node_interfaces::NodeGraphInterface::SharedPtr node_graph_{nullptr};
rclcpp::node_interfaces::NodeServicesInterface::SharedPtr node_services_{nullptr};
rclcpp::node_interfaces::NodeLoggingInterface::SharedPtr node_logging_{nullptr};
rclcpp::node_interfaces::NodeClockInterface::SharedPtr node_clock_{nullptr};
rclcpp::node_interfaces::NodeParametersInterface::SharedPtr node_parameters_{nullptr};
// Store (and update on node attach) logger for logging.
Logger logger_;
// QoS of the clock subscription.
rclcpp::QoS qos_;
// The subscription for the clock callback
using SubscriptionT = rclcpp::Subscription<rosgraph_msgs::msg::Clock>;
std::shared_ptr<SubscriptionT> clock_subscription_{nullptr};
std::mutex clock_sub_lock_;
rclcpp::CallbackGroup::SharedPtr clock_callback_group_;
rclcpp::executors::SingleThreadedExecutor::SharedPtr clock_executor_;
std::promise<void> cancel_clock_executor_promise_;
// The clock callback itself
void clock_cb(std::shared_ptr<const rosgraph_msgs::msg::Clock> msg)
{
if (!clocks_state_.is_ros_time_active() && SET_TRUE == this->parameter_state_) {
clocks_state_.enable_ros_time();
}
// Cache the last message in case a new clock is attached.
clocks_state_.cache_last_msg(msg);
auto time_msg = std::make_shared<builtin_interfaces::msg::Time>(msg->clock);
if (SET_TRUE == this->parameter_state_) {
clocks_state_.set_all_clocks(time_msg, true);
}
}
// Create the subscription for the clock topic
void create_clock_sub()
{
std::lock_guard<std::mutex> guard(clock_sub_lock_);
if (clock_subscription_) {
// Subscription already created.
return;
}
rclcpp::SubscriptionOptions options;
options.qos_overriding_options = rclcpp::QosOverridingOptions(
{
rclcpp::QosPolicyKind::Depth,
rclcpp::QosPolicyKind::Durability,
rclcpp::QosPolicyKind::History,
rclcpp::QosPolicyKind::Reliability,
});
if (use_clock_thread_) {
clock_callback_group_ = node_base_->create_callback_group(
rclcpp::CallbackGroupType::MutuallyExclusive,
false
);
options.callback_group = clock_callback_group_;
rclcpp::ExecutorOptions exec_options;
exec_options.context = node_base_->get_context();
clock_executor_ =
std::make_shared<rclcpp::executors::SingleThreadedExecutor>(exec_options);
if (!clock_executor_thread_.joinable()) {
cancel_clock_executor_promise_ = std::promise<void>{};
clock_executor_thread_ = std::thread(
[this]() {
auto future = cancel_clock_executor_promise_.get_future();
clock_executor_->add_callback_group(clock_callback_group_, node_base_);
clock_executor_->spin_until_future_complete(future);
}
);
}
}
clock_subscription_ = rclcpp::create_subscription<rosgraph_msgs::msg::Clock>(
node_parameters_,
node_topics_,
"/clock",
qos_,
[this](std::shared_ptr<const rosgraph_msgs::msg::Clock> msg) {
// We are using node_base_ as an indication if there is a node attached.
// Only call the clock_cb if that is the case.
if (node_base_ != nullptr) {
clock_cb(msg);
}
},
options
);
}
// Destroy the subscription for the clock topic
void destroy_clock_sub()
{
std::lock_guard<std::mutex> guard(clock_sub_lock_);
if (clock_executor_thread_.joinable()) {
cancel_clock_executor_promise_.set_value();
clock_executor_->cancel();
clock_executor_thread_.join();
clock_executor_->remove_callback_group(clock_callback_group_);
}
clock_subscription_.reset();
}
// Parameter Event subscription
using ParamSubscriptionT = rclcpp::Subscription<rcl_interfaces::msg::ParameterEvent>;
std::shared_ptr<ParamSubscriptionT> parameter_subscription_;
// Callback for parameter updates
void on_parameter_event(std::shared_ptr<const rcl_interfaces::msg::ParameterEvent> event)
{
// Filter out events on 'use_sim_time' parameter instances in other nodes.
if (event->node != node_base_->get_fully_qualified_name()) {
return;
}
// Filter for only 'use_sim_time' being added or changed.
rclcpp::ParameterEventsFilter filter(event, {"use_sim_time"},
{rclcpp::ParameterEventsFilter::EventType::NEW,
rclcpp::ParameterEventsFilter::EventType::CHANGED});
for (auto & it : filter.get_events()) {
if (it.second->value.type != ParameterType::PARAMETER_BOOL) {
RCLCPP_ERROR(logger_, "use_sim_time parameter cannot be set to anything but a bool");
continue;
}
if (it.second->value.bool_value) {
parameter_state_ = SET_TRUE;
clocks_state_.enable_ros_time();
create_clock_sub();
} else {
parameter_state_ = SET_FALSE;
destroy_clock_sub();
clocks_state_.disable_ros_time();
}
}
// Handle the case that use_sim_time was deleted.
rclcpp::ParameterEventsFilter deleted(event, {"use_sim_time"},
{rclcpp::ParameterEventsFilter::EventType::DELETED});
for (auto & it : deleted.get_events()) {
(void) it; // if there is a match it's already matched, don't bother reading it.
// If the parameter is deleted mark it as unset but don't change state.
parameter_state_ = UNSET;
}
}
// An enum to hold the parameter state
enum UseSimTimeParameterState {UNSET, SET_TRUE, SET_FALSE};
UseSimTimeParameterState parameter_state_;
};
TimeSource::TimeSource(
std::shared_ptr<rclcpp::Node> node,
const rclcpp::QoS & qos,
bool use_clock_thread)
: TimeSource(qos, use_clock_thread)
{
attachNode(node);
}
TimeSource::TimeSource(
const rclcpp::QoS & qos,
bool use_clock_thread)
: constructed_use_clock_thread_(use_clock_thread),
constructed_qos_(qos)
{
node_state_ = std::make_shared<NodeState>(qos, use_clock_thread);
}
void TimeSource::attachNode(rclcpp::Node::SharedPtr node)
{
node_state_->set_use_clock_thread(node->get_node_options().use_clock_thread());
attachNode(
node->get_node_base_interface(),
node->get_node_topics_interface(),
node->get_node_graph_interface(),
node->get_node_services_interface(),
node->get_node_logging_interface(),
node->get_node_clock_interface(),
node->get_node_parameters_interface());
}
void TimeSource::attachNode(
rclcpp::node_interfaces::NodeBaseInterface::SharedPtr node_base_interface,
rclcpp::node_interfaces::NodeTopicsInterface::SharedPtr node_topics_interface,
rclcpp::node_interfaces::NodeGraphInterface::SharedPtr node_graph_interface,
rclcpp::node_interfaces::NodeServicesInterface::SharedPtr node_services_interface,
rclcpp::node_interfaces::NodeLoggingInterface::SharedPtr node_logging_interface,
rclcpp::node_interfaces::NodeClockInterface::SharedPtr node_clock_interface,
rclcpp::node_interfaces::NodeParametersInterface::SharedPtr node_parameters_interface)
{
node_state_->attachNode(
std::move(node_base_interface),
std::move(node_topics_interface),
std::move(node_graph_interface),
std::move(node_services_interface),
std::move(node_logging_interface),
std::move(node_clock_interface),
std::move(node_parameters_interface));
}
void TimeSource::detachNode()
{
node_state_.reset();
node_state_ = std::make_shared<NodeState>(
constructed_qos_,
constructed_use_clock_thread_);
}
void TimeSource::attachClock(std::shared_ptr<rclcpp::Clock> clock)
{
node_state_->attachClock(std::move(clock));
}
void TimeSource::detachClock(std::shared_ptr<rclcpp::Clock> clock)
{
node_state_->detachClock(std::move(clock));
}
bool TimeSource::get_use_clock_thread()
{
return node_state_->get_use_clock_thread();
}
void TimeSource::set_use_clock_thread(bool use_clock_thread)
{
node_state_->set_use_clock_thread(use_clock_thread);
}
bool TimeSource::clock_thread_is_joinable()
{
return node_state_->clock_thread_is_joinable();
}
TimeSource::~TimeSource()
{
}
} // namespace rclcpp
| 33.001802 | 100 | 0.71473 |
42ad3848e22a63e1e8823742916de5544ff84725 | 1,730 | hh | C++ | grasp/Grasp.hh | el-cangrejo/grasp | 492dd14928b0072beecf752075b712db96f06834 | [
"MIT"
] | 70 | 2018-10-17T17:37:22.000Z | 2022-02-28T15:19:47.000Z | grasp/Grasp.hh | el-cangrejo/grasp | 492dd14928b0072beecf752075b712db96f06834 | [
"MIT"
] | 3 | 2020-12-08T13:02:17.000Z | 2022-02-22T11:59:00.000Z | grasp/Grasp.hh | el-cangrejo/grasp | 492dd14928b0072beecf752075b712db96f06834 | [
"MIT"
] | 17 | 2018-10-29T04:09:45.000Z | 2022-03-19T11:34:55.000Z | /*!
\file grasp/Grasp.hh
\brief Grasp representation
\author João Borrego : jsbruglie
*/
#ifndef _GRASP_HH_
#define _GRASP_HH_
// Gazebo
#include <gazebo/gazebo_client.hh>
// Open YAML config files
#include "yaml-cpp/yaml.h"
// Debug streams
#include "debug.hh"
/// \brief Grasp representation class
class Grasp
{
// Public attributes
/// Grasp candidate name
public: int id;
/// Homogenous transform matrix from gripper to object reference frame
public: ignition::math::Matrix4d t_gripper_object;
/// Grasp success metric
public: double metric {false};
/// \brief Deafult constructor
public: Grasp(int id_=0);
/// \brief Constructor
/// \param t_gripper_object_ Transform matrix from gripper to object frame
/// \param id Grasp identifier
public: Grasp(ignition::math::Matrix4d t_gripper_object_, int id_=0);
/// \brief Load set of grasps from file
/// \param file_name Input file name
/// \param robot Target robot name
/// \param object_name Target object name
/// \param grasps Set of grasps retrieved from file
public: static void loadFromYml(
const std::string & file_name,
const std::string & robot,
const std::string & object_name,
std::vector<Grasp> & grasps);
/// \brief Export set of grasps to file
/// \param file_name Output file name
/// \param robot Target robot name
/// \param object_name Target object name
/// \param grasps Set of grasps to export to file
public: static void writeToYml(
const std::string & file_name,
const std::string & robot,
const std::string & object_name,
const std::vector<Grasp> & grasps);
};
#endif
| 27.903226 | 78 | 0.666474 |
42b16212868354cd93abf75113e378f0054ddfd3 | 3,500 | cpp | C++ | encoderlame.cpp | napcode/appstream | f4e5452e2f3cc68899a3a1e7033435a56d8a7c79 | [
"MIT"
] | null | null | null | encoderlame.cpp | napcode/appstream | f4e5452e2f3cc68899a3a1e7033435a56d8a7c79 | [
"MIT"
] | null | null | null | encoderlame.cpp | napcode/appstream | f4e5452e2f3cc68899a3a1e7033435a56d8a7c79 | [
"MIT"
] | null | null | null | #include "encoderlame.h"
EncoderLame::EncoderLame(EncoderConfig c)
: Encoder(c)
{
}
EncoderLame::~EncoderLame()
{
if (_lgf) {
lame_close(_lgf);
_lgf = 0;
}
delete[] _buffer;
}
bool EncoderLame::init()
{
if (isInitialized())
return true;
int rc;
_lgf = lame_init();
/*
emit message(QString::number(_config.numInChannels));
emit message(QString::number(_config.sampleRateIn));
emit message(QString::number(_config.sampleRateOut));
emit message(QString::number(_config.bitRate));
*/
lame_set_num_channels(_lgf, _config.numInChannels);
lame_set_in_samplerate(_lgf, _config.sampleRateIn);
lame_set_out_samplerate(_lgf, _config.sampleRateOut);
if (_config.mode == EncoderConfig::CBR)
lame_set_brate(_lgf, _config.quality);
else if (_config.mode == EncoderConfig::VBR) {
lame_set_VBR(_lgf, vbr_mtrh);
lame_set_VBR_quality(_lgf, 10.0 - 10 * _config.quality);
}
if ((rc = lame_init_params(_lgf)) < 0) {
emit error("unable to init lame");
emit error("Channels " + QString::number(_config.numInChannels));
emit error("RateIn " + QString::number(_config.sampleRateIn));
emit error("RateOut " + QString::number(_config.sampleRateOut));
emit error("BitRate " + QString::number(_config.quality));
return false;
}
else {
_initialized = true;
emit message("Lame initialized");
emit message("Version: " + getVersion());
}
// default output buffer size. see lame.h
resize(DSP_BLOCKSIZE);
return true;
}
void EncoderLame::setup()
{
// nothing to do here
}
void EncoderLame::encode(sample_t* buffer, uint32_t samples)
{
int rc;
if (samples == 0 || !isInitialized())
return;
if (_allocedFrames < samples)
resize(samples);
if (_config.numInChannels == 2)
rc = lame_encode_buffer_interleaved_ieee_double(_lgf, buffer, samples / _config.numInChannels, reinterpret_cast<unsigned char*>(_buffer), _bufferSize);
else if (_config.numInChannels == 1)
rc = lame_encode_buffer_ieee_double(_lgf, buffer, buffer, samples, reinterpret_cast<unsigned char*>(_buffer), _bufferSize);
else {
emit error("Lame can't handle more than 2 channels.");
assert(0);
}
if (rc >= 0)
_bufferValid = rc;
else {
_bufferValid = 0;
handleRC(rc);
}
}
void EncoderLame::finalize()
{
}
void EncoderLame::handleRC(int rc) const
{
switch (rc) {
case -1:
emit error("Lame: out buffer to small");
break;
case -2:
emit error("Lame: unable to allocate memory");
break;
case -3:
emit error("Lame: init not called. Should never happen.");
break;
case -4:
emit error("Lame: psycho acoustic problem occurred");
break;
default:
emit error("Lame: unknown error occurred. ");
}
}
void EncoderLame::resize(uint32_t newSize)
{
delete[] _buffer;
_allocedFrames = newSize;
// default output buffer size. see lame.h
_bufferSize = 1.25 * _allocedFrames + 7200;
_buffer = new char[_bufferSize];
}
QString EncoderLame::getVersion() const
{
QString info;
if (!isInitialized()) {
emit error("lame is not initialized. Can't get version info.");
return info;
}
QString lame_version(get_lame_version());
return lame_version;
}
| 27.559055 | 159 | 0.624571 |
42b21efa257618345907a5b16591432d070d102a | 19,630 | cpp | C++ | apiwznm/PnlWznmCarDetail.cpp | mpsitech/wznm-WhizniumSBE | 4911d561b28392d485c46e98fb915168d82b3824 | [
"MIT"
] | 3 | 2020-09-20T16:24:48.000Z | 2021-12-01T19:44:51.000Z | apiwznm/PnlWznmCarDetail.cpp | mpsitech/wznm-WhizniumSBE | 4911d561b28392d485c46e98fb915168d82b3824 | [
"MIT"
] | null | null | null | apiwznm/PnlWznmCarDetail.cpp | mpsitech/wznm-WhizniumSBE | 4911d561b28392d485c46e98fb915168d82b3824 | [
"MIT"
] | null | null | null | /**
* \file PnlWznmCarDetail.cpp
* API code for job PnlWznmCarDetail (implementation)
* \copyright (C) 2016-2020 MPSI Technologies GmbH
* \author Alexander Wirthmueller (auto-generation)
* \date created: 5 Dec 2020
*/
// IP header --- ABOVE
#include "PnlWznmCarDetail.h"
using namespace std;
using namespace Sbecore;
using namespace Xmlio;
/******************************************************************************
class PnlWznmCarDetail::VecVDo
******************************************************************************/
uint PnlWznmCarDetail::VecVDo::getIx(
const string& sref
) {
string s = StrMod::lc(sref);
if (s == "butsaveclick") return BUTSAVECLICK;
if (s == "butjtieditclick") return BUTJTIEDITCLICK;
if (s == "butmdlviewclick") return BUTMDLVIEWCLICK;
if (s == "butreuviewclick") return BUTREUVIEWCLICK;
if (s == "butjobviewclick") return BUTJOBVIEWCLICK;
return(0);
};
string PnlWznmCarDetail::VecVDo::getSref(
const uint ix
) {
if (ix == BUTSAVECLICK) return("ButSaveClick");
if (ix == BUTJTIEDITCLICK) return("ButJtiEditClick");
if (ix == BUTMDLVIEWCLICK) return("ButMdlViewClick");
if (ix == BUTREUVIEWCLICK) return("ButReuViewClick");
if (ix == BUTJOBVIEWCLICK) return("ButJobViewClick");
return("");
};
/******************************************************************************
class PnlWznmCarDetail::ContIac
******************************************************************************/
PnlWznmCarDetail::ContIac::ContIac(
const uint numFPupJti
, const uint numFPupRet
, const string& TxfAvl
, const string& TxfAct
) :
Block()
{
this->numFPupJti = numFPupJti;
this->numFPupRet = numFPupRet;
this->TxfAvl = TxfAvl;
this->TxfAct = TxfAct;
mask = {NUMFPUPJTI, NUMFPUPRET, TXFAVL, TXFACT};
};
bool PnlWznmCarDetail::ContIac::readXML(
xmlXPathContext* docctx
, string basexpath
, bool addbasetag
) {
clear();
bool basefound;
if (addbasetag)
basefound = checkUclcXPaths(docctx, basexpath, basexpath, "ContIacWznmCarDetail");
else
basefound = checkXPath(docctx, basexpath);
string itemtag = "ContitemIacWznmCarDetail";
if (basefound) {
if (extractUintAttrUclc(docctx, basexpath, itemtag, "Ci", "sref", "numFPupJti", numFPupJti)) add(NUMFPUPJTI);
if (extractUintAttrUclc(docctx, basexpath, itemtag, "Ci", "sref", "numFPupRet", numFPupRet)) add(NUMFPUPRET);
if (extractStringAttrUclc(docctx, basexpath, itemtag, "Ci", "sref", "TxfAvl", TxfAvl)) add(TXFAVL);
if (extractStringAttrUclc(docctx, basexpath, itemtag, "Ci", "sref", "TxfAct", TxfAct)) add(TXFACT);
};
return basefound;
};
void PnlWznmCarDetail::ContIac::writeXML(
xmlTextWriter* wr
, string difftag
, bool shorttags
) {
if (difftag.length() == 0) difftag = "ContIacWznmCarDetail";
string itemtag;
if (shorttags) itemtag = "Ci";
else itemtag = "ContitemIacWznmCarDetail";
xmlTextWriterStartElement(wr, BAD_CAST difftag.c_str());
writeUintAttr(wr, itemtag, "sref", "numFPupJti", numFPupJti);
writeUintAttr(wr, itemtag, "sref", "numFPupRet", numFPupRet);
writeStringAttr(wr, itemtag, "sref", "TxfAvl", TxfAvl);
writeStringAttr(wr, itemtag, "sref", "TxfAct", TxfAct);
xmlTextWriterEndElement(wr);
};
set<uint> PnlWznmCarDetail::ContIac::comm(
const ContIac* comp
) {
set<uint> items;
if (numFPupJti == comp->numFPupJti) insert(items, NUMFPUPJTI);
if (numFPupRet == comp->numFPupRet) insert(items, NUMFPUPRET);
if (TxfAvl == comp->TxfAvl) insert(items, TXFAVL);
if (TxfAct == comp->TxfAct) insert(items, TXFACT);
return(items);
};
set<uint> PnlWznmCarDetail::ContIac::diff(
const ContIac* comp
) {
set<uint> commitems;
set<uint> diffitems;
commitems = comm(comp);
diffitems = {NUMFPUPJTI, NUMFPUPRET, TXFAVL, TXFACT};
for (auto it = commitems.begin(); it != commitems.end(); it++) diffitems.erase(*it);
return(diffitems);
};
/******************************************************************************
class PnlWznmCarDetail::ContInf
******************************************************************************/
PnlWznmCarDetail::ContInf::ContInf(
const string& TxtSrf
, const string& TxtTit
, const string& TxtMdl
, const string& TxtReu
, const string& TxtJob
) :
Block()
{
this->TxtSrf = TxtSrf;
this->TxtTit = TxtTit;
this->TxtMdl = TxtMdl;
this->TxtReu = TxtReu;
this->TxtJob = TxtJob;
mask = {TXTSRF, TXTTIT, TXTMDL, TXTREU, TXTJOB};
};
bool PnlWznmCarDetail::ContInf::readXML(
xmlXPathContext* docctx
, string basexpath
, bool addbasetag
) {
clear();
bool basefound;
if (addbasetag)
basefound = checkUclcXPaths(docctx, basexpath, basexpath, "ContInfWznmCarDetail");
else
basefound = checkXPath(docctx, basexpath);
string itemtag = "ContitemInfWznmCarDetail";
if (basefound) {
if (extractStringAttrUclc(docctx, basexpath, itemtag, "Ci", "sref", "TxtSrf", TxtSrf)) add(TXTSRF);
if (extractStringAttrUclc(docctx, basexpath, itemtag, "Ci", "sref", "TxtTit", TxtTit)) add(TXTTIT);
if (extractStringAttrUclc(docctx, basexpath, itemtag, "Ci", "sref", "TxtMdl", TxtMdl)) add(TXTMDL);
if (extractStringAttrUclc(docctx, basexpath, itemtag, "Ci", "sref", "TxtReu", TxtReu)) add(TXTREU);
if (extractStringAttrUclc(docctx, basexpath, itemtag, "Ci", "sref", "TxtJob", TxtJob)) add(TXTJOB);
};
return basefound;
};
set<uint> PnlWznmCarDetail::ContInf::comm(
const ContInf* comp
) {
set<uint> items;
if (TxtSrf == comp->TxtSrf) insert(items, TXTSRF);
if (TxtTit == comp->TxtTit) insert(items, TXTTIT);
if (TxtMdl == comp->TxtMdl) insert(items, TXTMDL);
if (TxtReu == comp->TxtReu) insert(items, TXTREU);
if (TxtJob == comp->TxtJob) insert(items, TXTJOB);
return(items);
};
set<uint> PnlWznmCarDetail::ContInf::diff(
const ContInf* comp
) {
set<uint> commitems;
set<uint> diffitems;
commitems = comm(comp);
diffitems = {TXTSRF, TXTTIT, TXTMDL, TXTREU, TXTJOB};
for (auto it = commitems.begin(); it != commitems.end(); it++) diffitems.erase(*it);
return(diffitems);
};
/******************************************************************************
class PnlWznmCarDetail::StatApp
******************************************************************************/
PnlWznmCarDetail::StatApp::StatApp(
const uint ixWznmVExpstate
) :
Block()
{
this->ixWznmVExpstate = ixWznmVExpstate;
mask = {IXWZNMVEXPSTATE};
};
bool PnlWznmCarDetail::StatApp::readXML(
xmlXPathContext* docctx
, string basexpath
, bool addbasetag
) {
clear();
string srefIxWznmVExpstate;
bool basefound;
if (addbasetag)
basefound = checkUclcXPaths(docctx, basexpath, basexpath, "StatAppWznmCarDetail");
else
basefound = checkXPath(docctx, basexpath);
string itemtag = "StatitemAppWznmCarDetail";
if (basefound) {
if (extractStringAttrUclc(docctx, basexpath, itemtag, "Si", "sref", "srefIxWznmVExpstate", srefIxWznmVExpstate)) {
ixWznmVExpstate = VecWznmVExpstate::getIx(srefIxWznmVExpstate);
add(IXWZNMVEXPSTATE);
};
};
return basefound;
};
set<uint> PnlWznmCarDetail::StatApp::comm(
const StatApp* comp
) {
set<uint> items;
if (ixWznmVExpstate == comp->ixWznmVExpstate) insert(items, IXWZNMVEXPSTATE);
return(items);
};
set<uint> PnlWznmCarDetail::StatApp::diff(
const StatApp* comp
) {
set<uint> commitems;
set<uint> diffitems;
commitems = comm(comp);
diffitems = {IXWZNMVEXPSTATE};
for (auto it = commitems.begin(); it != commitems.end(); it++) diffitems.erase(*it);
return(diffitems);
};
/******************************************************************************
class PnlWznmCarDetail::StatShr
******************************************************************************/
PnlWznmCarDetail::StatShr::StatShr(
const bool ButSaveAvail
, const bool ButSaveActive
, const bool TxtSrfActive
, const bool PupJtiActive
, const bool ButJtiEditAvail
, const bool TxtTitActive
, const bool TxtMdlActive
, const bool ButMdlViewAvail
, const bool ButMdlViewActive
, const bool TxtReuActive
, const bool ButReuViewAvail
, const bool ButReuViewActive
, const bool TxtJobActive
, const bool ButJobViewAvail
, const bool ButJobViewActive
, const bool TxfAvlActive
, const bool TxfActActive
) :
Block()
{
this->ButSaveAvail = ButSaveAvail;
this->ButSaveActive = ButSaveActive;
this->TxtSrfActive = TxtSrfActive;
this->PupJtiActive = PupJtiActive;
this->ButJtiEditAvail = ButJtiEditAvail;
this->TxtTitActive = TxtTitActive;
this->TxtMdlActive = TxtMdlActive;
this->ButMdlViewAvail = ButMdlViewAvail;
this->ButMdlViewActive = ButMdlViewActive;
this->TxtReuActive = TxtReuActive;
this->ButReuViewAvail = ButReuViewAvail;
this->ButReuViewActive = ButReuViewActive;
this->TxtJobActive = TxtJobActive;
this->ButJobViewAvail = ButJobViewAvail;
this->ButJobViewActive = ButJobViewActive;
this->TxfAvlActive = TxfAvlActive;
this->TxfActActive = TxfActActive;
mask = {BUTSAVEAVAIL, BUTSAVEACTIVE, TXTSRFACTIVE, PUPJTIACTIVE, BUTJTIEDITAVAIL, TXTTITACTIVE, TXTMDLACTIVE, BUTMDLVIEWAVAIL, BUTMDLVIEWACTIVE, TXTREUACTIVE, BUTREUVIEWAVAIL, BUTREUVIEWACTIVE, TXTJOBACTIVE, BUTJOBVIEWAVAIL, BUTJOBVIEWACTIVE, TXFAVLACTIVE, TXFACTACTIVE};
};
bool PnlWznmCarDetail::StatShr::readXML(
xmlXPathContext* docctx
, string basexpath
, bool addbasetag
) {
clear();
bool basefound;
if (addbasetag)
basefound = checkUclcXPaths(docctx, basexpath, basexpath, "StatShrWznmCarDetail");
else
basefound = checkXPath(docctx, basexpath);
string itemtag = "StatitemShrWznmCarDetail";
if (basefound) {
if (extractBoolAttrUclc(docctx, basexpath, itemtag, "Si", "sref", "ButSaveAvail", ButSaveAvail)) add(BUTSAVEAVAIL);
if (extractBoolAttrUclc(docctx, basexpath, itemtag, "Si", "sref", "ButSaveActive", ButSaveActive)) add(BUTSAVEACTIVE);
if (extractBoolAttrUclc(docctx, basexpath, itemtag, "Si", "sref", "TxtSrfActive", TxtSrfActive)) add(TXTSRFACTIVE);
if (extractBoolAttrUclc(docctx, basexpath, itemtag, "Si", "sref", "PupJtiActive", PupJtiActive)) add(PUPJTIACTIVE);
if (extractBoolAttrUclc(docctx, basexpath, itemtag, "Si", "sref", "ButJtiEditAvail", ButJtiEditAvail)) add(BUTJTIEDITAVAIL);
if (extractBoolAttrUclc(docctx, basexpath, itemtag, "Si", "sref", "TxtTitActive", TxtTitActive)) add(TXTTITACTIVE);
if (extractBoolAttrUclc(docctx, basexpath, itemtag, "Si", "sref", "TxtMdlActive", TxtMdlActive)) add(TXTMDLACTIVE);
if (extractBoolAttrUclc(docctx, basexpath, itemtag, "Si", "sref", "ButMdlViewAvail", ButMdlViewAvail)) add(BUTMDLVIEWAVAIL);
if (extractBoolAttrUclc(docctx, basexpath, itemtag, "Si", "sref", "ButMdlViewActive", ButMdlViewActive)) add(BUTMDLVIEWACTIVE);
if (extractBoolAttrUclc(docctx, basexpath, itemtag, "Si", "sref", "TxtReuActive", TxtReuActive)) add(TXTREUACTIVE);
if (extractBoolAttrUclc(docctx, basexpath, itemtag, "Si", "sref", "ButReuViewAvail", ButReuViewAvail)) add(BUTREUVIEWAVAIL);
if (extractBoolAttrUclc(docctx, basexpath, itemtag, "Si", "sref", "ButReuViewActive", ButReuViewActive)) add(BUTREUVIEWACTIVE);
if (extractBoolAttrUclc(docctx, basexpath, itemtag, "Si", "sref", "TxtJobActive", TxtJobActive)) add(TXTJOBACTIVE);
if (extractBoolAttrUclc(docctx, basexpath, itemtag, "Si", "sref", "ButJobViewAvail", ButJobViewAvail)) add(BUTJOBVIEWAVAIL);
if (extractBoolAttrUclc(docctx, basexpath, itemtag, "Si", "sref", "ButJobViewActive", ButJobViewActive)) add(BUTJOBVIEWACTIVE);
if (extractBoolAttrUclc(docctx, basexpath, itemtag, "Si", "sref", "TxfAvlActive", TxfAvlActive)) add(TXFAVLACTIVE);
if (extractBoolAttrUclc(docctx, basexpath, itemtag, "Si", "sref", "TxfActActive", TxfActActive)) add(TXFACTACTIVE);
};
return basefound;
};
set<uint> PnlWznmCarDetail::StatShr::comm(
const StatShr* comp
) {
set<uint> items;
if (ButSaveAvail == comp->ButSaveAvail) insert(items, BUTSAVEAVAIL);
if (ButSaveActive == comp->ButSaveActive) insert(items, BUTSAVEACTIVE);
if (TxtSrfActive == comp->TxtSrfActive) insert(items, TXTSRFACTIVE);
if (PupJtiActive == comp->PupJtiActive) insert(items, PUPJTIACTIVE);
if (ButJtiEditAvail == comp->ButJtiEditAvail) insert(items, BUTJTIEDITAVAIL);
if (TxtTitActive == comp->TxtTitActive) insert(items, TXTTITACTIVE);
if (TxtMdlActive == comp->TxtMdlActive) insert(items, TXTMDLACTIVE);
if (ButMdlViewAvail == comp->ButMdlViewAvail) insert(items, BUTMDLVIEWAVAIL);
if (ButMdlViewActive == comp->ButMdlViewActive) insert(items, BUTMDLVIEWACTIVE);
if (TxtReuActive == comp->TxtReuActive) insert(items, TXTREUACTIVE);
if (ButReuViewAvail == comp->ButReuViewAvail) insert(items, BUTREUVIEWAVAIL);
if (ButReuViewActive == comp->ButReuViewActive) insert(items, BUTREUVIEWACTIVE);
if (TxtJobActive == comp->TxtJobActive) insert(items, TXTJOBACTIVE);
if (ButJobViewAvail == comp->ButJobViewAvail) insert(items, BUTJOBVIEWAVAIL);
if (ButJobViewActive == comp->ButJobViewActive) insert(items, BUTJOBVIEWACTIVE);
if (TxfAvlActive == comp->TxfAvlActive) insert(items, TXFAVLACTIVE);
if (TxfActActive == comp->TxfActActive) insert(items, TXFACTACTIVE);
return(items);
};
set<uint> PnlWznmCarDetail::StatShr::diff(
const StatShr* comp
) {
set<uint> commitems;
set<uint> diffitems;
commitems = comm(comp);
diffitems = {BUTSAVEAVAIL, BUTSAVEACTIVE, TXTSRFACTIVE, PUPJTIACTIVE, BUTJTIEDITAVAIL, TXTTITACTIVE, TXTMDLACTIVE, BUTMDLVIEWAVAIL, BUTMDLVIEWACTIVE, TXTREUACTIVE, BUTREUVIEWAVAIL, BUTREUVIEWACTIVE, TXTJOBACTIVE, BUTJOBVIEWAVAIL, BUTJOBVIEWACTIVE, TXFAVLACTIVE, TXFACTACTIVE};
for (auto it = commitems.begin(); it != commitems.end(); it++) diffitems.erase(*it);
return(diffitems);
};
/******************************************************************************
class PnlWznmCarDetail::Tag
******************************************************************************/
PnlWznmCarDetail::Tag::Tag(
const string& Cpt
, const string& CptSrf
, const string& CptTit
, const string& CptMdl
, const string& CptReu
, const string& CptJob
, const string& CptAvl
, const string& CptAct
) :
Block()
{
this->Cpt = Cpt;
this->CptSrf = CptSrf;
this->CptTit = CptTit;
this->CptMdl = CptMdl;
this->CptReu = CptReu;
this->CptJob = CptJob;
this->CptAvl = CptAvl;
this->CptAct = CptAct;
mask = {CPT, CPTSRF, CPTTIT, CPTMDL, CPTREU, CPTJOB, CPTAVL, CPTACT};
};
bool PnlWznmCarDetail::Tag::readXML(
xmlXPathContext* docctx
, string basexpath
, bool addbasetag
) {
clear();
bool basefound;
if (addbasetag)
basefound = checkUclcXPaths(docctx, basexpath, basexpath, "TagWznmCarDetail");
else
basefound = checkXPath(docctx, basexpath);
string itemtag = "TagitemWznmCarDetail";
if (basefound) {
if (extractStringAttrUclc(docctx, basexpath, itemtag, "Ti", "sref", "Cpt", Cpt)) add(CPT);
if (extractStringAttrUclc(docctx, basexpath, itemtag, "Ti", "sref", "CptSrf", CptSrf)) add(CPTSRF);
if (extractStringAttrUclc(docctx, basexpath, itemtag, "Ti", "sref", "CptTit", CptTit)) add(CPTTIT);
if (extractStringAttrUclc(docctx, basexpath, itemtag, "Ti", "sref", "CptMdl", CptMdl)) add(CPTMDL);
if (extractStringAttrUclc(docctx, basexpath, itemtag, "Ti", "sref", "CptReu", CptReu)) add(CPTREU);
if (extractStringAttrUclc(docctx, basexpath, itemtag, "Ti", "sref", "CptJob", CptJob)) add(CPTJOB);
if (extractStringAttrUclc(docctx, basexpath, itemtag, "Ti", "sref", "CptAvl", CptAvl)) add(CPTAVL);
if (extractStringAttrUclc(docctx, basexpath, itemtag, "Ti", "sref", "CptAct", CptAct)) add(CPTACT);
};
return basefound;
};
/******************************************************************************
class PnlWznmCarDetail::DpchAppData
******************************************************************************/
PnlWznmCarDetail::DpchAppData::DpchAppData(
const string& scrJref
, ContIac* contiac
, const set<uint>& mask
) :
DpchAppWznm(VecWznmVDpch::DPCHAPPWZNMCARDETAILDATA, scrJref)
{
if (find(mask, ALL)) this->mask = {SCRJREF, CONTIAC};
else this->mask = mask;
if (find(this->mask, CONTIAC) && contiac) this->contiac = *contiac;
};
string PnlWznmCarDetail::DpchAppData::getSrefsMask() {
vector<string> ss;
string srefs;
if (has(SCRJREF)) ss.push_back("scrJref");
if (has(CONTIAC)) ss.push_back("contiac");
StrMod::vectorToString(ss, srefs);
return(srefs);
};
void PnlWznmCarDetail::DpchAppData::writeXML(
xmlTextWriter* wr
) {
xmlTextWriterStartElement(wr, BAD_CAST "DpchAppWznmCarDetailData");
xmlTextWriterWriteAttribute(wr, BAD_CAST "xmlns", BAD_CAST "http://www.mpsitech.com/wznm");
if (has(SCRJREF)) writeString(wr, "scrJref", scrJref);
if (has(CONTIAC)) contiac.writeXML(wr);
xmlTextWriterEndElement(wr);
};
/******************************************************************************
class PnlWznmCarDetail::DpchAppDo
******************************************************************************/
PnlWznmCarDetail::DpchAppDo::DpchAppDo(
const string& scrJref
, const uint ixVDo
, const set<uint>& mask
) :
DpchAppWznm(VecWznmVDpch::DPCHAPPWZNMCARDETAILDO, scrJref)
{
if (find(mask, ALL)) this->mask = {SCRJREF, IXVDO};
else this->mask = mask;
this->ixVDo = ixVDo;
};
string PnlWznmCarDetail::DpchAppDo::getSrefsMask() {
vector<string> ss;
string srefs;
if (has(SCRJREF)) ss.push_back("scrJref");
if (has(IXVDO)) ss.push_back("ixVDo");
StrMod::vectorToString(ss, srefs);
return(srefs);
};
void PnlWznmCarDetail::DpchAppDo::writeXML(
xmlTextWriter* wr
) {
xmlTextWriterStartElement(wr, BAD_CAST "DpchAppWznmCarDetailDo");
xmlTextWriterWriteAttribute(wr, BAD_CAST "xmlns", BAD_CAST "http://www.mpsitech.com/wznm");
if (has(SCRJREF)) writeString(wr, "scrJref", scrJref);
if (has(IXVDO)) writeString(wr, "srefIxVDo", VecVDo::getSref(ixVDo));
xmlTextWriterEndElement(wr);
};
/******************************************************************************
class PnlWznmCarDetail::DpchEngData
******************************************************************************/
PnlWznmCarDetail::DpchEngData::DpchEngData() :
DpchEngWznm(VecWznmVDpch::DPCHENGWZNMCARDETAILDATA)
{
feedFPupJti.tag = "FeedFPupJti";
feedFPupRet.tag = "FeedFPupRet";
};
string PnlWznmCarDetail::DpchEngData::getSrefsMask() {
vector<string> ss;
string srefs;
if (has(SCRJREF)) ss.push_back("scrJref");
if (has(CONTIAC)) ss.push_back("contiac");
if (has(CONTINF)) ss.push_back("continf");
if (has(FEEDFPUPJTI)) ss.push_back("feedFPupJti");
if (has(FEEDFPUPRET)) ss.push_back("feedFPupRet");
if (has(STATAPP)) ss.push_back("statapp");
if (has(STATSHR)) ss.push_back("statshr");
if (has(TAG)) ss.push_back("tag");
StrMod::vectorToString(ss, srefs);
return(srefs);
};
void PnlWznmCarDetail::DpchEngData::readXML(
xmlXPathContext* docctx
, string basexpath
, bool addbasetag
) {
clear();
bool basefound;
if (addbasetag)
basefound = checkUclcXPaths(docctx, basexpath, basexpath, "DpchEngWznmCarDetailData");
else
basefound = checkXPath(docctx, basexpath);
if (basefound) {
if (extractStringUclc(docctx, basexpath, "scrJref", "", scrJref)) add(SCRJREF);
if (contiac.readXML(docctx, basexpath, true)) add(CONTIAC);
if (continf.readXML(docctx, basexpath, true)) add(CONTINF);
if (feedFPupJti.readXML(docctx, basexpath, true)) add(FEEDFPUPJTI);
if (feedFPupRet.readXML(docctx, basexpath, true)) add(FEEDFPUPRET);
if (statapp.readXML(docctx, basexpath, true)) add(STATAPP);
if (statshr.readXML(docctx, basexpath, true)) add(STATSHR);
if (tag.readXML(docctx, basexpath, true)) add(TAG);
} else {
contiac = ContIac();
continf = ContInf();
feedFPupJti.clear();
feedFPupRet.clear();
statapp = StatApp();
statshr = StatShr();
tag = Tag();
};
};
| 32.5 | 277 | 0.670301 |
42b2b194989dff2b2dd44420dd2d5941c206551b | 3,702 | hpp | C++ | src/integration/IntegrationNSphere.hpp | FrancoisGaits/utk | 8c408dd79635f98c46ed075c098f15e23972aad0 | [
"BSD-2-Clause-FreeBSD"
] | 44 | 2018-01-09T19:56:29.000Z | 2022-03-03T06:38:54.000Z | src/integration/IntegrationNSphere.hpp | FrancoisGaits/utk | 8c408dd79635f98c46ed075c098f15e23972aad0 | [
"BSD-2-Clause-FreeBSD"
] | 16 | 2018-01-29T18:01:42.000Z | 2022-03-31T07:01:09.000Z | src/integration/IntegrationNSphere.hpp | FrancoisGaits/utk | 8c408dd79635f98c46ed075c098f15e23972aad0 | [
"BSD-2-Clause-FreeBSD"
] | 12 | 2018-03-14T00:24:14.000Z | 2022-03-03T06:40:07.000Z | /*
* Hélène Perrier helene.perrier@liris.cnrs.fr
* and David Coeurjolly david.coeurjolly@liris.cnrs.fr
*
* Copyright (c) 2018 CNRS Université de Lyon
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice, this
* list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR
* ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
* The views and conclusions contained in the software and documentation are those
* of the authors and should not be interpreted as representing official policies,
* either expressed or implied, of the UTK project.
*/
#ifndef _UTK_INTEGRATION_DISK_ND_
#define _UTK_INTEGRATION_DISK_ND_
#include "../io/messageStream.hpp"
#include "../pointsets/Pointset.hpp"
#include <cmath>
#include <array>
namespace utk
{
class IntegrationNSphere
{
public:
IntegrationNSphere() { m_radius = 0.25; }
void setRadius(double arg_radius) { m_radius = arg_radius; }
template<unsigned int D, typename T, typename P>
bool compute(const Pointset<D, T, P>& arg_pointset, double& integration_value, double& analytic_value)
{
if(m_radius <= 0 && m_radius >= 0.5)
{
ERROR("IntegrationNSphere::compute radius must be in ]0, 0.5[");
return false;
}
std::array<double, D> nd_domain_extent;
for(unsigned int d=0; d<D; d++)
{
nd_domain_extent[d] = (arg_pointset.domain.pMax.pos() - arg_pointset.domain.pMin.pos())[d];
if(nd_domain_extent[d] == 0)
{
WARNING("IntegrationNSphere::compute domain extent is 0 on at least one dimension, scaling might fail");
}
if(nd_domain_extent[d] < 0)
{
ERROR("IntegrationNSphere::compute domain extent is negative on at least one dimension");
return false;
}
}
analytic_value = analyticIntegrand(D);
integration_value = 0;
for(uint i=0; i<arg_pointset.size(); i++)
{
Point<D, double> pt;
for(unsigned int d=0; d<D; d++)
pt.pos()[d] = -0.5 + (arg_pointset[i].pos() - arg_pointset.domain.pMin.pos())[d] / nd_domain_extent[d];
integration_value += sampleIntegrand<D>(pt);
}
integration_value /= (double)arg_pointset.size();
return true;
}
double analyticIntegrand(uint dim)
{
double num = pow(M_PI, (double)dim/2.0);
double denom = tgamma(((double)dim/2.0) + 1);
return (num/denom)*pow(m_radius, dim);
}
template<uint D>
double sampleIntegrand(Point<D, double>& pt)
{
double l = pt.pos().length();
if(l < m_radius)
return 1;
return 0;
}
double m_radius;
};
}//end namespace
#endif
| 32.473684 | 105 | 0.700702 |
42b5735b3471a7446cdf2188bd48234ed6b3765c | 3,014 | hpp | C++ | libbitcoin/include/bitcoin/constants.hpp | mousewu/bcclient | 64ee1f6f8337103d40a4a0c3dfb73cabcd09a04c | [
"MIT"
] | 8 | 2019-05-31T01:37:08.000Z | 2021-10-19T05:52:45.000Z | libbitcoin/include/bitcoin/constants.hpp | mousewu/bcclient | 64ee1f6f8337103d40a4a0c3dfb73cabcd09a04c | [
"MIT"
] | 3 | 2017-12-18T17:27:09.000Z | 2018-01-15T16:50:05.000Z | libbitcoin/include/bitcoin/constants.hpp | mousewu/bcclient | 64ee1f6f8337103d40a4a0c3dfb73cabcd09a04c | [
"MIT"
] | 5 | 2018-01-09T15:05:55.000Z | 2020-12-17T13:27:25.000Z | /*
* Copyright (c) 2011-2013 libbitcoin developers (see AUTHORS)
*
* This file is part of libbitcoin.
*
* libbitcoin is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License with
* additional permissions to the one published by the Free Software
* Foundation, either version 3 of the License, or (at your option)
* any later version. For more information see LICENSE.
*
* 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/>.
*/
#ifndef LIBBITCOIN_CONSTANTS_HPP
#define LIBBITCOIN_CONSTANTS_HPP
#include <cstdint>
#include <bitcoin/utility/big_number.hpp>
namespace libbitcoin {
constexpr uint32_t protocol_version = 60000;
constexpr uint64_t block_reward = 50;
// 210000 ~ 4 years / 10 minutes
constexpr uint64_t reward_interval = 210000;
constexpr size_t coinbase_maturity = 100;
#ifdef ENABLE_TESTNET
constexpr uint32_t protocol_port = 18333;
#else
constexpr uint32_t protocol_port = 8333;
#endif
// Threshold for nLockTime: below this value it is
// interpreted as block number, otherwise as UNIX timestamp.
// Tue Nov 5 00:53:20 1985 UTC
constexpr uint32_t locktime_threshold = 500000000;
constexpr uint64_t max_money_recursive(uint64_t current)
{
return (current > 0) ?
current + max_money_recursive(current >> 1) : 0;
}
constexpr uint64_t coin_price(uint64_t value=1)
{
return value * 100000000;
}
constexpr uint64_t max_money()
{
return reward_interval * max_money_recursive(coin_price(block_reward));
}
const hash_digest null_hash{0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0};
const short_hash null_short_hash{0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0};
constexpr uint32_t max_bits = 0x1d00ffff;
big_number max_target();
uint32_t magic_value();
constexpr uint32_t max_index = std::numeric_limits<uint32_t>::max();
// Every two weeks we readjust target
constexpr uint64_t target_timespan = 14 * 24 * 60 * 60;
// Aim for blocks every 10 mins
constexpr uint64_t target_spacing = 10 * 60;
// Two weeks worth of blocks = readjust interval = 2016
constexpr uint64_t readjustment_interval = target_timespan / target_spacing;
#ifdef ENABLE_TESTNET
// Block 514 is the first block after Feb 15 2014.
// Testnet started bip16 before mainnet.
constexpr uint32_t bip16_switchover_timestamp = 1333238400;
constexpr uint32_t bip16_switchover_height = 514;
#else
// April 1 2012
constexpr uint32_t bip16_switchover_timestamp = 1333238400;
constexpr uint32_t bip16_switchover_height = 173805;
#endif
} // namespace libbitcoin
#endif
| 31.395833 | 76 | 0.736231 |
42b713a94aed7da16b1cf74cfd6e5e60937a2e40 | 5,781 | cc | C++ | tensorflow_io/core/azure/azfs/azfs_client.cc | pshiko/io | a1793e6b41ed7a8db572249aba15a8e513a348a5 | [
"Apache-2.0"
] | 1 | 2020-01-20T17:48:31.000Z | 2020-01-20T17:48:31.000Z | tensorflow_io/core/azure/azfs/azfs_client.cc | pshiko/io | a1793e6b41ed7a8db572249aba15a8e513a348a5 | [
"Apache-2.0"
] | null | null | null | tensorflow_io/core/azure/azfs/azfs_client.cc | pshiko/io | a1793e6b41ed7a8db572249aba15a8e513a348a5 | [
"Apache-2.0"
] | null | null | null | /* Copyright 2019 The TensorFlow 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 "tensorflow_io/core/azure/azfs/azfs_client.h"
#include "logging.h"
namespace tensorflow {
namespace io {
/// \brief Splits a Azure path to a account, container and object.
///
/// For example,
/// "az://account-name.blob.core.windows.net/container/path/to/file.txt" gets
/// split into "account-name", "container" and "path/to/file.txt".
Status ParseAzBlobPath(StringPiece fname, bool empty_object_ok,
std::string *account, std::string *container,
std::string *object) {
if (!account || !object) {
return errors::Internal("account and object cannot be null.");
}
StringPiece scheme, accountp, objectp;
io::ParseURI(fname, &scheme, &accountp, &objectp);
if (scheme != "az") {
return errors::InvalidArgument(
"Azure Blob Storage path doesn't start with 'az://': ", fname);
}
// Consume blob.core.windows.net if it exists
absl::ConsumeSuffix(&accountp, kAzBlobEndpoint);
if (accountp.empty() || accountp.compare(".") == 0) {
return errors::InvalidArgument(
"Azure Blob Storage path doesn't contain a account name: ", fname);
}
*account = std::string(accountp);
absl::ConsumePrefix(&objectp, "/");
auto pos = objectp.find('/');
if (pos == std::string::npos) {
*container = objectp.data();
*object = "";
} else {
*container = std::string(objectp.substr(0, pos));
*object = std::string(objectp.substr(pos + 1));
}
return Status::OK();
}
std::string errno_to_string() {
switch (errno) {
/* common errors */
case invalid_parameters:
return "invalid_parameters";
/* client level */
case client_init_fail:
return "client_init_fail";
case client_already_init:
return "client_already_init";
case client_not_init:
return "client_not_init";
/* container level */
case container_already_exists:
return "container_already_exists";
case container_not_exists:
return "container_not_exists";
case container_name_invalid:
return "container_name_invalid";
case container_create_fail:
return "container_create_fail";
case container_delete_fail:
return "container_delete_fail";
/* blob level */
case blob__already_exists:
return "blob__already_exists";
case blob_not_exists:
return "blob_not_exists";
case blob_name_invalid:
return "blob_name_invalid";
case blob_delete_fail:
return "blob_delete_fail";
case blob_list_fail:
return "blob_list_fail";
case blob_copy_fail:
return "blob_copy_fail";
case blob_no_content_range:
return "blob_no_content_range";
/* unknown error */
case unknown_error:
default:
return "unknown_error - " + std::to_string(errno);
}
}
std::shared_ptr<azure::storage_lite::storage_credential> get_credential(
const std::string &account) {
const auto key = std::getenv("TF_AZURE_STORAGE_KEY");
if (key != nullptr) {
return std::make_shared<azure::storage_lite::shared_key_credential>(account,
key);
} else {
return std::make_shared<azure::storage_lite::anonymous_credential>();
}
}
azure::storage_lite::blob_client_wrapper CreateAzBlobClientWrapper(
const std::string &account) {
azure::storage_lite::logger::set_logger(
[](azure::storage_lite::log_level level, const std::string &log_msg) {
switch (level) {
case azure::storage_lite::log_level::info:
_TF_LOG_INFO << log_msg;
break;
case azure::storage_lite::log_level::error:
case azure::storage_lite::log_level::critical:
_TF_LOG_ERROR << log_msg;
break;
case azure::storage_lite::log_level::warn:
_TF_LOG_WARNING << log_msg;
break;
case azure::storage_lite::log_level::trace:
case azure::storage_lite::log_level::debug:
default:
break;
}
});
const auto use_dev_account = std::getenv("TF_AZURE_USE_DEV_STORAGE");
if (use_dev_account != nullptr) {
auto storage_account =
azure::storage_lite::storage_account::development_storage_account();
auto blob_client =
std::make_shared<azure::storage_lite::blob_client>(storage_account, 10);
azure::storage_lite::blob_client_wrapper blob_client_wrapper(blob_client);
return blob_client_wrapper;
}
const auto use_http_env = std::getenv("TF_AZURE_STORAGE_USE_HTTP");
const auto use_https = use_http_env == nullptr;
const auto blob_endpoint =
std::string(std::getenv("TF_AZURE_STORAGE_BLOB_ENDPOINT") ?: "");
auto credentials = get_credential(account);
auto storage_account = std::make_shared<azure::storage_lite::storage_account>(
account, credentials, use_https, blob_endpoint);
auto blob_client =
std::make_shared<azure::storage_lite::blob_client>(storage_account, 10);
azure::storage_lite::blob_client_wrapper blob_client_wrapper(blob_client);
return blob_client_wrapper;
}
} // namespace io
} // namespace tensorflow
| 34.207101 | 80 | 0.669953 |
42b976415bed9557543a9e1dd17c9c84c33fe02a | 593 | cpp | C++ | 03/exam03.cpp | Sadik326-ctrl/computer_programming | cbae264ffa04fc487008fa6a0a32e0a1a316e01e | [
"MIT"
] | null | null | null | 03/exam03.cpp | Sadik326-ctrl/computer_programming | cbae264ffa04fc487008fa6a0a32e0a1a316e01e | [
"MIT"
] | null | null | null | 03/exam03.cpp | Sadik326-ctrl/computer_programming | cbae264ffa04fc487008fa6a0a32e0a1a316e01e | [
"MIT"
] | null | null | null | // Demonstration of compound assignments
#include <iostream>
#include <iomanip>
using namespace std;
int main()
{
float x, y;
cout << "\n Please enter a starting value:
cin >> x;
";
cout << "\n Please enter the increment value: ";
cin >> y;
x += y;
cout << "\n And now multiplication! ";
cout << "\n Please enter a factor: ";
cin >> y;
x *= y;
cout << "\n Finally division.";
cout << "\n Please supply a divisor: ";
cin >> y;
x /= y;
cout << "\n And this is "
<< "your current lucky number: "
// without digits after
// the decimal point:
<< fixed << setprecision(0)
<< x << endl;
return 0;
}
| 19.766667 | 48 | 0.625632 |
42b9e0ae70299b5c0c42b2aa5b291bf768be26c4 | 485 | cpp | C++ | Part_Fourteen/BasePtrDerivedObj.cpp | ayushpareek179/CPP-course | b2b8b8d2dd06cd772e3c9838abd5b841237bb306 | [
"MIT"
] | null | null | null | Part_Fourteen/BasePtrDerivedObj.cpp | ayushpareek179/CPP-course | b2b8b8d2dd06cd772e3c9838abd5b841237bb306 | [
"MIT"
] | null | null | null | Part_Fourteen/BasePtrDerivedObj.cpp | ayushpareek179/CPP-course | b2b8b8d2dd06cd772e3c9838abd5b841237bb306 | [
"MIT"
] | null | null | null | //To depict pointer to a derived class objeof base class type
#include <iostream>
using namespace std;
class parent
{
public:
void func()
{
cout<<"Base's function\n";
}
};
class child:public parent
{
public:
void meth()
{
cout<<"Derived's function\n";
}
};
int main()
{
child c;
//parent* pa = &c; - Works as well
parent* p = new child();
p->func();
//p->meth() - doesn't work
//c.meth(); - works
return 0;
} | 16.724138 | 61 | 0.548454 |
42bbfc1363eb5582eaffb6b99a570e8fb7d41497 | 1,641 | hpp | C++ | release/include/mlclient/mlclient.hpp | adamfowleruk/mlcplusplus | bd8b47b8e92c7f66a22ecfe98353f3e8a621802d | [
"Apache-2.0"
] | 4 | 2016-04-21T06:27:40.000Z | 2017-01-20T12:10:54.000Z | release/include/mlclient/mlclient.hpp | marklogic/mlcplusplus | bd8b47b8e92c7f66a22ecfe98353f3e8a621802d | [
"Apache-2.0"
] | 239 | 2015-11-26T23:10:33.000Z | 2017-01-03T23:48:23.000Z | release/include/mlclient/mlclient.hpp | marklogic-community/mlcplusplus | bd8b47b8e92c7f66a22ecfe98353f3e8a621802d | [
"Apache-2.0"
] | 3 | 2017-11-01T15:52:51.000Z | 2021-12-02T05:22:49.000Z | /*
* Copyright (c) MarkLogic Corporation. All rights reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#pragma once
#ifndef MLCLIENT_HPP
#define MLCLIENT_HPP
#include <memory>
#include <vector>
#include <map>
//#include "mlclient/ext/easylogging++.h"
#ifdef _WIN32
#ifdef MLCLIENT_EXPORTS
#define MLCLIENT_API __declspec(dllexport)
#else
#define MLCLIENT_API __declspec(dllimport)
#endif
#include <ostream>
#include <sstream>
#include <string>
/*
namespace mlclient {
MLCLIENT_API el::base::type::StoragePointer sharedLoggingRepository();
}
*/
#else
#define MLCLIENT_API
#endif
namespace mlclient {
typedef std::map<std::string,std::string> StringMap;
typedef std::vector<std::string> SearchSuggestionSet;
typedef std::vector<std::string> StringList;
// note: this implementation does not disable this overload for array types
template<typename T, typename... Args>
std::unique_ptr<T> make_unique(Args&&... args)
{
return std::unique_ptr<T>(new T(std::forward<Args>(args)...));
}
} // end namespace mlclient
#endif /* defined(MLCLIENT_HPP) */
| 26.047619 | 78 | 0.718464 |
42bf6c136b9f6b914ccb85044ba0132dc453ba41 | 470 | cpp | C++ | bzoj/1261.cpp | swwind/code | 25c4c5ca2f8578ba792b44cbdf44286d39dfb7e0 | [
"WTFPL"
] | 3 | 2017-09-17T09:12:50.000Z | 2018-04-06T01:18:17.000Z | bzoj/1261.cpp | swwind/code | 25c4c5ca2f8578ba792b44cbdf44286d39dfb7e0 | [
"WTFPL"
] | null | null | null | bzoj/1261.cpp | swwind/code | 25c4c5ca2f8578ba792b44cbdf44286d39dfb7e0 | [
"WTFPL"
] | null | null | null | #include <bits/stdc++.h>
#define ll long long
using namespace std;
int a[5050], len, n;
int mul(int val){
for(int i = 1; i <= len; i++)
a[i]*=val;
for(int i = 1; i <= len; i++){
a[i+1]+=a[i]/10;
a[i]%=10;
}
if(a[len+1])len++;
}
int main(){
scanf("%d", &n);
a[len=1]=1;
while(n > 4) mul(3), n-=3; mul(n);
printf("%d\n", len);
if(len > 100) for(int i = 0; i < 100; i++) putchar(a[len-i]+'0');
else for(int i = len; i; i--) putchar(a[i]+'0');
return 0;
}
| 19.583333 | 66 | 0.510638 |
42c7ae69afc9abae4f5cbfc1f4417f023535f44d | 392 | cpp | C++ | main.cpp | Ibsardar/OpenGLDemo | 8801f5b670d47ebae116902d46e645108c7a0a63 | [
"MIT"
] | null | null | null | main.cpp | Ibsardar/OpenGLDemo | 8801f5b670d47ebae116902d46e645108c7a0a63 | [
"MIT"
] | null | null | null | main.cpp | Ibsardar/OpenGLDemo | 8801f5b670d47ebae116902d46e645108c7a0a63 | [
"MIT"
] | null | null | null | #include <iostream>
#include "Display.h"
#include <GL/glew.h>
int main(char argc, char** argv) {
Display display(800, 600, "This is My World!");
// game loop
while (!display.isClosed()) {
// fill the display with a color
glClearColor(0.0f, 0.15f, 0.3f, 1.0f);
// clear the display
glClear(GL_COLOR_BUFFER_BIT);
// update the display
display.update();
}
return 0;
} | 15.68 | 48 | 0.647959 |
42ca18dbe7063fba14cb1e1702ba8e4dbc5225ac | 9,112 | cc | C++ | tensorflow/lite/experimental/micro/examples/micro_speech/micro_features/filterbank_util.cc | uve/tensorflow | e08079463bf43e5963acc41da1f57e95603f8080 | [
"Apache-2.0"
] | null | null | null | tensorflow/lite/experimental/micro/examples/micro_speech/micro_features/filterbank_util.cc | uve/tensorflow | e08079463bf43e5963acc41da1f57e95603f8080 | [
"Apache-2.0"
] | null | null | null | tensorflow/lite/experimental/micro/examples/micro_speech/micro_features/filterbank_util.cc | uve/tensorflow | e08079463bf43e5963acc41da1f57e95603f8080 | [
"Apache-2.0"
] | null | null | null | /* Copyright 2018 The TensorFlow 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 "tensorflow/lite/experimental/micro/examples/micro_speech/micro_features/filterbank_util.h"
#include <assert.h>
#include <math.h>
#include "tensorflow/lite/experimental/micro/examples/micro_speech/micro_features/static_alloc.h"
#define kFilterbankIndexAlignment 4
#define kFilterbankChannelBlockSize 4
void FilterbankFillConfigWithDefaults(struct FilterbankConfig* config) {
config->num_channels = 32;
config->lower_band_limit = 125.0f;
config->upper_band_limit = 7500.0f;
config->output_scale_shift = 7;
}
static float FreqToMel(float freq) {
return 1127.0 * log(1.0 + (freq / 700.0));
}
static void CalculateCenterFrequencies(const int num_channels,
const float lower_frequency_limit,
const float upper_frequency_limit,
float* center_frequencies) {
assert(lower_frequency_limit >= 0.0f);
assert(upper_frequency_limit > lower_frequency_limit);
const float mel_low = FreqToMel(lower_frequency_limit);
const float mel_hi = FreqToMel(upper_frequency_limit);
const float mel_span = mel_hi - mel_low;
const float mel_spacing = mel_span / (static_cast<float>(num_channels));
int i;
for (i = 0; i < num_channels; ++i) {
center_frequencies[i] = mel_low + (mel_spacing * (i + 1));
}
}
static void QuantizeFilterbankWeights(const float float_weight, int16_t* weight,
int16_t* unweight) {
*weight = floor(float_weight * (1 << kFilterbankBits) + 0.5);
*unweight = floor((1.0 - float_weight) * (1 << kFilterbankBits) + 0.5);
}
int FilterbankPopulateState(tflite::ErrorReporter* error_reporter,
const struct FilterbankConfig* config,
struct FilterbankState* state, int sample_rate,
int spectrum_size) {
state->num_channels = config->num_channels;
const int num_channels_plus_1 = config->num_channels + 1;
// How should we align things to index counts given the byte alignment?
const int index_alignment =
(kFilterbankIndexAlignment < sizeof(int16_t)
? 1
: kFilterbankIndexAlignment / sizeof(int16_t));
STATIC_ALLOC_ENSURE_ARRAY_SIZE(
state->channel_frequency_starts,
(num_channels_plus_1 * sizeof(*state->channel_frequency_starts)));
STATIC_ALLOC_ENSURE_ARRAY_SIZE(
state->channel_weight_starts,
(num_channels_plus_1 * sizeof(*state->channel_weight_starts)));
STATIC_ALLOC_ENSURE_ARRAY_SIZE(
state->channel_widths,
(num_channels_plus_1 * sizeof(*state->channel_widths)));
STATIC_ALLOC_ENSURE_ARRAY_SIZE(state->work,
(num_channels_plus_1 * sizeof(*state->work)));
float center_mel_freqs[kFeatureSliceSize + 1];
STATIC_ALLOC_ENSURE_ARRAY_SIZE(
center_mel_freqs, (num_channels_plus_1 * sizeof(*center_mel_freqs)));
int16_t actual_channel_starts[kFeatureSliceSize + 1];
STATIC_ALLOC_ENSURE_ARRAY_SIZE(
actual_channel_starts,
(num_channels_plus_1 * sizeof(*actual_channel_starts)));
int16_t actual_channel_widths[kFeatureSliceSize + 1];
STATIC_ALLOC_ENSURE_ARRAY_SIZE(
actual_channel_widths,
(num_channels_plus_1 * sizeof(*actual_channel_widths)));
CalculateCenterFrequencies(num_channels_plus_1, config->lower_band_limit,
config->upper_band_limit, center_mel_freqs);
// Always exclude DC.
const float hz_per_sbin =
0.5 * sample_rate / (static_cast<float>(spectrum_size) - 1);
state->start_index = 1.5 + config->lower_band_limit / hz_per_sbin;
state->end_index = 0; // Initialized to zero here, but actually set below.
// For each channel, we need to figure out what frequencies belong to it, and
// how much padding we need to add so that we can efficiently multiply the
// weights and unweights for accumulation. To simplify the multiplication
// logic, all channels will have some multiplication to do (even if there are
// no frequencies that accumulate to that channel) - they will be directed to
// a set of zero weights.
int chan_freq_index_start = state->start_index;
int weight_index_start = 0;
int needs_zeros = 0;
int chan;
for (chan = 0; chan < num_channels_plus_1; ++chan) {
// Keep jumping frequencies until we overshoot the bound on this channel.
int freq_index = chan_freq_index_start;
while (FreqToMel((freq_index)*hz_per_sbin) <= center_mel_freqs[chan]) {
++freq_index;
}
const int width = freq_index - chan_freq_index_start;
actual_channel_starts[chan] = chan_freq_index_start;
actual_channel_widths[chan] = width;
if (width == 0) {
// This channel doesn't actually get anything from the frequencies, it's
// always zero. We need then to insert some 'zero' weights into the
// output, and just redirect this channel to do a single multiplication at
// this point. For simplicity, the zeros are placed at the beginning of
// the weights arrays, so we have to go and update all the other
// weight_starts to reflect this shift (but only once).
state->channel_frequency_starts[chan] = 0;
state->channel_weight_starts[chan] = 0;
state->channel_widths[chan] = kFilterbankChannelBlockSize;
if (!needs_zeros) {
needs_zeros = 1;
int j;
for (j = 0; j < chan; ++j) {
state->channel_weight_starts[j] += kFilterbankChannelBlockSize;
}
weight_index_start += kFilterbankChannelBlockSize;
}
} else {
// How far back do we need to go to ensure that we have the proper
// alignment?
const int aligned_start =
(chan_freq_index_start / index_alignment) * index_alignment;
const int aligned_width = (chan_freq_index_start - aligned_start + width);
const int padded_width =
(((aligned_width - 1) / kFilterbankChannelBlockSize) + 1) *
kFilterbankChannelBlockSize;
state->channel_frequency_starts[chan] = aligned_start;
state->channel_weight_starts[chan] = weight_index_start;
state->channel_widths[chan] = padded_width;
weight_index_start += padded_width;
}
chan_freq_index_start = freq_index;
}
// Allocate the two arrays to store the weights - weight_index_start contains
// the index of what would be the next set of weights that we would need to
// add, so that's how many weights we need to allocate.
STATIC_ALLOC_ENSURE_ARRAY_SIZE(
state->weights, (weight_index_start * sizeof(*state->weights)));
for (int i = 0; i < weight_index_start; ++i) {
state->weights[i] = 0;
}
STATIC_ALLOC_ENSURE_ARRAY_SIZE(
state->unweights, (weight_index_start * sizeof(*state->unweights)));
for (int i = 0; i < weight_index_start; ++i) {
state->unweights[i] = 0;
}
// Next pass, compute all the weights. Since everything has been memset to
// zero, we only need to fill in the weights that correspond to some frequency
// for a channel.
const float mel_low = FreqToMel(config->lower_band_limit);
for (chan = 0; chan < num_channels_plus_1; ++chan) {
int frequency = actual_channel_starts[chan];
const int num_frequencies = actual_channel_widths[chan];
const int frequency_offset =
frequency - state->channel_frequency_starts[chan];
const int weight_start = state->channel_weight_starts[chan];
const float denom_val = (chan == 0) ? mel_low : center_mel_freqs[chan - 1];
int j;
for (j = 0; j < num_frequencies; ++j, ++frequency) {
const float weight =
(center_mel_freqs[chan] - FreqToMel(frequency * hz_per_sbin)) /
(center_mel_freqs[chan] - denom_val);
// Make the float into an integer for the weights (and unweights).
const int weight_index = weight_start + frequency_offset + j;
QuantizeFilterbankWeights(weight, state->weights + weight_index,
state->unweights + weight_index);
}
if (frequency > state->end_index) {
state->end_index = frequency;
}
}
if (state->end_index >= spectrum_size) {
error_reporter->Report("Filterbank end_index is above spectrum size.");
return 0;
}
return 1;
}
| 42.779343 | 101 | 0.674056 |
42cc99107701f2f6cd3ea17c5e1ebb7147bd583b | 340 | cpp | C++ | Proyecto_Final-Jorge_Pastor_V2/Trabajo de informatica/Trabajo_InformaticaI/propietarios.cpp | jorgepastor5/Spaceships-shop-manager | 51ec0aad6042f4a247a4d385c7ff4ab9233f7c35 | [
"MIT"
] | null | null | null | Proyecto_Final-Jorge_Pastor_V2/Trabajo de informatica/Trabajo_InformaticaI/propietarios.cpp | jorgepastor5/Spaceships-shop-manager | 51ec0aad6042f4a247a4d385c7ff4ab9233f7c35 | [
"MIT"
] | null | null | null | Proyecto_Final-Jorge_Pastor_V2/Trabajo de informatica/Trabajo_InformaticaI/propietarios.cpp | jorgepastor5/Spaceships-shop-manager | 51ec0aad6042f4a247a4d385c7ff4ab9233f7c35 | [
"MIT"
] | null | null | null | #include <iostream>
#include <string.h>
#include "propietarios.h"
#include <aplicacion.h>
#include <naves.h>
using namespace std;
propietarios::propietarios(){
}
void propietarios::setPlaneta(string planeta){
this->planeta = planeta;
}
string propietarios::getPlaneta(){
return planeta;
}
propietarios::~propietarios(){
}
| 12.592593 | 46 | 0.714706 |
42cd05326a8fba4bdf024c553065cb2b6aaab797 | 1,716 | cpp | C++ | model/src/ConstraintBlockImpl.cpp | mballance-sf/open-ps | a5ed44ce30bfe59462801ca7de4361d16950bcd2 | [
"Apache-2.0"
] | null | null | null | model/src/ConstraintBlockImpl.cpp | mballance-sf/open-ps | a5ed44ce30bfe59462801ca7de4361d16950bcd2 | [
"Apache-2.0"
] | null | null | null | model/src/ConstraintBlockImpl.cpp | mballance-sf/open-ps | a5ed44ce30bfe59462801ca7de4361d16950bcd2 | [
"Apache-2.0"
] | null | null | null | /*
* ConstraintBlockImpl.cpp
*
*
* Copyright 2016 Mentor Graphics Corporation
* All Rights Reserved Worldwide
*
* 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.
*
* Created on: May 4, 2016
* Author: ballance
*/
#include "ConstraintBlockImpl.h"
ConstraintBlockImpl::ConstraintBlockImpl(const std::string &name) :
BaseItemImpl(IBaseItem::TypeConstraint), NamedItemImpl(name) {
}
ConstraintBlockImpl::~ConstraintBlockImpl() {
// TODO Auto-generated destructor stub
}
void ConstraintBlockImpl::add(IConstraint *c) {
if (c) {
c->setParent(this);
m_constraints.push_back(c);
}
}
void ConstraintBlockImpl::add(const std::vector<IConstraint *> &cl) {
std::vector<IConstraint *>::const_iterator it;
for (it=cl.begin(); it!=cl.end(); it++) {
(*it)->setParent(this);
m_constraints.push_back(*it);
}
}
IBaseItem *ConstraintBlockImpl::clone() const {
ConstraintBlockImpl *ret = new ConstraintBlockImpl(getName());
for (std::vector<IConstraint *>::const_iterator it=getConstraints().begin();
it!=getConstraints().end(); it++) {
ret->add(dynamic_cast<IConstraint *>((*it)->clone()));
}
return ret;
}
| 26.4 | 78 | 0.685897 |
42ce15e3ef1c818c6fa7f3164b3ea50efac752c3 | 720 | cpp | C++ | 0-100/7/main.cpp | KevinEsh/LeetCode-Problems | 7e29509ad1cdc907bbba339f82e89f9e210e8249 | [
"MIT"
] | null | null | null | 0-100/7/main.cpp | KevinEsh/LeetCode-Problems | 7e29509ad1cdc907bbba339f82e89f9e210e8249 | [
"MIT"
] | null | null | null | 0-100/7/main.cpp | KevinEsh/LeetCode-Problems | 7e29509ad1cdc907bbba339f82e89f9e210e8249 | [
"MIT"
] | null | null | null | #include <string>
#include <iostream>
#include <algorithm>
#define lower -2147483648
#define upper 2147483647
class Solution
{
public:
int reverse(int x)
{
std::string sx = x < 0 ? "-" : "";
sx += std::to_string(abs(x));
if (x < 0)
{
std::reverse(sx.begin() + 1, sx.end());
}
else
{
std::reverse(sx.begin(), sx.end());
}
long long lx = stol(sx);
if (lower <= lx && lx <= upper)
{
return (int)lx;
}
return 0;
}
};
int main()
{
Solution model = Solution();
int reversed = model.reverse(-124265343);
std::cout << reversed << std::endl;
return 0;
} | 16.744186 | 51 | 0.475 |
42d20121235ebecbae7e13193478f3f5503966f2 | 619 | cpp | C++ | max_profit.cpp | shirishbahirat/algorithm | ec743d4c16ab4f429f22bd6f71540341b3905b3b | [
"Apache-2.0"
] | null | null | null | max_profit.cpp | shirishbahirat/algorithm | ec743d4c16ab4f429f22bd6f71540341b3905b3b | [
"Apache-2.0"
] | null | null | null | max_profit.cpp | shirishbahirat/algorithm | ec743d4c16ab4f429f22bd6f71540341b3905b3b | [
"Apache-2.0"
] | null | null | null | #include <iostream>
#include <vector>
using namespace std;
class Solution
{
public:
int maxProfit(vector<int> &prices)
{
int minprice = 0x7FFFFFFF;
int maxprofit = 0;
for (int i = 0; i < prices.size(); i++)
{
if (prices[i] < minprice)
minprice = prices[i];
else if (prices[i] - minprice > maxprofit)
maxprofit = prices[i] - minprice;
}
return maxprofit;
}
};
int main(int argc, char const *argv[])
{
Solution *obj = new Solution();
vector<int> prices = {7, 1, 5, 3, 6, 4};
int profit = obj->maxProfit(prices);
cout << profit << endl;
return 0;
}
| 18.205882 | 48 | 0.588045 |
42d2282bcf9fdd8a29be439803e5bd59024aa175 | 1,831 | cpp | C++ | src/main.cpp | HsiehYiChia/canny_text | 1025d09161cb75d06f858b14df7187ee2247219e | [
"MIT"
] | 1 | 2019-07-07T22:34:13.000Z | 2019-07-07T22:34:13.000Z | src/main.cpp | HsiehYiChia/canny_text | 1025d09161cb75d06f858b14df7187ee2247219e | [
"MIT"
] | null | null | null | src/main.cpp | HsiehYiChia/canny_text | 1025d09161cb75d06f858b14df7187ee2247219e | [
"MIT"
] | null | null | null | #include <iostream>
#include <chrono>
#include <thread>
#include <opencv2/opencv.hpp>
#include "../inc/ER.h"
#include "../inc/OCR.h"
#include "../inc/adaboost.h"
#include "../inc/utils.h"
#ifdef _WIN32
#include "../inc/getopt.h"
#elif __linux__
#include <getopt.h>
#endif
using namespace std;
int main(int argc, char* argv[])
{
ERFilter* er_filter = new ERFilter(THRESHOLD_STEP, MIN_ER_AREA, MAX_ER_AREA, NMS_STABILITY_T, NMS_OVERLAP_COEF, MIN_OCR_PROBABILITY);
er_filter->stc = new CascadeBoost("classifier/strong.classifier");
er_filter->wtc = new CascadeBoost("classifier/weak.classifier");
er_filter->ocr = new OCR("classifier/OCR.model", OCR_IMG_L, OCR_FEATURE_L);
er_filter->load_tp_table("dictionary/tp_table.txt");
er_filter->corrector.load("dictionary/big.txt");
char *filename = nullptr;
char *training_type = nullptr;
int is_file = -1;
char c = 0;
while ((c = getopt (argc, argv, "v:i:o:l:t:")) != -1)
{
switch (c)
{
case 'i':
filename = optarg;
image_mode(er_filter, filename);
break;
case 'v':
filename = optarg;
video_mode(er_filter, filename);
break;
case 'l':
filename = optarg;
draw_linear_time_MSER(filename);
break;
case 't':
training_type = optarg;
if (strcmp(training_type, "detection")==0)
{
get_lbp_data();
train_detection_classifier();
}
else if (strcmp(training_type, "ocr") == 0)
{
get_ocr_data();
train_ocr_model();
}
case '?':
/* Camera Mode */
if (optopt == 'v' && isprint(optopt))
video_mode(er_filter, nullptr);
else if (optopt == 'i' || optopt =='l')
{
cout << "Option -" << (char)optopt << " requires an argument" << endl;
usage();
}
break;
default:
usage();
abort();
}
}
delete er_filter->wtc;
delete er_filter->stc;
delete er_filter->ocr;
return 0;
}
| 21.797619 | 134 | 0.650464 |
42d36a7ff407d996315af2f45511739d597bc098 | 8,305 | hpp | C++ | SDK/PUBG_GameplayTasks_classes.hpp | realrespecter/PUBG-FULL-SDK | 5e2b0f103c74c95d2329c4c9dfbfab48aa0da737 | [
"MIT"
] | 7 | 2019-03-06T11:04:52.000Z | 2019-07-10T20:00:51.000Z | SDK/PUBG_GameplayTasks_classes.hpp | realrespecter/PUBG-FULL-SDK | 5e2b0f103c74c95d2329c4c9dfbfab48aa0da737 | [
"MIT"
] | null | null | null | SDK/PUBG_GameplayTasks_classes.hpp | realrespecter/PUBG-FULL-SDK | 5e2b0f103c74c95d2329c4c9dfbfab48aa0da737 | [
"MIT"
] | 10 | 2019-03-06T11:53:46.000Z | 2021-02-18T14:01:11.000Z | #pragma once
// PUBG FULL SDK - Generated By Respecter (5.3.4.11 [06/03/2019]) SDK
#ifdef _MSC_VER
#pragma pack(push, 0x8)
#endif
#include "PUBG_GameplayTasks_structs.hpp"
namespace SDK
{
//---------------------------------------------------------------------------
//Classes
//---------------------------------------------------------------------------
// Class GameplayTasks.GameplayTaskResource
// 0x0010 (0x0040 - 0x0030)
class UGameplayTaskResource : public UObject
{
public:
int ManualResourceID; // 0x0030(0x0004) (Edit, BlueprintVisible, BlueprintReadOnly, ZeroConstructor, Config, DisableEditOnInstance, IsPlainOldData)
int8_t AutoResourceID; // 0x0034(0x0001) (ZeroConstructor, IsPlainOldData)
unsigned char UnknownData00[0x3]; // 0x0035(0x0003) MISSED OFFSET
unsigned char bManuallySetID : 1; // 0x0038(0x0001) (Edit, DisableEditOnInstance)
unsigned char UnknownData01[0x7]; // 0x0039(0x0007) MISSED OFFSET
static UClass* StaticClass()
{
static auto ptr = UObject::FindClass("Class GameplayTasks.GameplayTaskResource");
return ptr;
}
};
// Class GameplayTasks.GameplayTask
// 0x0040 (0x0070 - 0x0030)
class UGameplayTask : public UObject
{
public:
unsigned char UnknownData00[0x8]; // 0x0030(0x0008) MISSED OFFSET
struct FName InstanceName; // 0x0038(0x0008) (ZeroConstructor, IsPlainOldData)
unsigned char UnknownData01[0x2]; // 0x0040(0x0002) MISSED OFFSET
ETaskResourceOverlapPolicy ResourceOverlapPolicy; // 0x0042(0x0001) (ZeroConstructor, Config, IsPlainOldData)
unsigned char UnknownData02[0x25]; // 0x0043(0x0025) MISSED OFFSET
class UGameplayTask* ChildTask; // 0x0068(0x0008) (ZeroConstructor, IsPlainOldData)
static UClass* StaticClass()
{
static auto ptr = UObject::FindClass("Class GameplayTasks.GameplayTask");
return ptr;
}
void ReadyForActivation();
void GenericGameplayTaskDelegate__DelegateSignature();
void EndTask();
};
// Class GameplayTasks.GameplayTaskOwnerInterface
// 0x0000 (0x0030 - 0x0030)
class UGameplayTaskOwnerInterface : public UInterface
{
public:
static UClass* StaticClass()
{
static auto ptr = UObject::FindClass("Class GameplayTasks.GameplayTaskOwnerInterface");
return ptr;
}
};
// Class GameplayTasks.GameplayTask_ClaimResource
// 0x0000 (0x0070 - 0x0070)
class UGameplayTask_ClaimResource : public UGameplayTask
{
public:
static UClass* StaticClass()
{
static auto ptr = UObject::FindClass("Class GameplayTasks.GameplayTask_ClaimResource");
return ptr;
}
void ReadyForActivation();
void GenericGameplayTaskDelegate__DelegateSignature();
void EndTask();
};
// Class GameplayTasks.GameplayTask_SpawnActor
// 0x0040 (0x00B0 - 0x0070)
class UGameplayTask_SpawnActor : public UGameplayTask
{
public:
struct FScriptMulticastDelegate SUCCESS; // 0x0070(0x0010) (ZeroConstructor, InstancedReference, BlueprintAssignable)
struct FScriptMulticastDelegate DidNotSpawn; // 0x0080(0x0010) (ZeroConstructor, InstancedReference, BlueprintAssignable)
unsigned char UnknownData00[0x18]; // 0x0090(0x0018) MISSED OFFSET
class UClass* ClassToSpawn; // 0x00A8(0x0008) (ZeroConstructor, IsPlainOldData)
static UClass* StaticClass()
{
static auto ptr = UObject::FindClass("Class GameplayTasks.GameplayTask_SpawnActor");
return ptr;
}
class UGameplayTask_SpawnActor* STATIC_SpawnActor(TScriptInterface<class UGameplayTaskOwnerInterface>* TaskOwner, struct FVector* SpawnLocation, struct FRotator* SpawnRotation, class UClass** Class, bool* bSpawnOnlyOnAuthority);
void FinishSpawningActor(class UObject** WorldContextObject, class AActor** SpawnedActor);
bool BeginSpawningActor(class UObject** WorldContextObject, class AActor** SpawnedActor);
};
// Class GameplayTasks.GameplayTask_TimeLimitedExecution
// 0x0030 (0x00A0 - 0x0070)
class UGameplayTask_TimeLimitedExecution : public UGameplayTask
{
public:
struct FScriptMulticastDelegate OnFinished; // 0x0070(0x0010) (ZeroConstructor, InstancedReference, BlueprintAssignable)
struct FScriptMulticastDelegate OnTimeExpired; // 0x0080(0x0010) (ZeroConstructor, InstancedReference, BlueprintAssignable)
unsigned char UnknownData00[0x10]; // 0x0090(0x0010) MISSED OFFSET
static UClass* StaticClass()
{
static auto ptr = UObject::FindClass("Class GameplayTasks.GameplayTask_TimeLimitedExecution");
return ptr;
}
void TaskFinishDelegate__DelegateSignature();
};
// Class GameplayTasks.GameplayTask_WaitDelay
// 0x0018 (0x0088 - 0x0070)
class UGameplayTask_WaitDelay : public UGameplayTask
{
public:
struct FScriptMulticastDelegate OnFinish; // 0x0070(0x0010) (ZeroConstructor, InstancedReference, BlueprintAssignable)
unsigned char UnknownData00[0x8]; // 0x0080(0x0008) MISSED OFFSET
static UClass* StaticClass()
{
static auto ptr = UObject::FindClass("Class GameplayTasks.GameplayTask_WaitDelay");
return ptr;
}
class UGameplayTask_WaitDelay* STATIC_TaskWaitDelay(TScriptInterface<class UGameplayTaskOwnerInterface>* TaskOwner, float* Time, unsigned char* Priority);
void TaskDelayDelegate__DelegateSignature();
};
// Class GameplayTasks.GameplayTasksComponent
// 0x0070 (0x0260 - 0x01F0)
class UGameplayTasksComponent : public UActorComponent
{
public:
unsigned char UnknownData00[0x8]; // 0x01F0(0x0008) MISSED OFFSET
TArray<class UGameplayTask*> SimulatedTasks; // 0x01F8(0x0010) (Net, ZeroConstructor)
TArray<class UGameplayTask*> TaskPriorityQueue; // 0x0208(0x0010) (ZeroConstructor)
unsigned char UnknownData01[0x10]; // 0x0218(0x0010) MISSED OFFSET
TArray<class UGameplayTask*> TickingTasks; // 0x0228(0x0010) (ZeroConstructor)
unsigned char UnknownData02[0x8]; // 0x0238(0x0008) MISSED OFFSET
struct FScriptMulticastDelegate OnClaimedResourcesChange; // 0x0240(0x0010) (BlueprintVisible, ZeroConstructor, InstancedReference)
unsigned char UnknownData03[0x10]; // 0x0250(0x0010) MISSED OFFSET
static UClass* StaticClass()
{
static auto ptr = UObject::FindClass("Class GameplayTasks.GameplayTasksComponent");
return ptr;
}
void OnRep_SimulatedTasks();
EGameplayTaskRunResult STATIC_K2_RunGameplayTask(TScriptInterface<class UGameplayTaskOwnerInterface>* TaskOwner, class UGameplayTask** Task, unsigned char* Priority, TArray<class UClass*>* AdditionalRequiredResources, TArray<class UClass*>* AdditionalClaimedResources);
};
}
#ifdef _MSC_VER
#pragma pack(pop)
#endif
| 43.710526 | 270 | 0.586635 |
42d3a2f68e017ecba874aac3207ad55e3241fd65 | 981 | cpp | C++ | src/sharding/hasher.cpp | oystr-foss/proxy-load-balancer | 14a58a1db4a189f27d0671cb89cfa4a06bd8b415 | [
"BSL-1.0"
] | 9 | 2020-10-06T16:36:11.000Z | 2021-07-25T15:06:25.000Z | src/sharding/hasher.cpp | oystr-foss/proxy-load-balancer | 14a58a1db4a189f27d0671cb89cfa4a06bd8b415 | [
"BSL-1.0"
] | null | null | null | src/sharding/hasher.cpp | oystr-foss/proxy-load-balancer | 14a58a1db4a189f27d0671cb89cfa4a06bd8b415 | [
"BSL-1.0"
] | null | null | null | //
// Created by realngnx on 11/06/2021.
//
#include <openssl/sha.h>
#include <openssl/md5.h>
#include "./hasher.hpp"
long Digest::to_md5_hash(std::string key) {
const char * hashed = reinterpret_cast<const char *>(md5(key));
return calculate_hash(hashed);
}
long Digest::to_sha256_hash(std::string key) {
const char * hashed = reinterpret_cast<const char *>(sha256(key));
return calculate_hash(hashed);
}
long Digest::calculate_hash(const char *hashed) {
long hash = 0;
for (int i = 0; i < 4; i++) {
hash <<= 8;
hash |= ((int) hashed[i]) & 0xFF;
}
return hash;
}
const unsigned char * Digest::sha256(const std::string &key) {
char const *c = key.c_str();
return SHA256(reinterpret_cast<const unsigned char *>(c), key.length(), nullptr);
}
const unsigned char * Digest::md5(const std::string &key) {
char const *c = key.c_str();
return MD5(reinterpret_cast<const unsigned char *>(c), key.length(), nullptr);
}
| 25.815789 | 85 | 0.64526 |
42d504427440ff4dcf5cf5f7baa66f1310cf7b39 | 917 | cpp | C++ | AddIn/DemoAddIn/cpp/DemoAddIn/EdgeBarDialog.cpp | XelaNimed/Samples | 2b509c985d99b53a9de1e2fb377a5a54dae43987 | [
"MIT"
] | 34 | 2015-06-08T05:10:28.000Z | 2022-02-08T20:15:42.000Z | AddIn/DemoAddIn/cpp/DemoAddIn/EdgeBarDialog.cpp | kabircosta/Samples | 3ffe1b268d49ec63686078d5c4f4d6eccb8f6f5f | [
"MIT"
] | 1 | 2019-04-03T06:32:23.000Z | 2019-04-03T06:32:23.000Z | AddIn/DemoAddIn/cpp/DemoAddIn/EdgeBarDialog.cpp | kabircosta/Samples | 3ffe1b268d49ec63686078d5c4f4d6eccb8f6f5f | [
"MIT"
] | 44 | 2015-03-26T17:29:45.000Z | 2021-12-29T03:41:29.000Z | // EdgeBarDialog.cpp : implementation file
//
#include "stdafx.h"
#include "DemoAddIn.h"
#include "EdgeBarDialog.h"
#include "afxdialogex.h"
// CEdgeBarDialog dialog
IMPLEMENT_DYNAMIC(CEdgeBarDialog, CDialogEx)
CEdgeBarDialog::CEdgeBarDialog(CWnd* pParent /*=NULL*/)
: CDialogEx(CEdgeBarDialog::IDD, pParent)
{
}
CEdgeBarDialog::~CEdgeBarDialog()
{
}
void CEdgeBarDialog::DoDataExchange(CDataExchange* pDX)
{
CDialogEx::DoDataExchange(pDX);
DDX_Control(pDX, IDC_LIST1, m_listView);
}
BEGIN_MESSAGE_MAP(CEdgeBarDialog, CDialogEx)
ON_WM_SIZE()
END_MESSAGE_MAP()
// CEdgeBarDialog message handlers
void CEdgeBarDialog::OnSize(UINT nType, int cx, int cy)
{
CDialogEx::OnSize(nType, cx, cy);
// TODO: Add your message handler code here
RECT rect;
// Get the dialog rectangle.
GetClientRect(&rect);
// Resize CListCtrl.
if (m_listView.m_hWnd != NULL)
{
m_listView.MoveWindow(&rect, TRUE);
}
} | 16.981481 | 55 | 0.742639 |
42da23d3f9b47e5504e83b1de7b6fb30fa6face1 | 6,368 | cpp | C++ | analysis_pipelines/scripts/scVILP/scripts/PerfectPhy/tools/convert.cpp | ProSolo/benchmarking_prosolo | 60fc1fcc990be9eedcdf024670fa81e68c0d3e2f | [
"MIT"
] | 2 | 2020-04-29T02:56:42.000Z | 2021-03-04T21:17:15.000Z | analysis_pipelines/scripts/scVILP/scripts/PerfectPhy/tools/convert.cpp | ProSolo/benchmarking_prosolo | 60fc1fcc990be9eedcdf024670fa81e68c0d3e2f | [
"MIT"
] | null | null | null | analysis_pipelines/scripts/scVILP/scripts/PerfectPhy/tools/convert.cpp | ProSolo/benchmarking_prosolo | 60fc1fcc990be9eedcdf024670fa81e68c0d3e2f | [
"MIT"
] | null | null | null | #include<vector>
#include<fstream>
#include<iostream>
#include<cctype>
using namespace std;
enum ArgError { ERROR = -1, QUIT = 0, NONE = 1 };
ArgError handleArguments(int argc, char** argv, char &dummychar, string &index, string &mapfile ) {
const char* helpmessage =
"Usage: ./convert.out [option] \n"
"\n"
"Options:\n"
"-h, --help Displays this message then quits.\n"
"-dummy CHAR Set CHAR as a dummy state (outputs -1).\n"
"-index I Set index of dataset as I (default is 1).\n"
"-mapfile FILE Writes the state mapping to FILE\n";
string arg;
for (int i = 1; i < argc; i++) {
if (argv[i][0] != '-') {
cerr << "Bad argument: " << argv[i] << " is not a flag" << endl;
return ERROR;
}
arg = argv[i];
if (arg.compare("-dummy") == 0) {
if (argc > i + 1) {
dummychar = argv[i+1][0];
if (!isgraph(dummychar)) {
cerr << "Bad argument: dummy character must be graphical" << endl;
return ERROR;
}
i++;
}
else {
cerr << "Bad argument: " << arg << " must precede a character" << endl;
return ERROR;
}
}
else if (arg.compare("-index") == 0) {
if (argc > i + 1) {
index = argv[i+1];
for (unsigned int j = 0; j < index.size(); j++)
if ( !( isdigit(index[j]) || (j == 0 && index[j] == '-' && index.size() > 1) ) ) {
cerr << "Bad argument: index must be an integer, not " << index << endl;
return ERROR;
}
i++;
}
else {
cerr << "Bad argument: " << arg << " must precede an integer" << endl;
return ERROR;
}
}
else if (arg.compare("-mapfile") == 0) {
if (argc > i + 1) {
mapfile = argv[i+1];
i++;
}
else {
cerr << "Bad argument: " << arg << " must precede a filename" << endl;
return ERROR;
}
}
else if (arg.compare("-h") == 0 || arg.compare("--help") == 0) {
cout << helpmessage;
return QUIT;
}
else {
cerr << "Bad argument: " << arg << " is not a valid flag" << endl;
return ERROR;
}
}
return NONE;
}
class Mapping {
private:
char c;
int n;
public:
Mapping(char in, int out):c(in), n(out) {}
void printTo(ostream& outf) const { outf << c << ' ' << n << ' '; }
};
#define readinto(var) do {\
cin >> var;\
if (!cin) {\
cerr << "Input error: " << #var << " could not be read" << endl;\
cerr << "Expected input:" << endl << "n m" << endl << "(n rows of: (10-char name) (m matrix cells...) )" << endl;\
return -1;\
}\
} while(false)
int main(int argc, char** argv) {
char dummychar = '\0';
string index;
string mapfile;
#define NAMEWIDTH 10
// improve io speed since not using C streams
ios_base::sync_with_stdio(false);
ArgError argerr = handleArguments(argc, argv, dummychar, index, mapfile);
if (argerr != NONE)
return argerr;
if (index.empty())
index = "1";
bool outputmap = (mapfile.size() > 0);
// read size of matrix
int n, m;
readinto(n);
readinto(m);
vector<vector<int> > data(n, vector<int>(m));
for (int i = 0; i < n; i++) {
vector<int>& row = data[i];
char cell;
// skip over the 10-character name
cin >> noskipws;
while (cin.get() != '\n');
cin.ignore(NAMEWIDTH);
cin >> skipws;
for (int j = 0; j < m; j++) {
int& mcell = row[j];
// skip over spaces between cells
//while (cin.peek() == ' ')
// cin.get(c);
readinto(cell);
if (cell == dummychar)
mcell = -1;
else
mcell = cell;
}
}
// convert to multistate numbers without gaps
vector<int> stateMap;
vector<vector<Mapping> > allmaps;
if (outputmap) {
allmaps.resize(m);
for(int j = 0; j < m; j++)
allmaps[j].reserve(n);
}
for (int j = 0; j < m; j++) {
for (int i = 0; i < n; i++) {
int& cell = data[i][j];
if (cell == -1)
continue;
int k, statecount = stateMap.size();
for (k = 0; k < statecount; k++)
if (stateMap[k] == cell) {
cell = k;
break;
}
if (k == statecount) {
if (outputmap)
allmaps[j].push_back(Mapping(cell, k));
stateMap.push_back(cell);
cell = k;
}
}
stateMap.clear();
}
if (outputmap) {
// write mapping to mapfile
ofstream outf(mapfile.c_str());
outf << index << endl << m;
if (dummychar != '\0') {
outf << ' ';
Mapping(dummychar, -1).printTo(outf);
}
outf << endl;
for (int j = 0; j < m; j++) {
const vector<Mapping>& row = allmaps[j];
outf << (int) row.size() << " ";
for (unsigned int k = 0; k < row.size(); k++)
row[k].printTo(outf);
outf << endl;
}
}
// write data to stdout
cout << index << endl << n << ' ' << m << endl;
for (int i = 0; i < n; i++) {
const vector<int>& row = data[i];
for (int j = 0; j < m; j++)
cout << row[j] << ' ';
cout << endl;
}
return 0;
}
#undef readinto
| 26.533333 | 126 | 0.400911 |
42dc5e85be449bb356e0607f71257bb5befcd199 | 1,198 | cpp | C++ | test/unit/math/prim/fun/svd_V_test.cpp | LaudateCorpus1/math | 990a66b3cccd27a5fd48626360bb91093a48278b | [
"BSD-3-Clause"
] | null | null | null | test/unit/math/prim/fun/svd_V_test.cpp | LaudateCorpus1/math | 990a66b3cccd27a5fd48626360bb91093a48278b | [
"BSD-3-Clause"
] | null | null | null | test/unit/math/prim/fun/svd_V_test.cpp | LaudateCorpus1/math | 990a66b3cccd27a5fd48626360bb91093a48278b | [
"BSD-3-Clause"
] | null | null | null | #include <stan/math/prim.hpp>
#include <gtest/gtest.h>
#include <test/unit/util.hpp>
#include <stdexcept>
TEST(MathMatrixPrimMat, svd_V) {
using stan::math::matrix_d;
using stan::math::svd_V;
// Values generated using R base::svd
matrix_d m00(0, 0);
EXPECT_THROW(svd_V(m00), std::invalid_argument);
matrix_d m11(1, 1);
m11 << 5;
matrix_d m11_V(1, 1);
m11_V << 1;
EXPECT_MATRIX_FLOAT_EQ(m11_V, svd_V(m11));
matrix_d m22(2, 2);
m22 << 1, 9, -4, 2;
matrix_d m22_V(2, 2);
m22_V << 0.014701114509569043, 0.999891932776825976, 0.999891932776825976,
-0.014701114509569043;
EXPECT_MATRIX_FLOAT_EQ(m22_V, svd_V(m22));
matrix_d m23(2, 3);
m23 << 1, 3, -5, 7, 9, -11;
matrix_d m23_V(3, 2);
m23_V << -0.41176240532160857, 0.81473005032163681, -0.56383954240865775,
0.12417046246885260, 0.71591667949570703, 0.56638912538393127;
EXPECT_MATRIX_FLOAT_EQ(m23_V, svd_V(m23));
matrix_d m32(3, 2);
m32 << 1, 3, -5, 7, 9, -11;
matrix_d m32_V(2, 2);
m32_V << -0.60622380392317887, 0.79529409626685355, 0.79529409626685355,
0.60622380392317887;
EXPECT_MATRIX_FLOAT_EQ(
m32_V, svd_V(m32)); // R's SVD returns different signs than Eigen.
}
| 27.860465 | 76 | 0.682805 |
42ddfb6b787055c1ca8ab033ae14936586fa5e59 | 2,590 | cpp | C++ | src/schemas/project/mutations/CreateTrade.cpp | BlockChain-Station/enjin-cpp-sdk | 3af1cd001d7e660787bbfb2e2414a96f5a95a228 | [
"Apache-2.0"
] | 12 | 2021-09-28T14:37:22.000Z | 2022-03-04T17:54:11.000Z | src/schemas/project/mutations/CreateTrade.cpp | BlockChain-Station/enjin-cpp-sdk | 3af1cd001d7e660787bbfb2e2414a96f5a95a228 | [
"Apache-2.0"
] | null | null | null | src/schemas/project/mutations/CreateTrade.cpp | BlockChain-Station/enjin-cpp-sdk | 3af1cd001d7e660787bbfb2e2414a96f5a95a228 | [
"Apache-2.0"
] | 8 | 2021-11-05T18:56:55.000Z | 2022-01-10T11:14:24.000Z | /* Copyright 2021 Enjin Pte. Ltd.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include "enjinsdk/project/CreateTrade.hpp"
#include "RapidJsonUtils.hpp"
namespace enjin::sdk::project {
CreateTrade::CreateTrade() : graphql::AbstractGraphqlRequest("enjin.sdk.project.CreateTrade") {
}
std::string CreateTrade::serialize() const {
rapidjson::Document document(rapidjson::kObjectType);
utils::join_serialized_object_to_document(document, ProjectTransactionRequestArguments::serialize());
if (asking_assets.has_value()) {
utils::set_array_member_from_type_vector<models::Trade>(document, "askingAssets", asking_assets.value());
}
if (offering_assets.has_value()) {
utils::set_array_member_from_type_vector<models::Trade>(document, "offeringAssets", offering_assets.value());
}
if (recipient_address.has_value()) {
utils::set_string_member(document, "recipientAddress", recipient_address.value());
}
return utils::document_to_string(document);
}
CreateTrade& CreateTrade::set_asking_assets(std::vector<models::Trade> assets) {
asking_assets = assets;
return *this;
}
CreateTrade& CreateTrade::set_offering_assets(std::vector<models::Trade> assets) {
offering_assets = assets;
return *this;
}
CreateTrade& CreateTrade::set_recipient_address(const std::string& recipient_address) {
CreateTrade::recipient_address = recipient_address;
return *this;
}
bool CreateTrade::operator==(const CreateTrade& rhs) const {
return static_cast<const graphql::AbstractGraphqlRequest&>(*this) ==
static_cast<const graphql::AbstractGraphqlRequest&>(rhs) &&
static_cast<const ProjectTransactionRequestArguments<CreateTrade>&>(*this) ==
static_cast<const ProjectTransactionRequestArguments<CreateTrade>&>(rhs) &&
asking_assets == rhs.asking_assets &&
offering_assets == rhs.offering_assets &&
recipient_address == rhs.recipient_address;
}
bool CreateTrade::operator!=(const CreateTrade& rhs) const {
return !(rhs == *this);
}
}
| 35.479452 | 117 | 0.72973 |
42e605a1f750beaaa3612e31308570d2f47beb89 | 35 | cpp | C++ | CacheSystem/StandardInitFunctions.cpp | kivzcu/HrdDataCacheSystem | cff2e3bd40a43bd374c7b16648daaf761dc3826a | [
"Apache-2.0"
] | null | null | null | CacheSystem/StandardInitFunctions.cpp | kivzcu/HrdDataCacheSystem | cff2e3bd40a43bd374c7b16648daaf761dc3826a | [
"Apache-2.0"
] | 3 | 2017-11-01T08:40:08.000Z | 2018-02-05T07:49:18.000Z | CacheSystem/StandardInitFunctions.cpp | kivzcu/HrdDataCacheSystem | cff2e3bd40a43bd374c7b16648daaf761dc3826a | [
"Apache-2.0"
] | 1 | 2021-02-16T13:14:23.000Z | 2021-02-16T13:14:23.000Z | #include "StandardInitFunctions.h"
| 17.5 | 34 | 0.828571 |
42ec31f75b4445181baf206aa4b8e13eeccd87df | 4,472 | cpp | C++ | deps/MAC_SDK/Source/MACDll/WinampSettingsDlg.cpp | jjzhang166/mous | 54a219712970bd6fabbac85102e1615babb69c41 | [
"BSD-2-Clause"
] | 75 | 2015-04-26T11:22:07.000Z | 2022-02-12T17:18:37.000Z | deps/MAC_SDK/Source/MACDll/WinampSettingsDlg.cpp | aliakbarRashidi/mous | 54a219712970bd6fabbac85102e1615babb69c41 | [
"BSD-2-Clause"
] | 7 | 2016-05-31T21:56:01.000Z | 2019-09-15T06:25:28.000Z | deps/MAC_SDK/Source/MACDll/WinampSettingsDlg.cpp | aliakbarRashidi/mous | 54a219712970bd6fabbac85102e1615babb69c41 | [
"BSD-2-Clause"
] | 19 | 2015-09-23T01:50:15.000Z | 2022-02-12T17:18:41.000Z | #include "stdafx.h"
#include "MACDll.h"
#include "WinampSettingsDlg.h"
#include ".\winampsettingsdlg.h"
IMPLEMENT_DYNAMIC(CWinampSettingsDlg, CDialog)
CWinampSettingsDlg::CWinampSettingsDlg(CWnd * pParent)
: CDialog(CWinampSettingsDlg::IDD, pParent)
{
m_hwndParent = NULL;
GetModuleFileName(AfxGetInstanceHandle(), m_strSettingsFilename.GetBuffer(MAX_PATH), MAX_PATH);
m_strSettingsFilename.ReleaseBuffer();
m_strSettingsFilename = m_strSettingsFilename.Left(m_strSettingsFilename.GetLength() - 3) + _T("ini");
LoadSettings();
}
CWinampSettingsDlg::~CWinampSettingsDlg()
{
}
void CWinampSettingsDlg::DoDataExchange(CDataExchange * pDX)
{
CDialog::DoDataExchange(pDX);
DDX_Check(pDX, IGNORE_BITSTREAM_ERRORS_CHECK, m_bIgnoreBitstreamErrors);
DDX_Check(pDX, SUPPRESS_SILENCE_CHECK, m_bSuppressSilence);
DDX_Check(pDX, SCALE_OUTPUT_CHECK, m_bScaleOutput);
DDX_Text(pDX, FILE_DISPLAY_METHOD_EDIT, m_strFileDisplayMethod);
DDX_Control(pDX, THREAD_PRIORITY_SLIDER, m_ctrlThreadPrioritySlider);
}
BEGIN_MESSAGE_MAP(CWinampSettingsDlg, CDialog)
END_MESSAGE_MAP()
BOOL CWinampSettingsDlg::LoadSettings()
{
GetPrivateProfileString(_T("Plugin Settings"), _T("File Display Method"), _T("%1 - %2"), m_strFileDisplayMethod.GetBuffer(1024), 1023, m_strSettingsFilename);
m_strFileDisplayMethod.ReleaseBuffer();
m_nThreadPriority = GetPrivateProfileInt(_T("Plugin Settings"), _T("Thread Priority)"), THREAD_PRIORITY_HIGHEST, m_strSettingsFilename);
m_bScaleOutput = GetPrivateProfileInt(_T("Plugin Settings"), _T("Scale Output"), FALSE, m_strSettingsFilename);
m_bIgnoreBitstreamErrors = GetPrivateProfileInt(_T("Plugin Settings"), _T("Ignore Bitstream Errors"), FALSE, m_strSettingsFilename);
m_bSuppressSilence = GetPrivateProfileInt(_T("Plugin Settings"), _T("Suppress Silence"), FALSE, m_strSettingsFilename);
return TRUE;
}
BOOL CWinampSettingsDlg::SaveSettings()
{
CString strTemp;
WritePrivateProfileString(_T("Plugin Settings"), _T("File Display Method"), m_strFileDisplayMethod, m_strSettingsFilename);
strTemp.Format(_T("%d"), m_nThreadPriority);
WritePrivateProfileString(_T("Plugin Settings"), _T("Thread Priority"), strTemp, m_strSettingsFilename);
strTemp.Format(_T("%d"), m_bScaleOutput);
WritePrivateProfileString(_T("Plugin Settings"), _T("Scale Output"), strTemp, m_strSettingsFilename);
strTemp.Format(_T("%d"), m_bIgnoreBitstreamErrors);
WritePrivateProfileString(_T("Plugin Settings"), _T("Ignore Bitstream Errors"), strTemp, m_strSettingsFilename);
strTemp.Format(_T("%d"), m_bSuppressSilence);
WritePrivateProfileString(_T("Plugin Settings"), _T("Suppress Silence"), strTemp, m_strSettingsFilename);
return TRUE;
}
BOOL CWinampSettingsDlg::Show(HWND hwndParent)
{
m_hwndParent = hwndParent;
DoModal();
return TRUE;
}
BOOL CWinampSettingsDlg::OnInitDialog()
{
CDialog::OnInitDialog();
m_ctrlThreadPrioritySlider.SetRange(0, 4);
m_ctrlThreadPrioritySlider.SetPos(GetSliderFromThreadPriority());
return TRUE; // return TRUE unless you set the focus to a control
// EXCEPTION: OCX Property Pages should return FALSE
}
void CWinampSettingsDlg::OnOK()
{
UpdateData(TRUE);
m_nThreadPriority = GetThreadPriorityFromSlider();
SaveSettings();
CDialog::OnOK();
}
int CWinampSettingsDlg::GetSliderFromThreadPriority()
{
int nSlider = 4;
switch (m_nThreadPriority)
{
case THREAD_PRIORITY_LOWEST: nSlider = 0; break;
case THREAD_PRIORITY_BELOW_NORMAL: nSlider = 1; break;
case THREAD_PRIORITY_NORMAL: nSlider = 2; break;
case THREAD_PRIORITY_ABOVE_NORMAL: nSlider = 3; break;
case THREAD_PRIORITY_HIGHEST: nSlider = 4; break;
}
return nSlider;
}
int CWinampSettingsDlg::GetThreadPriorityFromSlider()
{
int nThreadPriority = THREAD_PRIORITY_HIGHEST;
switch (m_ctrlThreadPrioritySlider.GetPos())
{
case 0: nThreadPriority = THREAD_PRIORITY_LOWEST; break;
case 1: nThreadPriority = THREAD_PRIORITY_BELOW_NORMAL; break;
case 2: nThreadPriority = THREAD_PRIORITY_NORMAL; break;
case 3: nThreadPriority = THREAD_PRIORITY_ABOVE_NORMAL; break;
case 4: nThreadPriority = THREAD_PRIORITY_HIGHEST; break;
}
return nThreadPriority;
}
| 35.776 | 163 | 0.727862 |
42ee21d925bf2c58bc145b5c191e40d71ac631a0 | 22,748 | cpp | C++ | vlc_linux/vlc-3.0.16/modules/demux/adaptive/Streams.cpp | Brook1711/biubiu_Qt6 | 5c4d22a1d1beef63bc6c7738dce6c477c4642803 | [
"MIT"
] | null | null | null | vlc_linux/vlc-3.0.16/modules/demux/adaptive/Streams.cpp | Brook1711/biubiu_Qt6 | 5c4d22a1d1beef63bc6c7738dce6c477c4642803 | [
"MIT"
] | null | null | null | vlc_linux/vlc-3.0.16/modules/demux/adaptive/Streams.cpp | Brook1711/biubiu_Qt6 | 5c4d22a1d1beef63bc6c7738dce6c477c4642803 | [
"MIT"
] | null | null | null | /*
* Streams.cpp
*****************************************************************************
* Copyright (C) 2014 - VideoLAN and VLC authors
*
* This program is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as published
* by the Free Software Foundation; either version 2.1 of the License, or
* (at your option) any later version.
*
* This 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 Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, write to the Free Software Foundation,
* Inc., 51 Franklin Street, Fifth Floor, Boston MA 02110-1301, USA.
*****************************************************************************/
#ifdef HAVE_CONFIG_H
# include "config.h"
#endif
#include "Streams.hpp"
#include "logic/AbstractAdaptationLogic.h"
#include "http/HTTPConnection.hpp"
#include "http/HTTPConnectionManager.h"
#include "playlist/BaseAdaptationSet.h"
#include "playlist/BaseRepresentation.h"
#include "playlist/SegmentChunk.hpp"
#include "plumbing/SourceStream.hpp"
#include "plumbing/CommandsQueue.hpp"
#include "tools/FormatNamespace.hpp"
#include "tools/Debug.hpp"
#include <vlc_demux.h>
#include <algorithm>
using namespace adaptive;
using namespace adaptive::http;
AbstractStream::AbstractStream(demux_t * demux_)
{
p_realdemux = demux_;
format = StreamFormat::UNKNOWN;
currentChunk = NULL;
eof = false;
valid = true;
disabled = false;
discontinuity = false;
needrestart = false;
inrestart = false;
demuxfirstchunk = false;
segmentTracker = NULL;
demuxersource = NULL;
demuxer = NULL;
fakeesout = NULL;
notfound_sequence = 0;
last_buffer_status = buffering_lessthanmin;
vlc_mutex_init(&lock);
}
bool AbstractStream::init(const StreamFormat &format_, SegmentTracker *tracker, AbstractConnectionManager *conn)
{
/* Don't even try if not supported or already init */
if((unsigned)format_ == StreamFormat::UNSUPPORTED || demuxersource)
return false;
demuxersource = new (std::nothrow) BufferedChunksSourceStream( VLC_OBJECT(p_realdemux), this );
if(demuxersource)
{
CommandsFactory *factory = new (std::nothrow) CommandsFactory();
if(factory)
{
CommandsQueue *commandsqueue = new (std::nothrow) CommandsQueue(factory);
if(commandsqueue)
{
fakeesout = new (std::nothrow) FakeESOut(p_realdemux->out, commandsqueue);
if(fakeesout)
{
/* All successfull */
fakeesout->setExtraInfoProvider( this );
const Role & streamRole = tracker->getStreamRole();
if(streamRole.isDefault() && streamRole.autoSelectable())
fakeesout->setPriority(ES_PRIORITY_MIN + 10);
else if(!streamRole.autoSelectable())
fakeesout->setPriority(ES_PRIORITY_NOT_DEFAULTABLE);
format = format_;
segmentTracker = tracker;
segmentTracker->registerListener(this);
segmentTracker->notifyBufferingState(true);
connManager = conn;
fakeesout->setExpectedTimestamp(segmentTracker->getPlaybackTime());
declaredCodecs();
return true;
}
delete commandsqueue;
commandsqueue = NULL;
}
else
{
delete factory;
}
}
delete demuxersource;
}
return false;
}
AbstractStream::~AbstractStream()
{
delete currentChunk;
if(segmentTracker)
segmentTracker->notifyBufferingState(false);
delete segmentTracker;
delete demuxer;
delete demuxersource;
delete fakeesout;
vlc_mutex_destroy(&lock);
}
void AbstractStream::prepareRestart(bool b_discontinuity)
{
if(demuxer)
{
/* Enqueue Del Commands for all current ES */
demuxer->drain();
fakeEsOut()->resetTimestamps();
/* Enqueue Del Commands for all current ES */
fakeEsOut()->scheduleAllForDeletion();
if(b_discontinuity)
fakeEsOut()->schedulePCRReset();
fakeEsOut()->commandsQueue()->Commit();
/* ignoring demuxer's own Del commands */
fakeEsOut()->commandsQueue()->setDrop(true);
delete demuxer;
fakeEsOut()->commandsQueue()->setDrop(false);
demuxer = NULL;
}
}
void AbstractStream::setLanguage(const std::string &lang)
{
language = lang;
}
void AbstractStream::setDescription(const std::string &desc)
{
description = desc;
}
mtime_t AbstractStream::getPCR() const
{
vlc_mutex_locker locker(const_cast<vlc_mutex_t *>(&lock));
if(!valid || disabled)
return VLC_TS_INVALID;
return fakeEsOut()->commandsQueue()->getPCR();
}
mtime_t AbstractStream::getMinAheadTime() const
{
if(!segmentTracker)
return 0;
return segmentTracker->getMinAheadTime();
}
mtime_t AbstractStream::getFirstDTS() const
{
vlc_mutex_locker locker(const_cast<vlc_mutex_t *>(&lock));
if(!valid || disabled)
return VLC_TS_INVALID;
mtime_t dts = fakeEsOut()->commandsQueue()->getFirstDTS();
if(dts == VLC_TS_INVALID)
dts = fakeEsOut()->commandsQueue()->getPCR();
return dts;
}
int AbstractStream::esCount() const
{
return fakeEsOut()->esCount();
}
bool AbstractStream::seekAble() const
{
bool restarting = fakeEsOut()->restarting();
bool draining = fakeEsOut()->commandsQueue()->isDraining();
bool eof = fakeEsOut()->commandsQueue()->isEOF();
msg_Dbg(p_realdemux, "demuxer %p, fakeesout restarting %d, "
"discontinuity %d, commandsqueue draining %d, commandsqueue eof %d",
static_cast<void *>(demuxer), restarting, discontinuity, draining, eof);
if(!valid || restarting || discontinuity || (!eof && draining))
{
msg_Warn(p_realdemux, "not seekable");
return false;
}
else
{
return true;
}
}
bool AbstractStream::isSelected() const
{
return fakeEsOut()->hasSelectedEs();
}
bool AbstractStream::reactivate(mtime_t basetime)
{
vlc_mutex_locker locker(&lock);
if(setPosition(basetime, false))
{
setDisabled(false);
return true;
}
else
{
eof = true; /* can't reactivate */
return false;
}
}
bool AbstractStream::startDemux()
{
if(demuxer)
return false;
demuxersource->Reset();
demuxer = createDemux(format);
if(!demuxer && format != StreamFormat())
msg_Err(p_realdemux, "Failed to create demuxer %p %s", (void *)demuxer,
format.str().c_str());
demuxfirstchunk = true;
return !!demuxer;
}
bool AbstractStream::restartDemux()
{
bool b_ret = true;
if(!demuxer)
{
fakeesout->recycleAll();
b_ret = startDemux();
}
else if(demuxer->needsRestartOnSeek())
{
inrestart = true;
/* Push all ES as recycling candidates */
fakeEsOut()->recycleAll();
/* Restart with ignoring es_Del pushes to queue when terminating demux */
fakeEsOut()->commandsQueue()->setDrop(true);
demuxer->destroy();
fakeEsOut()->commandsQueue()->setDrop(false);
b_ret = demuxer->create();
inrestart = false;
}
else
{
fakeEsOut()->commandsQueue()->Commit();
}
return b_ret;
}
void AbstractStream::setDisabled(bool b)
{
if(disabled != b)
segmentTracker->notifyBufferingState(!b);
disabled = b;
}
bool AbstractStream::isValid() const
{
vlc_mutex_locker locker(const_cast<vlc_mutex_t *>(&lock));
return valid;
}
bool AbstractStream::isDisabled() const
{
vlc_mutex_locker locker(const_cast<vlc_mutex_t *>(&lock));
return disabled;
}
bool AbstractStream::decodersDrained()
{
return fakeEsOut()->decodersDrained();
}
AbstractStream::buffering_status AbstractStream::getLastBufferStatus() const
{
return last_buffer_status;
}
mtime_t AbstractStream::getDemuxedAmount(mtime_t from) const
{
return fakeEsOut()->commandsQueue()->getDemuxedAmount(from);
}
AbstractStream::buffering_status AbstractStream::bufferize(mtime_t nz_deadline,
unsigned i_min_buffering, unsigned i_extra_buffering)
{
last_buffer_status = doBufferize(nz_deadline, i_min_buffering, i_extra_buffering);
return last_buffer_status;
}
AbstractStream::buffering_status AbstractStream::doBufferize(mtime_t nz_deadline,
mtime_t i_min_buffering, mtime_t i_extra_buffering)
{
vlc_mutex_lock(&lock);
/* Ensure it is configured */
if(!segmentTracker || !connManager || !valid)
{
vlc_mutex_unlock(&lock);
return AbstractStream::buffering_end;
}
/* Disable streams that are not selected (alternate streams) */
if(esCount() && !isSelected() && !fakeEsOut()->restarting())
{
setDisabled(true);
segmentTracker->reset();
fakeEsOut()->commandsQueue()->Abort(false);
msg_Dbg(p_realdemux, "deactivating %s stream %s",
format.str().c_str(), description.c_str());
vlc_mutex_unlock(&lock);
return AbstractStream::buffering_end;
}
if(fakeEsOut()->commandsQueue()->isDraining())
{
vlc_mutex_unlock(&lock);
return AbstractStream::buffering_suspended;
}
segmentTracker->setStartPosition();
/* Reached end of live playlist */
if(!segmentTracker->bufferingAvailable())
{
vlc_mutex_unlock(&lock);
return AbstractStream::buffering_suspended;
}
if(!demuxer)
{
format = segmentTracker->getCurrentFormat();
if(!startDemux())
{
/* If demux fails because of probing failure / wrong format*/
if(discontinuity)
{
msg_Dbg( p_realdemux, "Draining on format change" );
prepareRestart();
discontinuity = false;
fakeEsOut()->commandsQueue()->setDraining();
vlc_mutex_unlock(&lock);
return AbstractStream::buffering_ongoing;
}
valid = false; /* Prevent further retries */
fakeEsOut()->commandsQueue()->setEOF(true);
vlc_mutex_unlock(&lock);
return AbstractStream::buffering_end;
}
}
const int64_t i_total_buffering = i_min_buffering + i_extra_buffering;
mtime_t i_demuxed = fakeEsOut()->commandsQueue()->getDemuxedAmount(nz_deadline);
segmentTracker->notifyBufferingLevel(i_min_buffering, i_demuxed, i_total_buffering);
if(i_demuxed < i_total_buffering) /* not already demuxed */
{
mtime_t nz_extdeadline = fakeEsOut()->commandsQueue()->getBufferingLevel() +
(i_total_buffering - i_demuxed) / 4;
nz_deadline = std::max(nz_deadline, nz_extdeadline);
/* need to read, demuxer still buffering, ... */
vlc_mutex_unlock(&lock);
Demuxer::Status demuxStatus = demuxer->demux(nz_deadline);
vlc_mutex_lock(&lock);
if(demuxStatus != Demuxer::Status::STATUS_SUCCESS)
{
if(discontinuity || needrestart)
{
msg_Dbg(p_realdemux, "Restarting demuxer");
prepareRestart(discontinuity);
if(discontinuity)
{
msg_Dbg(p_realdemux, "Draining on discontinuity");
fakeEsOut()->commandsQueue()->setDraining();
discontinuity = false;
}
needrestart = false;
vlc_mutex_unlock(&lock);
return AbstractStream::buffering_ongoing;
}
fakeEsOut()->commandsQueue()->setEOF(true);
vlc_mutex_unlock(&lock);
return AbstractStream::buffering_end;
}
i_demuxed = fakeEsOut()->commandsQueue()->getDemuxedAmount(nz_deadline);
segmentTracker->notifyBufferingLevel(i_min_buffering, i_demuxed, i_total_buffering);
}
vlc_mutex_unlock(&lock);
if(i_demuxed < i_total_buffering) /* need to read more */
{
if(i_demuxed < i_min_buffering)
return AbstractStream::buffering_lessthanmin; /* high prio */
return AbstractStream::buffering_ongoing;
}
return AbstractStream::buffering_full;
}
AbstractStream::status AbstractStream::dequeue(mtime_t nz_deadline, mtime_t *pi_pcr)
{
vlc_mutex_locker locker(&lock);
*pi_pcr = nz_deadline;
if(fakeEsOut()->commandsQueue()->isDraining())
{
AdvDebug(mtime_t pcrvalue = fakeEsOut()->commandsQueue()->getPCR();
mtime_t dtsvalue = fakeEsOut()->commandsQueue()->getFirstDTS();
msg_Dbg(p_realdemux, "Stream %s pcr %" PRId64 " dts %" PRId64 " deadline %" PRId64 " [DRAINING]",
description.c_str(), pcrvalue, dtsvalue, nz_deadline));
*pi_pcr = fakeEsOut()->commandsQueue()->Process(p_realdemux->out, VLC_TS_0 + nz_deadline);
if(!fakeEsOut()->commandsQueue()->isEmpty())
return AbstractStream::status_demuxed;
if(!fakeEsOut()->commandsQueue()->isEOF())
{
fakeEsOut()->commandsQueue()->Abort(true); /* reset buffering level and flags */
return AbstractStream::status_discontinuity;
}
}
if(!valid || disabled || fakeEsOut()->commandsQueue()->isEOF())
{
*pi_pcr = nz_deadline;
return AbstractStream::status_eof;
}
mtime_t bufferingLevel = fakeEsOut()->commandsQueue()->getBufferingLevel();
AdvDebug(mtime_t pcrvalue = fakeEsOut()->commandsQueue()->getPCR();
mtime_t dtsvalue = fakeEsOut()->commandsQueue()->getFirstDTS();
msg_Dbg(p_realdemux, "Stream %s pcr %" PRId64 " dts %" PRId64 " deadline %" PRId64 " buflevel %" PRId64,
description.c_str(), pcrvalue, dtsvalue, nz_deadline, bufferingLevel));
if(nz_deadline + VLC_TS_0 <= bufferingLevel) /* demuxed */
{
*pi_pcr = fakeEsOut()->commandsQueue()->Process( p_realdemux->out, VLC_TS_0 + nz_deadline );
return AbstractStream::status_demuxed;
}
return AbstractStream::status_buffering;
}
std::string AbstractStream::getContentType()
{
if (currentChunk == NULL && !eof)
{
const bool b_restarting = fakeEsOut()->restarting();
currentChunk = segmentTracker->getNextChunk(!b_restarting, connManager);
}
if(currentChunk)
return currentChunk->getContentType();
else
return std::string();
}
block_t * AbstractStream::readNextBlock()
{
if (currentChunk == NULL && !eof)
{
const bool b_restarting = fakeEsOut()->restarting();
currentChunk = segmentTracker->getNextChunk(!b_restarting, connManager);
}
if(discontinuity && demuxfirstchunk)
{
/* clear up discontinuity on demux start (discontinuity on start segment bug) */
discontinuity = false;
}
if(discontinuity || needrestart)
{
msg_Info(p_realdemux, "Encountered discontinuity");
/* Force stream/demuxer to end for this call */
return NULL;
}
if(currentChunk == NULL)
{
eof = true;
return NULL;
}
const bool b_segment_head_chunk = (currentChunk->getBytesRead() == 0);
block_t *block = currentChunk->readBlock();
if(block == NULL)
{
if(currentChunk->getRequestStatus() == RequestStatus::NotFound &&
++notfound_sequence < 3)
{
discontinuity = true;
}
delete currentChunk;
currentChunk = NULL;
return NULL;
}
else notfound_sequence = 0;
demuxfirstchunk = false;
if (currentChunk->isEmpty())
{
delete currentChunk;
currentChunk = NULL;
}
block = checkBlock(block, b_segment_head_chunk);
return block;
}
bool AbstractStream::setPosition(mtime_t time, bool tryonly)
{
if(!seekAble())
return false;
bool b_needs_restart = demuxer ? demuxer->needsRestartOnSeek() : true;
bool ret = segmentTracker->setPositionByTime(time, b_needs_restart, tryonly);
if(!tryonly && ret)
{
// clear eof flag before restartDemux() to prevent readNextBlock() fail
eof = false;
demuxfirstchunk = true;
notfound_sequence = 0;
if(b_needs_restart)
{
if(currentChunk)
delete currentChunk;
currentChunk = NULL;
needrestart = false;
fakeEsOut()->resetTimestamps();
mtime_t seekMediaTime = segmentTracker->getPlaybackTime(true);
fakeEsOut()->setExpectedTimestamp(seekMediaTime);
if( !restartDemux() )
{
msg_Info(p_realdemux, "Restart demux failed");
eof = true;
valid = false;
ret = false;
}
else
{
fakeEsOut()->commandsQueue()->setEOF(false);
}
}
else fakeEsOut()->commandsQueue()->Abort( true );
// in some cases, media time seek != sent dts
// es_out_Control(p_realdemux->out, ES_OUT_SET_NEXT_DISPLAY_TIME,
// VLC_TS_0 + time);
}
return ret;
}
bool AbstractStream::getMediaPlaybackTimes(mtime_t *start, mtime_t *end,
mtime_t *length,
mtime_t *mediaStart,
mtime_t *demuxStart) const
{
return (segmentTracker->getMediaPlaybackRange(start, end, length) &&
fakeEsOut()->getStartTimestamps(mediaStart, demuxStart));
}
void AbstractStream::runUpdates()
{
if(valid && !disabled)
segmentTracker->updateSelected();
}
void AbstractStream::fillExtraFMTInfo( es_format_t *p_fmt ) const
{
if(!p_fmt->psz_language && !language.empty())
p_fmt->psz_language = strdup(language.c_str());
if(!p_fmt->psz_description && !description.empty())
p_fmt->psz_description = strdup(description.c_str());
}
AbstractDemuxer * AbstractStream::createDemux(const StreamFormat &format)
{
AbstractDemuxer *ret = newDemux( VLC_OBJECT(p_realdemux), format,
(es_out_t *)fakeEsOut(), demuxersource );
if(ret && !ret->create())
{
delete ret;
ret = NULL;
}
else fakeEsOut()->commandsQueue()->Commit();
return ret;
}
AbstractDemuxer *AbstractStream::newDemux(vlc_object_t *p_obj, const StreamFormat &format,
es_out_t *out, AbstractSourceStream *source) const
{
AbstractDemuxer *ret = NULL;
switch((unsigned)format)
{
case StreamFormat::MP4:
ret = new Demuxer(p_obj, "mp4", out, source);
break;
case StreamFormat::MPEG2TS:
ret = new Demuxer(p_obj, "ts", out, source);
break;
default:
case StreamFormat::UNSUPPORTED:
break;
}
return ret;
}
void AbstractStream::trackerEvent(const SegmentTrackerEvent &event)
{
switch(event.type)
{
case SegmentTrackerEvent::DISCONTINUITY:
discontinuity = true;
break;
case SegmentTrackerEvent::FORMATCHANGE:
/* Check if our current demux is still valid */
if(*event.u.format.f != format || format == StreamFormat(StreamFormat::UNKNOWN))
{
/* Format has changed between segments, we need to drain and change demux */
msg_Info(p_realdemux, "Changing stream format %s -> %s",
format.str().c_str(), event.u.format.f->str().c_str());
format = *event.u.format.f;
/* This is an implict discontinuity */
discontinuity = true;
}
break;
case SegmentTrackerEvent::SWITCHING:
if(demuxer && !inrestart)
{
if(!demuxer->bitstreamSwitchCompatible() ||
(event.u.switching.next &&
!event.u.switching.next->getAdaptationSet()->isBitSwitchable()))
needrestart = true;
}
break;
case SegmentTrackerEvent::SEGMENT_CHANGE:
if(demuxer && demuxer->needsRestartOnEachSegment() && !inrestart)
{
needrestart = true;
}
break;
default:
break;
}
}
static void add_codec_string_from_fourcc(vlc_fourcc_t fourcc,
std::list<std::string> &codecs)
{
std::string codec;
codec.insert(0, reinterpret_cast<const char *>(&fourcc), 4);
codecs.push_back(codec);
}
void AbstractStream::declaredCodecs()
{
const std::string & streamDesc = segmentTracker->getStreamDescription();
const std::string & streamLang = segmentTracker->getStreamLanguage();
std::list<std::string> codecs = segmentTracker->getCurrentCodecs();
if(codecs.empty())
{
const StreamFormat format = segmentTracker->getCurrentFormat();
switch(format)
{
case StreamFormat::TTML:
add_codec_string_from_fourcc(VLC_CODEC_TTML, codecs);
break;
case StreamFormat::WEBVTT:
add_codec_string_from_fourcc(VLC_CODEC_WEBVTT, codecs);
break;
default:
break;
}
}
for(std::list<std::string>::const_iterator it = codecs.begin();
it != codecs.end(); ++it)
{
FormatNamespace fnsp(*it);
es_format_t fmt;
es_format_Init(&fmt, fnsp.getFmt()->i_cat, fnsp.getFmt()->i_codec);
es_format_Copy(&fmt, fnsp.getFmt());
if(!streamLang.empty())
fmt.psz_language = strdup(streamLang.c_str());
if(!streamDesc.empty())
fmt.psz_description = strdup(streamDesc.c_str());
fakeEsOut()->declareEs( &fmt );
es_format_Clean(&fmt);
}
}
FakeESOut::LockedFakeEsOut AbstractStream::fakeEsOut()
{
return fakeesout->WithLock();
}
FakeESOut::LockedFakeEsOut AbstractStream::fakeEsOut() const
{
return fakeesout->WithLock();
}
| 30.61642 | 117 | 0.603833 |
42eeb128acdfaa26adbf040fc8c4d2607459d420 | 344 | cpp | C++ | src/utils/file.cpp | kanisiuskenneth/simple-libev-http-get-server | 4a0d721512a72f0ac719a8b67c12454e3c2c0cdd | [
"MIT"
] | null | null | null | src/utils/file.cpp | kanisiuskenneth/simple-libev-http-get-server | 4a0d721512a72f0ac719a8b67c12454e3c2c0cdd | [
"MIT"
] | null | null | null | src/utils/file.cpp | kanisiuskenneth/simple-libev-http-get-server | 4a0d721512a72f0ac719a8b67c12454e3c2c0cdd | [
"MIT"
] | null | null | null | #include "file.h"
#include <string>
#include <fstream>
#include <iostream>
#include <sstream>
using namespace std;
File::File(string filename) {
ifstream inFile;
inFile.open(filename);
stringstream strStream;
strStream << inFile.rdbuf();
content = strStream.str();
}
string File::GetContent() {
return content;
}
| 17.2 | 32 | 0.674419 |
0cd31c2d57119c4b743b42991bf7b19b70237050 | 915 | cpp | C++ | src/boost/archive/yaml_oarchive.cpp | rwols/yaml-archive | 4afec73e557c15350c5e068c010f4e378edc95ef | [
"BSL-1.0"
] | 1 | 2018-01-27T23:35:21.000Z | 2018-01-27T23:35:21.000Z | src/boost/archive/yaml_oarchive.cpp | rwols/yaml-archive | 4afec73e557c15350c5e068c010f4e378edc95ef | [
"BSL-1.0"
] | 2 | 2019-08-17T05:37:36.000Z | 2019-08-17T22:57:26.000Z | src/boost/archive/yaml_oarchive.cpp | rwols/yaml-archive | 4afec73e557c15350c5e068c010f4e378edc95ef | [
"BSL-1.0"
] | 1 | 2021-03-19T11:53:53.000Z | 2021-03-19T11:53:53.000Z | /** @file
*
* @brief Defines narrow concrete output archives.
*
* @author Raoul Wols
*
* @date 2017
*
* @copyright See LICENSE.md
*
*/
#if (defined _MSC_VER) && (_MSC_VER == 1200)
#pragma warning(disable : 4786) // too long name, harmless warning
#endif
#define BOOST_ARCHIVE_SOURCE
#include <boost/archive/detail/archive_serializer_map.hpp>
#include <boost/archive/yaml_oarchive.hpp>
#include <boost/serialization/config.hpp>
// explicitly instantiate for this type of yaml stream
#include <boost/archive/impl/archive_serializer_map.ipp>
#include <boost/archive/impl/basic_yaml_oarchive.ipp>
#include <boost/archive/impl/yaml_oarchive_impl.ipp>
namespace boost {
namespace archive {
template class detail::archive_serializer_map<yaml_oarchive>;
template class basic_yaml_oarchive<yaml_oarchive>;
template class yaml_oarchive_impl<yaml_oarchive>;
} // namespace archive
} // namespace boost
| 25.416667 | 66 | 0.76612 |
0cd88d993983b62868af471659f79d4d06a7acfd | 1,513 | cpp | C++ | course1/Laba2/G/main.cpp | flydzen/ITMO_algo | ea251dca0fddb0d4d212377c6785cdc3667ece89 | [
"MIT"
] | null | null | null | course1/Laba2/G/main.cpp | flydzen/ITMO_algo | ea251dca0fddb0d4d212377c6785cdc3667ece89 | [
"MIT"
] | null | null | null | course1/Laba2/G/main.cpp | flydzen/ITMO_algo | ea251dca0fddb0d4d212377c6785cdc3667ece89 | [
"MIT"
] | null | null | null | #include <iostream>
#include <vector>
#include <cmath>
#include <algorithm>
#define ui unsigned int
#define ull unsigned long long
#define us unsigned long long
#pragma GCC optimize("03")
using namespace std;
ui cur = 0;
ui a, b;
inline ui nextRand24() {
cur = cur * a + b;
return cur >> 8;
}
inline ui nextRand32() {
return (nextRand24() << 8) ^ nextRand24();
}
inline ui digit(ui num, ui i) {
return (num >> (i * 8) & 0xFF);
}
void lsd(vector<ui> &v) {
ui k = 256;
ui m = 4;
ui n = v.size();
vector<ui> nV(n);
for (ui i = 0; i < m; i++) {
vector<ui> c(k);
for (ui j = 0; j < n; j++) {
c[digit(v[j], i)]++;
}
ui count = 0;
for (ui j = 0; j < k; j++) {
ui temp = c[j];
c[j] = count;
count += temp;
}
for (ui j = 0; j < n; j++) {
ui d = digit(v[j], i);
nV[c[d]] = v[j];
c[d]++;
}
v = nV;
}
}
int main() {
ios_base::sync_with_stdio(false);
cin.tie(nullptr);
ui t, n;
cin >> t >> n;
for (ui i = 0; i < t; i++) {
cin >> a >> b;
vector<ui> vec(n);
for (ui j = 0; j < n; j++) {
vec[j] = nextRand32();
}
lsd(vec);
unsigned long long summ = 0;
for (ui ij = 0; ij < n; ij++) {
summ += (unsigned long long) (ij + 1) * vec[(size_t) ij];
}
cout << summ << endl;
vec.clear();
}
return 0;
}
| 20.173333 | 69 | 0.432254 |
0cd9c66e0780db9a044edb30d4d606f462b86e57 | 3,313 | cpp | C++ | src/BlockEntities/ChestEntity.cpp | planetx/MCServer | 4e119b522409af682e62ed38f4d22ddd9da40170 | [
"Apache-2.0"
] | null | null | null | src/BlockEntities/ChestEntity.cpp | planetx/MCServer | 4e119b522409af682e62ed38f4d22ddd9da40170 | [
"Apache-2.0"
] | null | null | null | src/BlockEntities/ChestEntity.cpp | planetx/MCServer | 4e119b522409af682e62ed38f4d22ddd9da40170 | [
"Apache-2.0"
] | null | null | null |
#include "Globals.h" // NOTE: MSVC stupidness requires this to be the same across all modules
#include "ChestEntity.h"
#include "../Item.h"
#include "../Entities/Player.h"
#include "../UI/Window.h"
cChestEntity::cChestEntity(int a_BlockX, int a_BlockY, int a_BlockZ, cWorld * a_World, BLOCKTYPE a_Type) :
super(a_Type, a_BlockX, a_BlockY, a_BlockZ, ContentsWidth, ContentsHeight, a_World),
m_NumActivePlayers(0)
{
}
cChestEntity::~cChestEntity()
{
cWindow * Window = GetWindow();
if (Window != nullptr)
{
Window->OwnerDestroyed();
}
}
void cChestEntity::SendTo(cClientHandle & a_Client)
{
// The chest entity doesn't need anything sent to the client when it's created / gets in the viewdistance
// All the actual handling is in the cWindow UI code that gets called when the chest is rclked
UNUSED(a_Client);
}
void cChestEntity::UsedBy(cPlayer * a_Player)
{
// If the window is not created, open it anew:
cWindow * Window = GetWindow();
if (Window == nullptr)
{
OpenNewWindow();
Window = GetWindow();
}
// Open the window for the player:
if (Window != nullptr)
{
if (a_Player->GetWindow() != Window)
{
a_Player->OpenWindow(Window);
}
}
// This is rather a hack
// Instead of marking the chunk as dirty upon chest contents change, we mark it dirty now
// We cannot properly detect contents change, but such a change doesn't happen without a player opening the chest first.
// The few false positives aren't much to worry about
int ChunkX, ChunkZ;
cChunkDef::BlockToChunk(m_PosX, m_PosZ, ChunkX, ChunkZ);
m_World->MarkChunkDirty(ChunkX, ChunkZ, true);
}
void cChestEntity::OpenNewWindow(void)
{
// TODO: cats are an obstruction
if ((GetPosY() + 1 < cChunkDef::Height) && cBlockInfo::IsSolid(GetWorld()->GetBlock(GetPosX(), GetPosY() + 1, GetPosZ())))
{
// Obstruction, don't open
return;
}
// Callback for opening together with neighbor chest:
class cOpenDouble :
public cChestCallback
{
cChestEntity * m_ThisChest;
public:
cOpenDouble(cChestEntity * a_ThisChest) :
m_ThisChest(a_ThisChest)
{
}
virtual bool Item(cChestEntity * a_Chest) override
{
if ((a_Chest->GetPosY() + 1 < cChunkDef::Height) && cBlockInfo::IsSolid(a_Chest->GetWorld()->GetBlock(a_Chest->GetPosX(), a_Chest->GetPosY() + 1, a_Chest->GetPosZ())))
{
// Obstruction, don't open
return false;
}
// The primary chest should eb the one with lesser X or Z coord:
cChestEntity * Primary = a_Chest;
cChestEntity * Secondary = m_ThisChest;
if (
(Primary->GetPosX() > Secondary->GetPosX()) ||
(Primary->GetPosZ() > Secondary->GetPosZ())
)
{
std::swap(Primary, Secondary);
}
m_ThisChest->OpenWindow(new cChestWindow(Primary, Secondary));
return false;
}
} ;
// Scan neighbors for adjacent chests:
cOpenDouble OpenDbl(this);
if (
m_World->DoWithChestAt(m_PosX - 1, m_PosY, m_PosZ, OpenDbl) ||
m_World->DoWithChestAt(m_PosX + 1, m_PosY, m_PosZ, OpenDbl) ||
m_World->DoWithChestAt(m_PosX, m_PosY, m_PosZ - 1, OpenDbl) ||
m_World->DoWithChestAt(m_PosX, m_PosY, m_PosZ + 1, OpenDbl)
)
{
// The double-chest window has been opened in the callback
return;
}
// There is no chest neighbor, open a single-chest window:
OpenWindow(new cChestWindow(this));
}
| 23.167832 | 170 | 0.689104 |