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 109 | max_stars_repo_head_hexsha stringlengths 40 40 | max_stars_repo_licenses listlengths 1 9 | max_stars_count int64 1 191k ⌀ | max_stars_repo_stars_event_min_datetime stringlengths 24 24 ⌀ | max_stars_repo_stars_event_max_datetime stringlengths 24 24 ⌀ | max_issues_repo_path stringlengths 4 269 | max_issues_repo_name stringlengths 5 116 | max_issues_repo_head_hexsha stringlengths 40 40 | max_issues_repo_licenses listlengths 1 9 | max_issues_count int64 1 48.5k ⌀ | max_issues_repo_issues_event_min_datetime stringlengths 24 24 ⌀ | max_issues_repo_issues_event_max_datetime stringlengths 24 24 ⌀ | max_forks_repo_path stringlengths 4 269 | max_forks_repo_name stringlengths 5 116 | max_forks_repo_head_hexsha stringlengths 40 40 | max_forks_repo_licenses listlengths 1 9 | max_forks_count int64 1 105k ⌀ | max_forks_repo_forks_event_min_datetime stringlengths 24 24 ⌀ | max_forks_repo_forks_event_max_datetime stringlengths 24 24 ⌀ | content stringlengths 7 1.05M | avg_line_length float64 1.21 330k | max_line_length int64 6 990k | alphanum_fraction float64 0.01 0.99 | author_id stringlengths 2 40 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
1f7d8456c5838e79e62387209e49b4c930680972 | 8,434 | cpp | C++ | examples/ex30p.cpp | ajithvallabai/mfem | 5920fbf645f328c29a9d6489f2474d989f808451 | [
"BSD-3-Clause"
] | null | null | null | examples/ex30p.cpp | ajithvallabai/mfem | 5920fbf645f328c29a9d6489f2474d989f808451 | [
"BSD-3-Clause"
] | null | null | null | examples/ex30p.cpp | ajithvallabai/mfem | 5920fbf645f328c29a9d6489f2474d989f808451 | [
"BSD-3-Clause"
] | 1 | 2019-07-09T20:41:56.000Z | 2019-07-09T20:41:56.000Z | // MFEM Example 30 - Parallel Version
//
// Compile with: make ex30p
//
// Sample runs: mpirun -np 4 ex30p -m ../data/square-disc.mesh -o 1
// mpirun -np 4 ex30p -m ../data/square-disc.mesh -o 2
// mpirun -np 4 ex30p -m ../data/square-disc.mesh -o 2 -me 1e3
// mpirun -np 4 ex30p -m ../data/square-disc-nurbs.mesh -o 2
// mpirun -np 4 ex30p -m ../data/star.mesh -o 2 -eo 4
// mpirun -np 4 oscp -m ../data/fichera.mesh -o 2 -me 1e4
// mpirun -np 4 ex30p -m ../data/disc-nurbs.mesh -o 2
// mpirun -np 4 ex30p -m ../data/ball-nurbs.mesh -o 2 -eo 3 -e 1e-2
// mpirun -np 4 ex30p -m ../data/star-surf.mesh -o 2
// mpirun -np 4 ex30p -m ../data/square-disc-surf.mesh -o 2
// mpirun -np 4 ex30p -m ../data/amr-quad.mesh -l 2
//
// Description: This is an example of adaptive mesh refinement preprocessing
// which lowers the data oscillation [1] to a user-defined
// relative threshold. There is no PDE being solved.
//
// MFEM's capability to work with both conforming and
// nonconforming meshes is demonstrated in example 6. In some
// problems, the material data or loading data is not sufficiently
// resolved on the initial mesh. This missing fine scale data
// reduces the accuracy of the solution as well as the accuracy
// of some local error estimators. By preprocessing the mesh
// before solving the PDE, many issues can be avoided.
//
// [1] Morin, P., Nochetto, R. H., & Siebert, K. G. (2000).
// Data oscillation and convergence of adaptive FEM. SIAM
// Journal on Numerical Analysis, 38(2), 466-488.
//
// [2] Mitchell, W. F. (2013). A collection of 2D elliptic
// problems for testing adaptive grid refinement algorithms.
// Applied mathematics and computation, 220, 350-364.
#include "mfem.hpp"
#include <fstream>
#include <iostream>
using namespace std;
using namespace mfem;
// Piecewise-affine function which is sometimes mesh-conforming
double affine_function(const Vector &p)
{
double x = p(0), y = p(1);
if (x < 0.0)
{
return 1.0 + x + y;
}
else
{
return 1.0;
}
}
// Piecewise-constant function which is never mesh-conforming
double jump_function(const Vector &p)
{
if (p.Normlp(2.0) > 0.4 && p.Normlp(2.0) < 0.6) { return 1.0; }
return 5.0;
}
// Singular function derived from the Laplacian of the "steep wavefront"
// problem in [2].
double singular_function(const Vector &p)
{
double x = p(0), y = p(1);
double alpha = 1000.0;
double xc = 0.75, yc = 0.5;
double r0 = 0.7;
double r = sqrt(pow(x - xc,2.0) + pow(y - yc,2.0));
double num = - ( alpha - pow(alpha,3) * (pow(r,2) - pow(r0,2)) );
double denom = pow(r * ( pow(alpha,2) * pow(r0,2) + pow(alpha,2) * pow(r,2) \
- 2 * pow(alpha,2) * r0 * r + 1.0 ),2);
denom = max(denom,1e-8);
return num / denom;
}
int main(int argc, char *argv[])
{
// 0. Initialize MPI.
int num_procs, myid;
MPI_Init(&argc, &argv);
MPI_Comm_size(MPI_COMM_WORLD, &num_procs);
MPI_Comm_rank(MPI_COMM_WORLD, &myid);
// 1. Parse command-line options.
const char *mesh_file = "../data/star.mesh";
int order = 1;
int nc_limit = 1;
int max_elems = 1e5;
double double_max_elems = double(max_elems);
bool visualization = true;
bool nc_simplices = true;
double osc_threshold = 1e-3;
int enriched_order = 5;
OptionsParser args(argc, argv);
args.AddOption(&mesh_file, "-m", "--mesh",
"Mesh file to use.");
args.AddOption(&order, "-o", "--order",
"Finite element order (polynomial degree).");
args.AddOption(&nc_limit, "-l", "--nc-limit",
"Maximum level of hanging nodes.");
args.AddOption(&double_max_elems, "-me", "--max-elems",
"Stop after reaching this many elements.");
args.AddOption(&visualization, "-vis", "--visualization", "-no-vis",
"--no-visualization",
"Enable or disable GLVis visualization.");
args.AddOption(&osc_threshold, "-e", "--error",
"relative data oscillation threshold.");
args.AddOption(&enriched_order, "-eo", "--enriched_order",
"Enriched quadrature order.");
args.AddOption(&nc_simplices, "-ns", "--nonconforming-simplices",
"-cs", "--conforming-simplices",
"For simplicial meshes, enable/disable nonconforming"
" refinement");
args.Parse();
if (!args.Good())
{
if (myid == 0)
{
args.PrintUsage(cout);
}
MPI_Finalize();
return 1;
}
if (myid == 0)
{
args.PrintOptions(cout);
}
max_elems = int(double_max_elems);
Mesh mesh(mesh_file, 1, 1);
// 2. Since a NURBS mesh can currently only be refined uniformly, we need to
// convert it to a piecewise-polynomial curved mesh. First we refine the
// NURBS mesh a bit more and then project the curvature to quadratic Nodes.
if (mesh.NURBSext)
{
for (int i = 0; i < 2; i++)
{
mesh.UniformRefinement();
}
mesh.SetCurvature(2);
}
// 3. Make sure the mesh is in the non-conforming mode to enable local
// refinement of quadrilaterals/hexahedra. Simplices can be refined
// either in conforming or in non-conforming mode. The conforming
// mode however does not support dynamic partitioning.
mesh.EnsureNCMesh(nc_simplices);
// 4. Define a parallel mesh by partitioning the serial mesh.
// Once the parallel mesh is defined, the serial mesh can be deleted.
ParMesh pmesh(MPI_COMM_WORLD, mesh);
mesh.Clear();
// 5. Define functions and refiner.
FunctionCoefficient affine_coeff(affine_function);
FunctionCoefficient jump_coeff(jump_function);
FunctionCoefficient singular_coeff(singular_function);
CoefficientRefiner coeffrefiner(affine_coeff,order);
// 6. Connect to GLVis.
char vishost[] = "localhost";
int visport = 19916;
socketstream sol_sock;
if (visualization)
{
sol_sock.open(vishost, visport);
}
// 7. Define custom integration rule (optional).
const IntegrationRule *irs[Geometry::NumGeom];
int order_quad = 2*order + enriched_order;
for (int i=0; i < Geometry::NumGeom; ++i)
{
irs[i] = &(IntRules.Get(i, order_quad));
}
// 8. Apply custom refiner settings.
coeffrefiner.SetIntRule(irs);
coeffrefiner.SetMaxElements(max_elems);
coeffrefiner.SetThreshold(osc_threshold);
coeffrefiner.SetNCLimit(nc_limit);
coeffrefiner.PrintWarnings();
// 9. Preprocess mesh to control osc (piecewise-affine function).
// This is mostly just a verification check. The oscillation should
// be zero if the function is mesh-conforming and order > 0.
coeffrefiner.PreprocessMesh(pmesh);
int globalNE = pmesh.GetGlobalNE();
double osc = coeffrefiner.GetOsc();
if (myid == 0)
{
mfem::out << "\n";
mfem::out << "Function 0 (affine) \n";
mfem::out << "Number of Elements " << globalNE << "\n";
mfem::out << "Osc error " << osc << "\n";
}
// 10. Preprocess mesh to control osc (jump function).
coeffrefiner.ResetCoefficient(jump_coeff);
coeffrefiner.PreprocessMesh(pmesh);
globalNE = pmesh.GetGlobalNE();
osc = coeffrefiner.GetOsc();
if (myid == 0)
{
mfem::out << "\n";
mfem::out << "Function 1 (discontinuous) \n";
mfem::out << "Number of Elements " << globalNE << "\n";
mfem::out << "Osc error " << osc << "\n";
}
// 11. Preprocess mesh to control osc (singular function).
coeffrefiner.ResetCoefficient(singular_coeff);
coeffrefiner.PreprocessMesh(pmesh);
globalNE = pmesh.GetGlobalNE();
osc = coeffrefiner.GetOsc();
if (myid == 0)
{
mfem::out << "\n";
mfem::out << "Function 2 (singular) \n";
mfem::out << "Number of Elements " << globalNE << "\n";
mfem::out << "Osc error " << osc << "\n";
}
sol_sock.precision(8);
sol_sock << "parallel " << num_procs << " " << myid << "\n";
sol_sock << "mesh\n" << pmesh << flush;
MPI_Finalize();
return 0;
}
| 34.85124 | 81 | 0.600901 | ajithvallabai |
1f84165a95592b9dcb4054bcf07a11a16389cc2b | 3,590 | cpp | C++ | src/scenes/SFPC/yosukeJohnWhitneyMatrix/yosukeJohnWhitneyMatrix.cpp | roymacdonald/ReCoded | 3bcb3d579cdd17381e54a508a1e4ef9e3d5bc4f1 | [
"MIT"
] | 64 | 2017-06-12T19:24:08.000Z | 2022-01-27T19:14:48.000Z | src/scenes/yosukeJohnWhitneyMatrix/yosukeJohnWhitneyMatrix.cpp | colaplate/recoded | 934e1184c7502d192435c406e56b8a2106e9b6b4 | [
"MIT"
] | 10 | 2017-06-13T10:38:39.000Z | 2017-11-15T11:21:05.000Z | src/scenes/yosukeJohnWhitneyMatrix/yosukeJohnWhitneyMatrix.cpp | colaplate/recoded | 934e1184c7502d192435c406e56b8a2106e9b6b4 | [
"MIT"
] | 24 | 2017-06-11T08:14:46.000Z | 2020-04-16T20:28:46.000Z |
#include "yosukeJohnWhitneyMatrix.h"
void yosukeJohnWhitneyMatrix::setup(){
// setup pramaters
numOfGroup.set("number-of-group", 4, 1, MAXNUMOFGROPU);
parameters.add(numOfGroup);
numOfBall.set("number-of-ball", 6, 1, MAXNUMOFBALL);
parameters.add(numOfBall);
radius.set("rotation-radius", 150, 1, 1000 );
parameters.add(radius);
speed.set("speed", 0.1, 0.0, 1.0 );
parameters.add(speed);
ballRadius.set("ball-radius", 4, 0, 10);
parameters.add(ballRadius);
setAuthor("Yosuke Sakai");
setOriginalArtist("John Whitney");
loadCode("scenes/yosukeJohnWhitneyMatrix/exampleCode.cpp");
//ofSetVerticalSync(true);
//ofBackground(0,0,0);
ofSetCircleResolution(150);
//transform the origin to the center of the screen.
xorigin = dimensions.width/2.0;
yorigin = dimensions.height/2.0;
//the radius of the lissajus
//radius = ;
//set the initial positon of the ball
for (int j=0; j<numOfGroup; j++) {
for (int i = 0; i < numOfBall; i++) {
t = ofGetElapsedTimef() / 10.0;
angleofangle[j][i] = - (i-1)*PI/15;
if(j==0 || j==1){
angle[j][i] = 5.0*sin((t-0.1) * PI/2.0 - PI/2.0) + 3.0*angleofangle[j][i];
} else {
angle[j][i] = 5.0*sin((t-0.1) * PI/2.0 - PI/2.0) + 3.0*angleofangle[j][i];
}
x[j][i] = xorigin + radius * sin(angle[j][i] * 1.0);
y[j][i] = yorigin + radius * -sin(angle[j][i] * 1.5);
}
}
lastTime = 0;
integratedTime = 0;
}
void yosukeJohnWhitneyMatrix::reset() {
lastTime = 0;
integratedTime = 0;
}
void yosukeJohnWhitneyMatrix::update(){
float now = getElapsedTimef();
if (lastTime == 0) {
lastTime = now;
}
float dt = now - lastTime;
lastTime = now;
integratedTime += dt * speed;
t = integratedTime;
for (int j=0; j<numOfGroup; j++) {
for (int i = 0; i < numOfBall; i++) {
angleofangle[j][i] = - (i-1)*PI/20; //the argument of sin
if(j==0 || j==1){
angle[j][i] = (5.0*sin((t-0.1) * PI/2.0 - PI/2.0) + 3.0*angleofangle[j][i]);
} else {
angle[j][i] = (5.0*sin((t-0.1) * PI/2.0 - PI/2.0) + 3.0*angleofangle[j][i]);
}
}
}
}
void yosukeJohnWhitneyMatrix::draw(){
for (int j=0; j<numOfGroup; j++) {
for (int i = 0; i < numOfBall; i++) {
if(j==0){
x[j][i] = xorigin + radius * -sin(1.0 * (angle[j][i] - PI/2.0));
y[j][i] = yorigin + radius * sin(1.5 * (angle[j][i] - PI/2.0));
} else if(j==1){
x[j][i] = xorigin + radius * sin(1.0 * (angle[j][i] - PI/2.0));
y[j][i] = yorigin + radius * sin(1.5 * (angle[j][i] - PI/2.0));
} else if(j==2){
x[j][i] = xorigin + radius * cos(1.0 * (angle[j][i] - PI/4.5));
y[j][i] = yorigin + radius * cos(1.5 * (angle[j][i] - PI/4.5));
} else {
x[j][i] = xorigin + radius * -cos(1.0 * (angle[j][i] - PI/4.5));
y[j][i] = yorigin + radius * cos(1.5 * (angle[j][i] - PI/4.5));
}
}
}
ofSetRectMode(OF_RECTMODE_CENTER);
ofSetColor(255);
ofFill();
for (int j=0; j<numOfGroup; j++) {
for (int i = 0; i < numOfBall; i++) {
ofDrawCircle(x[j][i], y[j][i], ballRadius);
}
}
}
| 29.916667 | 92 | 0.479109 | roymacdonald |
1f84cb7fd11acc3baba1edb3272eb6c8a9146224 | 740 | hpp | C++ | libs/renderer/include/Renderer.hpp | Sharpyfile/WARdrobe | 7842d486f65c7a045771f9ef78c0655eda2d346a | [
"DOC"
] | null | null | null | libs/renderer/include/Renderer.hpp | Sharpyfile/WARdrobe | 7842d486f65c7a045771f9ef78c0655eda2d346a | [
"DOC"
] | null | null | null | libs/renderer/include/Renderer.hpp | Sharpyfile/WARdrobe | 7842d486f65c7a045771f9ef78c0655eda2d346a | [
"DOC"
] | 1 | 2021-03-21T16:52:22.000Z | 2021-03-21T16:52:22.000Z | #pragma once
#include "Camera.hpp"
#include "Model.hpp"
#include "Shader.hpp"
#include "Skybox.hpp"
#include "glm/gtc/type_ptr.hpp"
#include "glm/glm.hpp"
class Renderer
{
public:
Renderer();
Renderer(unsigned int);
Renderer(bool, float[], int, unsigned int[], int, std::string);
void
Draw(Shader*, Model*, Camera*, glm::vec3, glm::vec3, glm::vec3, int, int);
void
DrawToShadowMap(Shader*, Model*, glm::vec3, glm::vec3, glm::vec3);
void Draw(Shader *);
void DrawRefractiveObject(Shader*, Model*, Camera*, Skybox* , glm::vec3, glm::vec3, glm::vec3, int, int);
void DrawSkybox(Shader*, Skybox*, Camera*, int, int);
void Init();
unsigned int drawingType;
glm::vec3 newColor = glm::vec3(1.0f, 1.0f, 1.0f);
private:
}; | 25.517241 | 106 | 0.674324 | Sharpyfile |
1f90d9fb6690212280330dcb10894212c38a3465 | 4,338 | cpp | C++ | src/algorithm/IsomorphSpace.cpp | ehzawad/HyperGraphLib | a1424437a01ad5a9e0efa71d723d32fd58ca589c | [
"MIT"
] | 22 | 2016-05-25T06:25:14.000Z | 2022-01-12T09:15:38.000Z | src/algorithm/IsomorphSpace.cpp | ehzawad/HyperGraphLib | a1424437a01ad5a9e0efa71d723d32fd58ca589c | [
"MIT"
] | 12 | 2016-05-08T15:02:48.000Z | 2021-03-24T07:25:19.000Z | src/algorithm/IsomorphSpace.cpp | ehzawad/HyperGraphLib | a1424437a01ad5a9e0efa71d723d32fd58ca589c | [
"MIT"
] | 6 | 2017-02-12T23:12:07.000Z | 2021-06-28T06:34:55.000Z | /*
* MIT License
*
* Copyright (c) 2015 Alexis LE GOADEC
*
* 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 "include/IsomorphSpace.hh"
#include <iostream>
#include <gecode/driver.hh>
#include <gecode/minimodel.hh>
IsomorphSpace::IsomorphSpace(
const boost::shared_ptr<HypergrapheAbstrait>& ptrHypergrapheAbstraitA,
const boost::shared_ptr<HypergrapheAbstrait>& ptrHypergrapheAbstraitB) :
_varEdge(
*this,
ptrHypergrapheAbstraitA->getHyperEdgeList().size() * ptrHypergrapheAbstraitA->getHyperVertexList().size() + 1,
0,
ptrHypergrapheAbstraitA->getHyperEdgeList().size() * ptrHypergrapheAbstraitA->getHyperVertexList().size()
),
_bVarEdge(
*this,
ptrHypergrapheAbstraitA->getHyperEdgeList().size() * ptrHypergrapheAbstraitA->getHyperVertexList().size() + 1,
0,
ptrHypergrapheAbstraitA->getHyperEdgeList().size() * ptrHypergrapheAbstraitA->getHyperVertexList().size()
),
_bVarEdge2(
*this,
ptrHypergrapheAbstraitA->getHyperEdgeList().size() * ptrHypergrapheAbstraitA->getHyperVertexList().size() + 1,
0,
ptrHypergrapheAbstraitA->getHyperEdgeList().size() * ptrHypergrapheAbstraitA->getHyperVertexList().size()
),
_ptrHypergrapheA (ptrHypergrapheAbstraitA),
_ptrHypergrapheB (ptrHypergrapheAbstraitB) {
}
void
IsomorphSpace::postConstraints() {
LibType::ListHyperVertex vertexA( _ptrHypergrapheA->getHyperVertexList() );
LibType::ListHyperEdge edgeA ( _ptrHypergrapheA->getHyperEdgeList() );
LibType::ListHyperVertex vertexB( _ptrHypergrapheB->getHyperVertexList() );
LibType::ListHyperEdge edgeB ( _ptrHypergrapheB->getHyperEdgeList() );
int j( 1 );
for(boost::shared_ptr<HyperEdge>& e : edgeA ) {
for(boost::shared_ptr<HyperVertex>& v : vertexA ) {
if( e->containVertex(v) ) {
Gecode::rel(*this, _bVarEdge[ j ], Gecode::IRT_EQ, j);
} else {
Gecode::rel(*this, _bVarEdge[ j ], Gecode::IRT_EQ, 0);
}
j++;
}
}
j = 1;
for(boost::shared_ptr<HyperEdge>& e : edgeB ) {
for(boost::shared_ptr<HyperVertex>& v : vertexB ) {
if( e->containVertex(v) ) {
Gecode::rel(*this, _bVarEdge2[ j ], Gecode::IRT_EQ, j);
} else {
Gecode::rel(*this, _bVarEdge2[ j ], Gecode::IRT_EQ, 0);
}
j++;
}
}
int u( 0 );
for(int g=0; g < edgeA.size(); g++) {
for(int h=0; h < vertexA.size(); h++) {
Gecode::element(*this, _bVarEdge, _varEdge[u], _bVarEdge2[u]);
u++;
}
}
Gecode::distinct(*this, _varEdge );
Gecode::branch(*this, _varEdge, Gecode::INT_VAR_SIZE_MIN(), Gecode::INT_VAL_SPLIT_MIN());
}
#if GECODE_VERSION_NUMBER > 500100
Gecode::Space*
IsomorphSpace::copy() {
return new IsomorphSpace(*this);
}
IsomorphSpace::IsomorphSpace(IsomorphSpace& p) :
Gecode::Space(p) {
_varEdge.update(*this, p._varEdge);
}
#else
Gecode::Space*
IsomorphSpace::copy(bool share) {
return new IsomorphSpace(share, *this);
}
IsomorphSpace::IsomorphSpace(bool share, IsomorphSpace& p) :
Gecode::Space(share, p) {
_varEdge.update(*this, share, p._varEdge);
}
#endif
| 33.114504 | 118 | 0.665514 | ehzawad |
1f9ab6767cb247484030b35aa5911d7aab15c084 | 777 | cpp | C++ | bolt/server/src/mhttppost.cpp | gamunu/bolt | c1a2956f02656f3ec2c244486a816337126905ae | [
"Apache-2.0"
] | 1 | 2022-03-06T09:23:56.000Z | 2022-03-06T09:23:56.000Z | bolt/server/src/mhttppost.cpp | gamunu/bolt | c1a2956f02656f3ec2c244486a816337126905ae | [
"Apache-2.0"
] | 3 | 2021-04-23T18:12:20.000Z | 2021-04-23T18:12:47.000Z | bolt/server/src/mhttppost.cpp | gamunu/bolt | c1a2956f02656f3ec2c244486a816337126905ae | [
"Apache-2.0"
] | null | null | null | #include<mhttppost.hpp>
#include<regex>
#include<boost/scoped_ptr.hpp>
#include <mysql_table.h>
#include <metadata.hpp>
using namespace std;
using namespace bolt::storage::mysql;
json::value MHttpPost::createTable(json::value object)
{
//TODO:Check if we are in windows or unix
wregex name_regx(U("^[A-Za-z][A-Za-z0-9]{2,62}$"));
json::value table_metadata;
if (!object.is_null())
{
if (object.has_field(U("TableName")))
{
auto iter = object.as_object().find(U("TableName"));
string_t tableName = iter->second.as_string();
if (regex_match(tableName, name_regx))
{
MysqlTable table = MysqlTable();
if (table.createTable(tableName))
{
table_metadata = Metadata::getMysqlTable(tableName);
}
}
}
}
return table_metadata;
} | 22.2 | 57 | 0.680824 | gamunu |
1f9b955121445f1fb7046fb0d6d4ddf4552fdfc2 | 1,570 | cc | C++ | gcc-gcc-7_3_0-release/libstdc++-v3/testsuite/22_locale/money_get/get/char/39168.cc | best08618/asylo | 5a520a9f5c461ede0f32acc284017b737a43898c | [
"Apache-2.0"
] | 7 | 2020-05-02T17:34:05.000Z | 2021-10-17T10:15:18.000Z | gcc-gcc-7_3_0-release/libstdc++-v3/testsuite/22_locale/money_get/get/char/39168.cc | best08618/asylo | 5a520a9f5c461ede0f32acc284017b737a43898c | [
"Apache-2.0"
] | null | null | null | gcc-gcc-7_3_0-release/libstdc++-v3/testsuite/22_locale/money_get/get/char/39168.cc | best08618/asylo | 5a520a9f5c461ede0f32acc284017b737a43898c | [
"Apache-2.0"
] | 2 | 2020-07-27T00:22:36.000Z | 2021-04-01T09:41:02.000Z | // Copyright (C) 2009-2017 Free Software Foundation, Inc.
//
// This file is part of the GNU ISO C++ Library. This library is free
// software; you can redistribute it and/or modify it under the
// terms of the GNU General Public License as published by the
// Free Software Foundation; either version 3, or (at your option)
// any later version.
// This library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
// You should have received a copy of the GNU General Public License along
// with this library; see the file COPYING3. If not see
// <http://www.gnu.org/licenses/>.
// 22.2.6.1.1 money_get members
#include <sstream>
#include <locale>
#include <climits>
#include <testsuite_hooks.h>
class my_moneypunct: public std::moneypunct<char>
{
protected:
std::string do_grouping() const { return std::string(1, CHAR_MAX); }
};
// libstdc++/39168
void test01()
{
using namespace std;
typedef istreambuf_iterator<char> iterator_type;
istringstream iss;
iss.imbue(locale(iss.getloc(), new my_moneypunct));
const money_get<char>& mg = use_facet<money_get<char> >(iss.getloc());
string digits;
ios_base::iostate err = ios_base::goodbit;
iss.str("123,456");
iterator_type end = mg.get(iss.rdbuf(), 0, false, iss, err, digits);
VERIFY( err == ios_base::goodbit );
VERIFY( digits == "123" );
VERIFY( *end == ',' );
}
int main()
{
test01();
return 0;
}
| 28.035714 | 74 | 0.708917 | best08618 |
1f9ceca10c7920f9b0c1b921829cf18a9ee37b75 | 16,916 | cpp | C++ | wxWidgets-2.9.1/src/osx/carbon/combobox.cpp | gamekit-developers/gamekit | 74c896af5826ebe8fb72f2911015738f38ab7bb2 | [
"Zlib",
"MIT"
] | 241 | 2015-01-04T00:36:58.000Z | 2022-01-06T19:19:23.000Z | wxWidgets-2.9.1/src/osx/carbon/combobox.cpp | gamekit-developers/gamekit | 74c896af5826ebe8fb72f2911015738f38ab7bb2 | [
"Zlib",
"MIT"
] | 10 | 2015-07-10T18:27:17.000Z | 2019-06-26T20:59:59.000Z | wxWidgets-2.9.1/src/osx/carbon/combobox.cpp | gamekit-developers/gamekit | 74c896af5826ebe8fb72f2911015738f38ab7bb2 | [
"Zlib",
"MIT"
] | 82 | 2015-01-25T18:02:35.000Z | 2022-03-05T12:28:17.000Z | /////////////////////////////////////////////////////////////////////////////
// Name: src/osx/carbon/combobox.cpp
// Purpose: wxComboBox class
// Author: Stefan Csomor, Dan "Bud" Keith (composite combobox)
// Modified by:
// Created: 1998-01-01
// RCS-ID: $Id$
// Copyright: (c) Stefan Csomor
// Licence: wxWindows licence
/////////////////////////////////////////////////////////////////////////////
#include "wx/wxprec.h"
#if wxUSE_COMBOBOX && wxOSX_USE_CARBON
#include "wx/combobox.h"
#ifndef WX_PRECOMP
#include "wx/button.h"
#include "wx/menu.h"
#include "wx/containr.h"
#include "wx/toplevel.h"
#include "wx/textctrl.h"
#endif
#include "wx/osx/private.h"
IMPLEMENT_DYNAMIC_CLASS(wxComboBox, wxControl)
WX_DELEGATE_TO_CONTROL_CONTAINER(wxComboBox, wxControl)
BEGIN_EVENT_TABLE(wxComboBox, wxControl)
WX_EVENT_TABLE_CONTROL_CONTAINER(wxComboBox)
END_EVENT_TABLE()
// ----------------------------------------------------------------------------
// constants
// ----------------------------------------------------------------------------
// the margin between the text control and the choice
// margin should be bigger on OS X due to blue highlight
// around text control.
static const wxCoord MARGIN = 4;
// this is the border a focus rect on OSX is needing
static const int TEXTFOCUSBORDER = 3 ;
// ----------------------------------------------------------------------------
// wxComboBoxText: text control forwards events to combobox
// ----------------------------------------------------------------------------
class wxComboBoxText : public wxTextCtrl
{
public:
wxComboBoxText( wxComboBox * cb )
: wxTextCtrl( cb , 1 )
{
m_cb = cb;
}
protected:
void OnChar( wxKeyEvent& event )
{
// Allows processing the tab key to go to the next control
if (event.GetKeyCode() == WXK_TAB)
{
wxNavigationKeyEvent NavEvent;
NavEvent.SetEventObject(this);
NavEvent.SetDirection(true);
NavEvent.SetWindowChange(false);
// Get the parent of the combo and have it process the navigation?
if (m_cb->GetParent()->HandleWindowEvent(NavEvent))
return;
}
// send the event to the combobox class in case the user has bound EVT_CHAR
wxKeyEvent kevt(event);
kevt.SetEventObject(m_cb);
if (m_cb->HandleWindowEvent(kevt))
// If the event was handled and not skipped then we're done
return;
if ( event.GetKeyCode() == WXK_RETURN )
{
wxCommandEvent event(wxEVT_COMMAND_TEXT_ENTER, m_cb->GetId());
event.SetString( GetValue() );
event.SetInt( m_cb->GetSelection() );
event.SetEventObject( m_cb );
// This will invoke the dialog default action,
// such as the clicking the default button.
if (!m_cb->HandleWindowEvent( event ))
{
wxTopLevelWindow *tlw = wxDynamicCast(wxGetTopLevelParent(this), wxTopLevelWindow);
if ( tlw && tlw->GetDefaultItem() )
{
wxButton *def = wxDynamicCast(tlw->GetDefaultItem(), wxButton);
if ( def && def->IsEnabled() )
{
wxCommandEvent event( wxEVT_COMMAND_BUTTON_CLICKED, def->GetId() );
event.SetEventObject(def);
def->Command(event);
}
}
return;
}
}
event.Skip();
}
void OnKeyUp( wxKeyEvent& event )
{
event.SetEventObject(m_cb);
event.SetId(m_cb->GetId());
if (! m_cb->HandleWindowEvent(event))
event.Skip();
}
void OnKeyDown( wxKeyEvent& event )
{
event.SetEventObject(m_cb);
event.SetId(m_cb->GetId());
if (! m_cb->HandleWindowEvent(event))
event.Skip();
}
void OnText( wxCommandEvent& event )
{
event.SetEventObject(m_cb);
event.SetId(m_cb->GetId());
if (! m_cb->HandleWindowEvent(event))
event.Skip();
}
void OnFocus( wxFocusEvent& event )
{
// in case the textcontrol gets the focus we propagate
// it to the parent's handlers.
wxFocusEvent evt2(event.GetEventType(),m_cb->GetId());
evt2.SetEventObject(m_cb);
m_cb->GetEventHandler()->ProcessEvent(evt2);
event.Skip();
}
private:
wxComboBox *m_cb;
DECLARE_EVENT_TABLE()
};
BEGIN_EVENT_TABLE(wxComboBoxText, wxTextCtrl)
EVT_KEY_DOWN(wxComboBoxText::OnKeyDown)
EVT_CHAR(wxComboBoxText::OnChar)
EVT_KEY_UP(wxComboBoxText::OnKeyUp)
EVT_SET_FOCUS(wxComboBoxText::OnFocus)
EVT_KILL_FOCUS(wxComboBoxText::OnFocus)
EVT_TEXT(wxID_ANY, wxComboBoxText::OnText)
END_EVENT_TABLE()
class wxComboBoxChoice : public wxChoice
{
public:
wxComboBoxChoice( wxComboBox *cb, int style )
: wxChoice( cb , 1 , wxDefaultPosition , wxDefaultSize , 0 , NULL , style & (wxCB_SORT) )
{
m_cb = cb;
}
int GetPopupWidth() const
{
switch ( GetWindowVariant() )
{
case wxWINDOW_VARIANT_NORMAL :
case wxWINDOW_VARIANT_LARGE :
return 24 ;
default :
return 21 ;
}
}
protected:
void OnChoice( wxCommandEvent& e )
{
wxString s = e.GetString();
m_cb->DelegateChoice( s );
wxCommandEvent event2(wxEVT_COMMAND_COMBOBOX_SELECTED, m_cb->GetId() );
event2.SetInt(m_cb->GetSelection());
event2.SetEventObject(m_cb);
event2.SetString(m_cb->GetStringSelection());
m_cb->ProcessCommand(event2);
// For consistency with MSW and GTK, also send a text updated event
// After all, the text is updated when a selection is made
wxCommandEvent TextEvent( wxEVT_COMMAND_TEXT_UPDATED, m_cb->GetId() );
TextEvent.SetString( m_cb->GetStringSelection() );
TextEvent.SetEventObject( m_cb );
m_cb->ProcessCommand( TextEvent );
}
virtual wxSize DoGetBestSize() const
{
wxSize sz = wxChoice::DoGetBestSize() ;
if (! m_cb->HasFlag(wxCB_READONLY) )
sz.x = GetPopupWidth() ;
return sz ;
}
private:
wxComboBox *m_cb;
friend class wxComboBox;
DECLARE_EVENT_TABLE()
};
BEGIN_EVENT_TABLE(wxComboBoxChoice, wxChoice)
EVT_CHOICE(wxID_ANY, wxComboBoxChoice::OnChoice)
END_EVENT_TABLE()
wxComboBox::~wxComboBox()
{
// delete the controls now, don't leave them alive even though they would
// still be eventually deleted by our parent - but it will be too late, the
// user code expects them to be gone now
wxDELETE(m_text);
wxDELETE(m_choice);
}
// ----------------------------------------------------------------------------
// geometry
// ----------------------------------------------------------------------------
wxSize wxComboBox::DoGetBestSize() const
{
if (!m_choice && !m_text)
return GetSize();
wxSize size = m_choice->GetBestSize();
if ( m_text != NULL )
{
wxSize sizeText = m_text->GetBestSize();
if (sizeText.y + 2 * TEXTFOCUSBORDER > size.y)
size.y = sizeText.y + 2 * TEXTFOCUSBORDER;
size.x = m_choice->GetPopupWidth() + sizeText.x + MARGIN;
size.x += TEXTFOCUSBORDER ;
}
else
{
// clipping is too tight
size.y += 1 ;
}
return size;
}
void wxComboBox::DoMoveWindow(int x, int y, int width, int height)
{
wxControl::DoMoveWindow( x, y, width , height );
if ( m_text == NULL )
{
// we might not be fully constructed yet, therefore watch out...
if ( m_choice )
m_choice->SetSize(0, 0 , width, -1);
}
else
{
wxCoord wText = width - m_choice->GetPopupWidth() - MARGIN;
m_text->SetSize(TEXTFOCUSBORDER, TEXTFOCUSBORDER, wText, -1);
wxSize tSize = m_text->GetSize();
wxSize cSize = m_choice->GetSize();
int yOffset = ( tSize.y + 2 * TEXTFOCUSBORDER - cSize.y ) / 2;
// put it at an inset of 1 to have outer area shadows drawn as well
m_choice->SetSize(TEXTFOCUSBORDER + wText + MARGIN - 1 , yOffset, m_choice->GetPopupWidth() , -1);
}
}
// ----------------------------------------------------------------------------
// operations forwarded to the subcontrols
// ----------------------------------------------------------------------------
bool wxComboBox::Enable(bool enable)
{
if ( !wxControl::Enable(enable) )
return false;
if (m_text)
m_text->Enable(enable);
return true;
}
bool wxComboBox::Show(bool show)
{
if ( !wxControl::Show(show) )
return false;
return true;
}
void wxComboBox::DelegateTextChanged( const wxString& value )
{
SetStringSelection( value );
}
void wxComboBox::DelegateChoice( const wxString& value )
{
SetStringSelection( value );
}
void wxComboBox::Init()
{
WX_INIT_CONTROL_CONTAINER();
}
bool wxComboBox::Create(wxWindow *parent,
wxWindowID id,
const wxString& value,
const wxPoint& pos,
const wxSize& size,
const wxArrayString& choices,
long style,
const wxValidator& validator,
const wxString& name)
{
if ( !Create( parent, id, value, pos, size, 0, NULL,
style, validator, name ) )
return false;
Append(choices);
return true;
}
bool wxComboBox::Create(wxWindow *parent,
wxWindowID id,
const wxString& value,
const wxPoint& pos,
const wxSize& size,
int n,
const wxString choices[],
long style,
const wxValidator& validator,
const wxString& name)
{
if ( !wxControl::Create(parent, id, wxDefaultPosition, wxDefaultSize, style ,
validator, name) )
{
return false;
}
wxSize csize = size;
if ( style & wxCB_READONLY )
{
m_text = NULL;
}
else
{
m_text = new wxComboBoxText(this);
if ( size.y == -1 )
{
csize.y = m_text->GetSize().y ;
csize.y += 2 * TEXTFOCUSBORDER ;
}
}
m_choice = new wxComboBoxChoice(this, style );
DoSetSize(pos.x, pos.y, csize.x, csize.y);
Append( n, choices );
// Needed because it is a wxControlWithItems
SetInitialSize(size);
SetStringSelection(value);
return true;
}
void wxComboBox::EnableTextChangedEvents(bool enable)
{
if ( m_text )
m_text->ForwardEnableTextChangedEvents(enable);
}
wxString wxComboBox::DoGetValue() const
{
wxCHECK_MSG( m_text, wxString(), "can't be called for read-only combobox" );
return m_text->GetValue();
}
wxString wxComboBox::GetValue() const
{
wxString result;
if ( m_text == NULL )
result = m_choice->GetString( m_choice->GetSelection() );
else
result = m_text->GetValue();
return result;
}
unsigned int wxComboBox::GetCount() const
{
return m_choice->GetCount() ;
}
void wxComboBox::SetValue(const wxString& value)
{
if ( HasFlag(wxCB_READONLY) )
SetStringSelection( value ) ;
else
m_text->SetValue( value );
}
void wxComboBox::WriteText(const wxString& text)
{
m_text->WriteText(text);
}
void wxComboBox::GetSelection(long *from, long *to) const
{
m_text->GetSelection(from, to);
}
// Clipboard operations
void wxComboBox::Copy()
{
if ( m_text != NULL )
m_text->Copy();
}
void wxComboBox::Cut()
{
if ( m_text != NULL )
m_text->Cut();
}
void wxComboBox::Paste()
{
if ( m_text != NULL )
m_text->Paste();
}
void wxComboBox::SetEditable(bool editable)
{
if ( ( m_text == NULL ) && editable )
{
m_text = new wxComboBoxText( this );
}
else if ( !editable )
{
wxDELETE(m_text);
}
int currentX, currentY;
GetPosition( ¤tX, ¤tY );
int currentW, currentH;
GetSize( ¤tW, ¤tH );
DoMoveWindow( currentX, currentY, currentW, currentH );
}
void wxComboBox::SetInsertionPoint(long pos)
{
if ( m_text )
m_text->SetInsertionPoint(pos);
}
void wxComboBox::SetInsertionPointEnd()
{
if ( m_text )
m_text->SetInsertionPointEnd();
}
long wxComboBox::GetInsertionPoint() const
{
if ( m_text )
return m_text->GetInsertionPoint();
return 0;
}
wxTextPos wxComboBox::GetLastPosition() const
{
if ( m_text )
return m_text->GetLastPosition();
return 0;
}
void wxComboBox::Replace(long from, long to, const wxString& value)
{
if ( m_text )
m_text->Replace(from,to,value);
}
void wxComboBox::Remove(long from, long to)
{
if ( m_text )
m_text->Remove(from,to);
}
void wxComboBox::SetSelection(long from, long to)
{
if ( m_text )
m_text->SetSelection(from,to);
}
int wxComboBox::DoInsertItems(const wxArrayStringsAdapter& items,
unsigned int pos,
void **clientData,
wxClientDataType type)
{
return m_choice->DoInsertItems(items, pos, clientData, type);
}
void wxComboBox::DoSetItemClientData(unsigned int n, void* clientData)
{
return m_choice->DoSetItemClientData( n , clientData ) ;
}
void* wxComboBox::DoGetItemClientData(unsigned int n) const
{
return m_choice->DoGetItemClientData( n ) ;
}
wxClientDataType wxComboBox::GetClientDataType() const
{
return m_choice->GetClientDataType();
}
void wxComboBox::SetClientDataType(wxClientDataType clientDataItemsType)
{
m_choice->SetClientDataType(clientDataItemsType);
}
void wxComboBox::DoDeleteOneItem(unsigned int n)
{
m_choice->DoDeleteOneItem( n );
}
void wxComboBox::DoClear()
{
m_choice->DoClear();
}
int wxComboBox::GetSelection() const
{
return m_choice->GetSelection();
}
void wxComboBox::SetSelection(int n)
{
m_choice->SetSelection( n );
if ( m_text != NULL )
m_text->SetValue(n != wxNOT_FOUND ? GetString(n) : wxString(wxEmptyString));
}
int wxComboBox::FindString(const wxString& s, bool bCase) const
{
return m_choice->FindString( s, bCase );
}
wxString wxComboBox::GetString(unsigned int n) const
{
return m_choice->GetString( n );
}
wxString wxComboBox::GetStringSelection() const
{
int sel = GetSelection();
if (sel != wxNOT_FOUND)
return wxString(this->GetString((unsigned int)sel));
else
return wxEmptyString;
}
void wxComboBox::SetString(unsigned int n, const wxString& s)
{
m_choice->SetString( n , s );
}
bool wxComboBox::IsEditable() const
{
return m_text != NULL && !HasFlag(wxCB_READONLY);
}
void wxComboBox::Undo()
{
if (m_text != NULL)
m_text->Undo();
}
void wxComboBox::Redo()
{
if (m_text != NULL)
m_text->Redo();
}
void wxComboBox::SelectAll()
{
if (m_text != NULL)
m_text->SelectAll();
}
bool wxComboBox::CanCopy() const
{
if (m_text != NULL)
return m_text->CanCopy();
else
return false;
}
bool wxComboBox::CanCut() const
{
if (m_text != NULL)
return m_text->CanCut();
else
return false;
}
bool wxComboBox::CanPaste() const
{
if (m_text != NULL)
return m_text->CanPaste();
else
return false;
}
bool wxComboBox::CanUndo() const
{
if (m_text != NULL)
return m_text->CanUndo();
else
return false;
}
bool wxComboBox::CanRedo() const
{
if (m_text != NULL)
return m_text->CanRedo();
else
return false;
}
bool wxComboBox::OSXHandleClicked( double WXUNUSED(timestampsec) )
{
/*
For consistency with other platforms, clicking in the text area does not constitute a selection
wxCommandEvent event(wxEVT_COMMAND_COMBOBOX_SELECTED, m_windowId );
event.SetInt(GetSelection());
event.SetEventObject(this);
event.SetString(GetStringSelection());
ProcessCommand(event);
*/
return true ;
}
wxTextWidgetImpl* wxComboBox::GetTextPeer() const
{
if (m_text)
return m_text->GetTextPeer();
return NULL;
}
#endif // wxUSE_COMBOBOX && wxOSX_USE_CARBON
| 24.730994 | 107 | 0.565855 | gamekit-developers |
1f9d47ab42c6c618df449777e23c5a474dbed1ac | 4,203 | cpp | C++ | src/FresponzeListener.cpp | suirless/fresponze | 2c8f9204c8ba4b734d7885cc1fe51f31c89d22ef | [
"Apache-2.0"
] | 8 | 2020-09-26T20:38:26.000Z | 2021-05-16T18:13:48.000Z | src/FresponzeListener.cpp | Vertver/Fresponze | ca45738a2c06474fb6f45b627f8b1c8b85e69cd1 | [
"Apache-2.0"
] | 23 | 2022-01-23T04:57:32.000Z | 2022-01-23T04:59:32.000Z | src/FresponzeListener.cpp | suirless/fresponze | 2c8f9204c8ba4b734d7885cc1fe51f31c89d22ef | [
"Apache-2.0"
] | 1 | 2020-12-07T13:48:15.000Z | 2020-12-07T13:48:15.000Z | /*********************************************************************
* Copyright (C) Anton Kovalev (vertver), 2020. All rights reserved.
* Fresponze - fast, simple and modern multimedia sound library
* Apache-2 License
**********************************************************************
* 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 "FresponzeListener.h"
CMediaListener::CMediaListener(IMediaResource* pInitialResource)
{
AddRef();
pInitialResource->Clone((void**)&pLocalResource);
pLocalResource->GetFormat(ResourceFormat);
ListenerFormat = ResourceFormat;
}
CMediaListener::~CMediaListener()
{
_RELEASE(pLocalResource);
FreeStuff();
}
void
CMediaListener::FreeStuff()
{
EmittersNode* pNode = pFirstEmitter;
EmittersNode* pThisNode = nullptr;
while (pNode) {
pThisNode = pNode->pNext;
_RELEASE(pNode->pEmitter);
delete pNode;
pNode = pThisNode;
}
}
bool
CMediaListener::AddEmitter(IBaseEmitter* pNewEmitter)
{
if (!pLastEmitter) {
pFirstEmitter = new EmittersNode;
memset(pFirstEmitter, 0, sizeof(EmittersNode));
pLastEmitter = pFirstEmitter;
pNewEmitter->Clone((void**)&pLastEmitter->pEmitter);
} else {
EmittersNode* pTemp = new EmittersNode;
memset(pFirstEmitter, 0, sizeof(EmittersNode));
pNewEmitter->Clone((void**)&pTemp->pEmitter);
pLastEmitter->pNext = pTemp;
pTemp->pPrev = pLastEmitter;
pLastEmitter = pTemp;
}
return true;
}
bool
CMediaListener::DeleteEmitter(IBaseEmitter* pEmitter)
{
EmittersNode* pNode = nullptr;
GetFirstEmitter(&pNode);
while (pNode) {
if (pNode->pEmitter == pEmitter) {
pNode->pPrev->pNext = pNode->pNext;
pNode->pNext->pPrev = pNode->pPrev;
_RELEASE(pNode->pEmitter);
delete pNode;
return true;
}
}
return false;
}
bool
CMediaListener::GetFirstEmitter(EmittersNode** pFirstEmitter)
{
*pFirstEmitter = this->pFirstEmitter;
return true;
}
bool
CMediaListener::SetResource(IMediaResource* pInitialResource)
{
_RELEASE(pLocalResource);
return pInitialResource->Clone((void**)&pLocalResource);
}
fr_i32
CMediaListener::SetPosition(fr_f32 FloatPosition)
{
return SetPosition(fr_i64(((fr_f64)ResourceFormat.Frames * fabs(FloatPosition))));
}
fr_i32
CMediaListener::SetPosition(fr_i64 FramePosition)
{
fr_i64 outputFrames = 0;
CalculateFrames64(FramePosition, ListenerFormat.SampleRate, ResourceFormat.SampleRate, outputFrames);
fr_i32 ret = pLocalResource->SetPosition(outputFrames);
CalculateFrames64(ret, ResourceFormat.SampleRate, ListenerFormat.SampleRate, outputFrames);
return outputFrames;
}
fr_i64
CMediaListener::GetPosition()
{
fr_i64 outputFrames = pLocalResource->GetPosition();
CalculateFrames64(outputFrames, ResourceFormat.SampleRate, ListenerFormat.SampleRate, outputFrames);
return outputFrames;
}
fr_i32
CMediaListener::GetFullFrames()
{
fr_i64 outputFrames = 0;
CalculateFrames64(ResourceFormat.Frames, ResourceFormat.SampleRate, ListenerFormat.SampleRate, outputFrames);
return (fr_i32)outputFrames;
}
fr_i32
CMediaListener::GetFormat(PcmFormat& fmt)
{
fmt = ListenerFormat;
return 0;
}
fr_i32
CMediaListener::SetFormat(PcmFormat fmt)
{
EmittersNode* pProcessEmitter = pFirstEmitter;
ListenerFormat = fmt;
pLocalResource->SetFormat(ListenerFormat);
pLocalResource->GetFormat(ResourceFormat);
while (pProcessEmitter) {
pProcessEmitter->pEmitter->SetFormat(&ListenerFormat);
pProcessEmitter = pProcessEmitter->pNext;
}
return 0;
}
fr_i32
CMediaListener::Process(fr_f32** ppOutputFloatData, fr_i32 frames)
{
fr_i32 inFrames = 0;
inFrames = (fr_i32)pLocalResource->Read(frames, ppOutputFloatData);
framesPos = pLocalResource->GetPosition();
return inFrames;
}
| 26.26875 | 110 | 0.730193 | suirless |
1fa10edad2574c55eaacb70ccf1e426684a9be6a | 109 | cpp | C++ | SteamAPIWrap/Helper.cpp | HoggeL/Ludosity-s-Steamworks-Wrapper | 5cd8f5740829a20af23343865895ceb782f9b0b4 | [
"MIT"
] | null | null | null | SteamAPIWrap/Helper.cpp | HoggeL/Ludosity-s-Steamworks-Wrapper | 5cd8f5740829a20af23343865895ceb782f9b0b4 | [
"MIT"
] | null | null | null | SteamAPIWrap/Helper.cpp | HoggeL/Ludosity-s-Steamworks-Wrapper | 5cd8f5740829a20af23343865895ceb782f9b0b4 | [
"MIT"
] | null | null | null | #include "Precompiled.hpp"
#include "Helper.hpp"
using namespace SteamAPIWrap;
namespace SteamAPIWrap
{
}
| 10.9 | 29 | 0.770642 | HoggeL |
1fa38e014ca5f85754d715b90f8c8c6bd411d65c | 4,557 | cpp | C++ | src/teleop_dummy/main_teleop_dummy_sigma.cpp | neemoh/ART | 3f990b9d3c4b58558adf97866faf4eea553ba71b | [
"Unlicense"
] | 11 | 2018-06-29T19:08:08.000Z | 2021-12-30T07:13:00.000Z | src/teleop_dummy/main_teleop_dummy_sigma.cpp | liuxia-zju/ATAR | 3f990b9d3c4b58558adf97866faf4eea553ba71b | [
"Unlicense"
] | 1 | 2020-05-09T23:44:55.000Z | 2020-05-09T23:44:55.000Z | src/teleop_dummy/main_teleop_dummy_sigma.cpp | liuxia-zju/ATAR | 3f990b9d3c4b58558adf97866faf4eea553ba71b | [
"Unlicense"
] | 6 | 2017-11-28T14:26:18.000Z | 2019-11-29T01:57:14.000Z | //
// Created by nima on 12/10/17.
//
#include <ros/ros.h>
#include <geometry_msgs/PoseStamped.h>
#include <sensor_msgs/Joy.h>
#include <kdl/frames.hpp>
#include <kdl_conversions/kdl_msg.h>
#include <std_msgs/String.h>
#include <std_msgs/Int8.h>
#include <src/ar_core/ControlEvents.h>
// This node simulates the slaves of the dvrk in a teleop mode and controls the
// behavior of the master console to mock that of the dvrk teleoperation mode.
// At the moment the dvrk does not publish the foot pedals status if the
// dvrk-console is not run in teleop mode. That's why we run the dvrk-console
// in a normal teleop mode, but Home the arms through this node (instead of
// the user interface) so that we can power up only the masters and not the
// slaves that are not needed here.
// ------------------------------------- global variables ---------------------------
int buttons[2];
bool new_buttons_msg;
bool new_master_pose;
KDL::Frame master_pose;
// ------------------------------------- callback functions ---------------------------
void ButtonsCallback(const sensor_msgs::JoyConstPtr & msg){
for (int i = 0; i < msg->buttons.size(); ++i) {
buttons[i] = msg->buttons[i];
}
new_buttons_msg = true;
}
void MasterPoseCurrentCallback(
const geometry_msgs::PoseStamped::ConstPtr &msg){
geometry_msgs::Pose pose = msg->pose;
tf::poseMsgToKDL(msg->pose, master_pose);
new_master_pose = true;
}
void ControlEventsCallback(const std_msgs::Int8ConstPtr
&msg) {
int8_t control_event = msg->data;
ROS_DEBUG("Received control event %d", control_event);
switch(control_event){
case CE_HOME_MASTERS:
break;
default:
break;
}
}
// ------------------------------------- Main ---------------------------
int main(int argc, char * argv[]) {
ros::init(argc, argv, "teleop_dummy");
ros::NodeHandle n(ros::this_node::getName());
if( ros::console::set_logger_level(
ROSCONSOLE_DEFAULT_NAME, ros::console::levels::Info) )
ros::console::notifyLoggerLevelsChanged();
// ------------------------------------- Buttons---------------------------
ros::Subscriber sub_clutch_clutch = n.subscribe(
"/sigma/sigma0/buttons", 1, ButtonsCallback);
// ------------ MATERS POSE
ros::Subscriber sub_master_current_pose = n.subscribe("/sigma/sigma0/pose",
1, MasterPoseCurrentCallback);
// ------------ SLAVE PUBLISH POSE
std::string pose_topic = std::string("/sigma/sigma0/dummy_slave_pose");
ros::Publisher pub_slave_pose
= n.advertise<geometry_msgs::PoseStamped>(pose_topic, 1);
// ------------ subscribe to control events that come from the GUI
ros::Subscriber sub_control_events = n.subscribe("/atar/control_events", 1,
ControlEventsCallback);
double scaling = 0.2;
n.getParam("scaling", scaling);
ROS_INFO(" Master to slave position scaling: %f", scaling);
// spinning freq, publishing freq will be according to the freq of master poses received
ros::Rate loop_rate(1000);
KDL::Vector master_position_at_clutch_instance;
KDL::Vector slave_position_at_clutch_instance;
KDL::Frame slave_pose;
// get initial tool position
std::vector<double> init_tool_position= {0., 0., 0.};
n.getParam("initial_slave_position", init_tool_position);
slave_pose.p = KDL::Vector(init_tool_position[0],
init_tool_position[1],
init_tool_position[2]);
while(ros::ok()){
if(new_buttons_msg){
new_buttons_msg = false;
master_position_at_clutch_instance = master_pose.p;
slave_position_at_clutch_instance = slave_pose.p;
}
// Incremental slave position
if(new_master_pose) {
new_master_pose = false;
// if operator present increment the slave position
if(buttons[1]==1){
slave_pose.p = slave_position_at_clutch_instance +
scaling * (master_pose.p - master_position_at_clutch_instance);
slave_pose.M = master_pose.M;
}
//publish pose
geometry_msgs::PoseStamped pose;
tf::poseKDLToMsg( slave_pose, pose.pose);
pub_slave_pose.publish(pose);
}
ros::spinOnce();
loop_rate.sleep();
}
}
| 33.507353 | 94 | 0.595128 | neemoh |
1fa651fd76841758e078bce56db748f2b9794d19 | 901 | cpp | C++ | OJ/vol127/UVa12709.cpp | jennygaz/competitive | 2807b0fbd2eaaca8ba618f03b1e62c0241849e6c | [
"MIT"
] | null | null | null | OJ/vol127/UVa12709.cpp | jennygaz/competitive | 2807b0fbd2eaaca8ba618f03b1e62c0241849e6c | [
"MIT"
] | null | null | null | OJ/vol127/UVa12709.cpp | jennygaz/competitive | 2807b0fbd2eaaca8ba618f03b1e62c0241849e6c | [
"MIT"
] | null | null | null | /* UVa 12709 - Falling Ants */
/* Solution: Sort by H then by the product LW */
/* by jennyga */
#include <iostream>
#include <vector>
#include <algorithm>
#include <tuple>
#include <functional>
using namespace std;
constexpr int MAXN = 110;
int main(){
ios_base::sync_with_stdio(0);
cin.tie(0);
cout.tie(0);
int n {};
vector<tuple<int, int, int>> data( MAXN );
while( cin >> n, n ){
int L {}, W {}, H {};
for( int i = 0; i < n; ++ i ){
cin >> L >> W >> H;
data[i] = { L, W, H };
}
sort( data.begin(), data.begin() + n,
[]( tuple<int, int, int>& lhs, tuple<int, int, int>& rhs ) -> bool {
if( get<2>( lhs ) != get<2>( rhs ) ) return get<2>( lhs ) > get<2>( rhs );
else return get<0>( lhs ) * get<1>( lhs ) > get<0>( rhs ) * get<1>( rhs );
} );
cout << get<0>( data[0] ) * get<1>( data[0] ) * get<2>( data[0] ) << '\n';
}
return 0;
}
| 25.027778 | 79 | 0.513873 | jennygaz |
1fa78f043c98ebdfff8814f34733c311bc583b2a | 8,334 | cpp | C++ | demos/cocos2d-x-3.2/Classes/HelloWorldScene.cpp | silwings/DragonBonesCPP | 8c1003875f78d8feba49fd30ada3196db9afdff1 | [
"MIT"
] | null | null | null | demos/cocos2d-x-3.2/Classes/HelloWorldScene.cpp | silwings/DragonBonesCPP | 8c1003875f78d8feba49fd30ada3196db9afdff1 | [
"MIT"
] | null | null | null | demos/cocos2d-x-3.2/Classes/HelloWorldScene.cpp | silwings/DragonBonesCPP | 8c1003875f78d8feba49fd30ada3196db9afdff1 | [
"MIT"
] | null | null | null | #include "HelloWorldScene.h"
USING_NS_CC;
using namespace dragonBones;
Scene* HelloWorld::createScene()
{
// 'scene' is an autorelease object
auto scene = Scene::create();
// 'layer' is an autorelease object
auto layer = HelloWorld::create();
// add layer as a child to scene
scene->addChild(layer);
// return the scene
return scene;
}
void HelloWorld::updateHandler(float passTime)
{
dragonBones::WorldClock::clock.advanceTime(passTime);
Rect rect = _armature->getBoundingBox();
Vec2 vec2s[4];
vec2s[0].x = rect.getMidX();
vec2s[0].y = rect.getMidY();
vec2s[1].x = rect.getMidX();
vec2s[1].y = rect.getMaxY();
vec2s[2].x = rect.getMaxX();
vec2s[2].y = rect.getMaxY();
vec2s[3].x = rect.getMaxX();
vec2s[3].y = rect.getMidY();
// log("rect = x=%f, y=%f, w=%f, h=%f", rect.origin.x, rect.origin.y, rect.size.width, rect.size.height);
// log("rect: left=%f, right=%f, top=%f, bottom=%f", rect.getMinX(), rect.getMaxX(), rect.getMaxY(), rect.getMinY());
drawnode->clear();
drawnode->drawPolygon(vec2s, 4, Color4F::WHITE, 1, Color4F::RED);
}
// on "init" you need to initialize your instance
void HelloWorld::demoInit()
{
//////////////////////////////
Size visibleSize = Director::getInstance()->getVisibleSize();
auto origin = Director::getInstance()->getVisibleOrigin();
/////////////////////////////
// 2. add a menu item with "X" image, which is clicked to quit the program
// you may modify it.
// add a "close" icon to exit the progress. it's an autorelease object
auto closeItem = MenuItemImage::create(
"CloseNormal.png",
"CloseSelected.png",
CC_CALLBACK_1(HelloWorld::menuCloseCallback, this));
closeItem->setPosition(origin.x + visibleSize.width - closeItem->getContentSize().width/2 ,
origin.y + closeItem->getContentSize().height/2);
// create menu, it's an autorelease object
auto menu = Menu::create(closeItem, NULL);
menu->setPosition(Vec2::ZERO);
this->addChild(menu, 1);
/////////////////////////////
// 3. add your codes below...
// add a label shows "Hello World"
// create and initialize a label
auto label = LabelTTF::create("Hello World", "Arial", 24);
// position the label on the center of the screen
label->setPosition(origin.x + visibleSize.width/2,
origin.y + visibleSize.height - label->getContentSize().height);
// add the label as a child to this layer
this->addChild(label, 1);
// factory
DBCCFactory::getInstance()->loadDragonBonesData("armatures/Knight/skeleton.xml");
DBCCFactory::getInstance()->loadTextureAtlas("armatures/Knight/texture.xml");
// DBCCFactory::getInstance()->loadDragonBonesData("leiyanfentian/leiyanfentian_skeleton.xml");
// DBCCFactory::getInstance()->loadTextureAtlas("leiyanfentian/leiyanfentian.xml");
// armature
auto armature = (dragonBones::DBCCArmature *)(dragonBones::DBCCFactory::factory.buildArmature("main", "zhugeliang"));
_armature = dragonBones::DBCCArmatureNode::create(armature);
drawnode = DrawNode::create();
//_armature->addChild(drawnode, -1);
this->addChild(drawnode);
_armature->getAnimation()->gotoAndPlay("walk");
_armature->setPosition(480.f, 200.f);
this->addChild(_armature);
// armature event
auto movementHandler = std::bind(&HelloWorld::armAnimationHandler, this, std::placeholders::_1);
auto frameHandler = std::bind(&HelloWorld::armAnimationHandler, this, std::placeholders::_1);
_armature->getCCEventDispatcher()->addCustomEventListener(dragonBones::EventData::START, movementHandler);
_armature->getCCEventDispatcher()->addCustomEventListener(dragonBones::EventData::FADE_IN, movementHandler);
_armature->getCCEventDispatcher()->addCustomEventListener(dragonBones::EventData::COMPLETE, movementHandler);
_armature->getCCEventDispatcher()->addCustomEventListener(dragonBones::EventData::LOOP_COMPLETE, movementHandler);
_armature->getCCEventDispatcher()->addCustomEventListener(dragonBones::EventData::ANIMATION_FRAME_EVENT, frameHandler);
// update
dragonBones::WorldClock::clock.add(_armature->getArmature());
// key
cocos2d::EventListenerKeyboard *listener = cocos2d::EventListenerKeyboard::create();
listener->onKeyPressed = [&](cocos2d::EventKeyboard::KeyCode keyCode, cocos2d::Event *event){
log("key pressed code=%d", keyCode);
switch (keyCode)
{
case cocos2d::EventKeyboard::KeyCode::KEY_A:
//_armature->getAnimation()->gotoAndPlay("wait");
_armature->getAnimation()->gotoAndPlay("skill1");
break;
case cocos2d::EventKeyboard::KeyCode::KEY_S:
_armature->getAnimation()->gotoAndPlay("wait");
break;
case cocos2d::EventKeyboard::KeyCode::KEY_D:
_armature->getAnimation()->gotoAndPlay("atk");
_curAction = "atk";
_jump2Wait = true;
break;
case cocos2d::EventKeyboard::KeyCode::KEY_F:
_armature->getAnimation()->gotoAndPlay("beAtk");
_curAction = "beAtk";
_jump2Wait = true;
break;
case cocos2d::EventKeyboard::KeyCode::KEY_W:
_armature->getAnimation()->gotoAndPlay("skill3");
_curAction = "skill3";
auto node = createEffect("leiyanfentian", "skill_self_1");
_armature->addChild(node);
_jump2Wait = true;
break;
}
};
//listener->onKeyReleased = std::bind(&DemoKnight::keyReleaseHandler, this, std::placeholders::_1, std::placeholders::_2);
this->getEventDispatcher()->addEventListenerWithSceneGraphPriority(listener, this);
}
void HelloWorld::armAnimationHandler(cocos2d::EventCustom *event)
{
dragonBones::EventData *eventData = (dragonBones::EventData *)(event->getUserData());
switch (eventData->getType())
{
case dragonBones::EventData::EventType::START:
cocos2d::log("animation start: %s %f", eventData->animationState->name.c_str(), utils::gettime());
break;
case dragonBones::EventData::EventType::FADE_IN:
cocos2d::log("animation fade in: %s %f", eventData->animationState->name.c_str(), utils::gettime());
break;
case dragonBones::EventData::EventType::COMPLETE:
cocos2d::log("animation complete: %s %f", eventData->animationState->name.c_str(), utils::gettime());
if(_jump2Wait && eventData->animationState->name == _curAction)
{
_jump2Wait = false;
_armature->getAnimation()->gotoAndPlay("wait");
}
break;
case dragonBones::EventData::EventType::LOOP_COMPLETE:
cocos2d::log("animation loop complete: %s %f", eventData->animationState->name.c_str(), utils::gettime());
if(_jump2Wait && eventData->animationState->name == _curAction)
{
_jump2Wait = false;
_armature->getAnimation()->gotoAndPlay("wait");
}
break;
case dragonBones::EventData::EventType::ANIMATION_FRAME_EVENT:
cocos2d::log("animation frame event: %s %s %f", eventData->animationState->name.c_str(), eventData->frameLabel, utils::gettime());
break;
}
}
dragonBones::DBCCArmatureNode* HelloWorld::createEffect(std::string dragonbones, std::string armature)
{
auto effect = (dragonBones::DBCCArmature *)(dragonBones::DBCCFactory::factory.buildArmature(armature, "", "", dragonbones, dragonbones));
effect->getAnimation()->gotoAndPlay("mv");
auto node = dragonBones::DBCCArmatureNode::create(effect);
dragonBones::WorldClock::clock.add(effect);
auto handler = [](cocos2d::EventCustom *event){
dragonBones::EventData *eventData = (dragonBones::EventData *)(event->getUserData());
dragonBones::WorldClock::clock.remove(eventData->armature);
auto node1 = static_cast<Node*>(eventData->armature->getDisplay());
//node1->getParent()->removeFromParent();
node1->setVisible(false);
eventData->armature->getAnimation()->stop();
};
node->getCCEventDispatcher()->addCustomEventListener(dragonBones::EventData::COMPLETE, handler);
node->getCCEventDispatcher()->addCustomEventListener(dragonBones::EventData::LOOP_COMPLETE, handler);
return node;
}
void HelloWorld::menuCloseCallback(Ref* pSender)
{
#if (CC_TARGET_PLATFORM == CC_PLATFORM_WP8) || (CC_TARGET_PLATFORM == CC_PLATFORM_WINRT)
MessageBox("You pressed the close button. Windows Store Apps do not implement a close button.","Alert");
return;
#endif
Director::getInstance()->end();
#if (CC_TARGET_PLATFORM == CC_PLATFORM_IOS)
exit(0);
#endif
}
| 37.881818 | 138 | 0.695944 | silwings |
1fb06c4cfc4d1e9dada028d300608be949e698f5 | 24,451 | cc | C++ | iree/hal/string_util.cc | OliverScherf/iree | f2d74fd832fa412ce4375661f0c8607a1985b61a | [
"Apache-2.0"
] | null | null | null | iree/hal/string_util.cc | OliverScherf/iree | f2d74fd832fa412ce4375661f0c8607a1985b61a | [
"Apache-2.0"
] | null | null | null | iree/hal/string_util.cc | OliverScherf/iree | f2d74fd832fa412ce4375661f0c8607a1985b61a | [
"Apache-2.0"
] | null | null | null | // Copyright 2019 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// 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.
#include "iree/hal/string_util.h"
#include <cctype>
#include <cinttypes>
#include <cstdio>
#include <vector>
#include "absl/strings/ascii.h"
#include "absl/strings/match.h"
#include "absl/strings/numbers.h"
#include "absl/strings/str_join.h"
#include "absl/strings/str_split.h"
#include "absl/strings/string_view.h"
#include "absl/strings/strip.h"
#include "absl/types/span.h"
#include "iree/base/api.h"
#include "iree/base/tracing.h"
#include "iree/hal/buffer.h"
#include "iree/hal/buffer_view.h"
#include "third_party/half/half.hpp"
IREE_API_EXPORT iree_status_t IREE_API_CALL iree_hal_parse_shape(
iree_string_view_t value, iree_host_size_t shape_capacity,
iree_hal_dim_t* out_shape, iree_host_size_t* out_shape_rank) {
IREE_ASSERT_ARGUMENT(out_shape_rank);
*out_shape_rank = 0;
auto str_value = absl::string_view(value.data, value.size);
if (str_value.empty()) {
return iree_ok_status(); // empty shape
}
std::vector<iree_hal_dim_t> dims;
for (auto dim_str : absl::StrSplit(str_value, 'x')) {
int dim_value = 0;
if (!absl::SimpleAtoi(dim_str, &dim_value)) {
return iree_make_status(IREE_STATUS_INVALID_ARGUMENT,
"shape[%zu] invalid value '%.*s' of '%.*s'",
dims.size(), (int)dim_str.size(), dim_str.data(),
(int)value.size, value.data);
}
if (dim_value < 0) {
return iree_make_status(IREE_STATUS_INVALID_ARGUMENT,
"shape[%zu] unsupported value %d of '%.*s'",
dims.size(), dim_value, (int)value.size,
value.data);
}
dims.push_back(dim_value);
}
if (out_shape_rank) {
*out_shape_rank = dims.size();
}
if (dims.size() > shape_capacity) {
return iree_status_from_code(IREE_STATUS_OUT_OF_RANGE);
}
if (out_shape) {
std::memcpy(out_shape, dims.data(), dims.size() * sizeof(*out_shape));
}
return iree_ok_status();
}
IREE_API_EXPORT iree_status_t IREE_API_CALL
iree_hal_format_shape(const iree_hal_dim_t* shape, iree_host_size_t shape_rank,
iree_host_size_t buffer_capacity, char* buffer,
iree_host_size_t* out_buffer_length) {
if (out_buffer_length) {
*out_buffer_length = 0;
}
iree_host_size_t buffer_length = 0;
for (iree_host_size_t i = 0; i < shape_rank; ++i) {
int n = std::snprintf(buffer ? buffer + buffer_length : nullptr,
buffer ? buffer_capacity - buffer_length : 0,
(i < shape_rank - 1) ? "%dx" : "%d", shape[i]);
if (n < 0) {
return iree_make_status(IREE_STATUS_FAILED_PRECONDITION,
"snprintf failed to write dimension %zu", i);
} else if (buffer && n >= buffer_capacity - buffer_length) {
buffer = nullptr;
}
buffer_length += n;
}
if (out_buffer_length) {
*out_buffer_length = buffer_length;
}
return buffer ? iree_ok_status()
: iree_status_from_code(IREE_STATUS_OUT_OF_RANGE);
}
IREE_API_EXPORT iree_status_t IREE_API_CALL iree_hal_parse_element_type(
iree_string_view_t value, iree_hal_element_type_t* out_element_type) {
IREE_ASSERT_ARGUMENT(out_element_type);
*out_element_type = IREE_HAL_ELEMENT_TYPE_NONE;
auto str_value = absl::string_view(value.data, value.size);
iree_hal_numerical_type_t numerical_type = IREE_HAL_NUMERICAL_TYPE_UNKNOWN;
if (absl::StartsWith(str_value, "i")) {
numerical_type = IREE_HAL_NUMERICAL_TYPE_INTEGER_SIGNED;
str_value.remove_prefix(1);
} else if (absl::StartsWith(str_value, "u")) {
numerical_type = IREE_HAL_NUMERICAL_TYPE_INTEGER_UNSIGNED;
str_value.remove_prefix(1);
} else if (absl::StartsWith(str_value, "f")) {
numerical_type = IREE_HAL_NUMERICAL_TYPE_FLOAT_IEEE;
str_value.remove_prefix(1);
} else if (absl::StartsWith(str_value, "x") ||
absl::StartsWith(str_value, "*")) {
numerical_type = IREE_HAL_NUMERICAL_TYPE_UNKNOWN;
str_value.remove_prefix(1);
} else {
return iree_make_status(IREE_STATUS_INVALID_ARGUMENT,
"unhandled element type prefix in '%.*s'",
(int)value.size, value.data);
}
uint32_t bit_count = 0;
if (!absl::SimpleAtoi(str_value, &bit_count) || bit_count > 0xFFu) {
return iree_make_status(IREE_STATUS_INVALID_ARGUMENT,
"out of range bit count in '%.*s'", (int)value.size,
value.data);
}
*out_element_type = iree_hal_make_element_type(numerical_type, bit_count);
return iree_ok_status();
}
IREE_API_EXPORT iree_status_t IREE_API_CALL iree_hal_format_element_type(
iree_hal_element_type_t element_type, iree_host_size_t buffer_capacity,
char* buffer, iree_host_size_t* out_buffer_length) {
if (out_buffer_length) {
*out_buffer_length = 0;
}
const char* prefix;
switch (iree_hal_element_numerical_type(element_type)) {
case IREE_HAL_NUMERICAL_TYPE_INTEGER_SIGNED:
prefix = "i";
break;
case IREE_HAL_NUMERICAL_TYPE_INTEGER_UNSIGNED:
prefix = "u";
break;
case IREE_HAL_NUMERICAL_TYPE_FLOAT_IEEE:
prefix = "f";
break;
default:
prefix = "*";
break;
}
int n = std::snprintf(
buffer, buffer_capacity, "%s%d", prefix,
static_cast<int32_t>(iree_hal_element_bit_count(element_type)));
if (n < 0) {
return iree_make_status(IREE_STATUS_FAILED_PRECONDITION, "snprintf failed");
}
if (out_buffer_length) {
*out_buffer_length = n;
}
return n >= buffer_capacity ? iree_status_from_code(IREE_STATUS_OUT_OF_RANGE)
: iree_ok_status();
}
// Parses a string of two character pairs representing hex numbers into bytes.
static void iree_hal_hex_string_to_bytes(const char* from, uint8_t* to,
ptrdiff_t num) {
/* clang-format off */
static constexpr char kHexValue[256] = {
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,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 0, 0, 0, 0, 0, 0, // '0'..'9'
0, 10, 11, 12, 13, 14, 15, 0, 0, 0, 0, 0, 0, 0, 0, 0, // 'A'..'F'
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 10, 11, 12, 13, 14, 15, 0, 0, 0, 0, 0, 0, 0, 0, 0, // 'a'..'f'
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,
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,
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,
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,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0
};
/* clang-format on */
for (int i = 0; i < num; i++) {
to[i] = (kHexValue[from[i * 2] & 0xFF] << 4) +
(kHexValue[from[i * 2 + 1] & 0xFF]);
}
}
// Parses a signal element string, assuming that the caller has validated that
// |out_data| has enough storage space for the parsed element data.
static iree_status_t iree_hal_parse_element_unsafe(
iree_string_view_t data_str, iree_hal_element_type_t element_type,
uint8_t* out_data) {
switch (element_type) {
case IREE_HAL_ELEMENT_TYPE_SINT_8: {
int32_t temp = 0;
if (!absl::SimpleAtoi(absl::string_view(data_str.data, data_str.size),
&temp) ||
temp > INT8_MAX) {
return iree_status_from_code(IREE_STATUS_INVALID_ARGUMENT);
}
*reinterpret_cast<int8_t*>(out_data) = static_cast<int8_t>(temp);
return iree_ok_status();
}
case IREE_HAL_ELEMENT_TYPE_UINT_8: {
uint32_t temp = 0;
if (!absl::SimpleAtoi(absl::string_view(data_str.data, data_str.size),
&temp) ||
temp > UINT8_MAX) {
return iree_status_from_code(IREE_STATUS_INVALID_ARGUMENT);
}
*reinterpret_cast<uint8_t*>(out_data) = static_cast<uint8_t>(temp);
return iree_ok_status();
}
case IREE_HAL_ELEMENT_TYPE_SINT_16: {
int32_t temp = 0;
if (!absl::SimpleAtoi(absl::string_view(data_str.data, data_str.size),
&temp) ||
temp > INT16_MAX) {
return iree_status_from_code(IREE_STATUS_INVALID_ARGUMENT);
}
*reinterpret_cast<int16_t*>(out_data) = static_cast<int16_t>(temp);
return iree_ok_status();
}
case IREE_HAL_ELEMENT_TYPE_UINT_16: {
uint32_t temp = 0;
if (!absl::SimpleAtoi(absl::string_view(data_str.data, data_str.size),
&temp) ||
temp > UINT16_MAX) {
return iree_status_from_code(IREE_STATUS_INVALID_ARGUMENT);
}
*reinterpret_cast<uint16_t*>(out_data) = static_cast<uint16_t>(temp);
return iree_ok_status();
}
case IREE_HAL_ELEMENT_TYPE_SINT_32:
return absl::SimpleAtoi(absl::string_view(data_str.data, data_str.size),
reinterpret_cast<int32_t*>(out_data))
? iree_ok_status()
: iree_status_from_code(IREE_STATUS_INVALID_ARGUMENT);
case IREE_HAL_ELEMENT_TYPE_UINT_32:
return absl::SimpleAtoi(absl::string_view(data_str.data, data_str.size),
reinterpret_cast<uint32_t*>(out_data))
? iree_ok_status()
: iree_status_from_code(IREE_STATUS_INVALID_ARGUMENT);
case IREE_HAL_ELEMENT_TYPE_SINT_64:
return absl::SimpleAtoi(absl::string_view(data_str.data, data_str.size),
reinterpret_cast<int64_t*>(out_data))
? iree_ok_status()
: iree_status_from_code(IREE_STATUS_INVALID_ARGUMENT);
case IREE_HAL_ELEMENT_TYPE_UINT_64:
return absl::SimpleAtoi(absl::string_view(data_str.data, data_str.size),
reinterpret_cast<uint64_t*>(out_data))
? iree_ok_status()
: iree_status_from_code(IREE_STATUS_INVALID_ARGUMENT);
case IREE_HAL_ELEMENT_TYPE_FLOAT_16: {
float temp = 0;
if (!absl::SimpleAtof(absl::string_view(data_str.data, data_str.size),
&temp)) {
return iree_status_from_code(IREE_STATUS_INVALID_ARGUMENT);
}
*reinterpret_cast<uint16_t*>(out_data) =
half_float::detail::float2half<std::round_to_nearest>(temp);
return iree_ok_status();
}
case IREE_HAL_ELEMENT_TYPE_FLOAT_32:
return absl::SimpleAtof(absl::string_view(data_str.data, data_str.size),
reinterpret_cast<float*>(out_data))
? iree_ok_status()
: iree_status_from_code(IREE_STATUS_INVALID_ARGUMENT);
case IREE_HAL_ELEMENT_TYPE_FLOAT_64:
return absl::SimpleAtod(absl::string_view(data_str.data, data_str.size),
reinterpret_cast<double*>(out_data))
? iree_ok_status()
: iree_status_from_code(IREE_STATUS_INVALID_ARGUMENT);
default: {
// Treat any unknown format as binary.
iree_host_size_t element_size = iree_hal_element_byte_count(element_type);
if (data_str.size != element_size * 2) {
return iree_make_status(IREE_STATUS_INVALID_ARGUMENT,
"binary hex element count mismatch: buffer "
"length=%zu < expected=%zu",
data_str.size, element_size * 2);
}
iree_hal_hex_string_to_bytes(data_str.data, out_data, element_size);
return iree_ok_status();
}
}
}
IREE_API_EXPORT iree_status_t IREE_API_CALL iree_hal_parse_element(
iree_string_view_t data_str, iree_hal_element_type_t element_type,
iree_byte_span_t data_ptr) {
iree_host_size_t element_size = iree_hal_element_byte_count(element_type);
if (data_ptr.data_length < element_size) {
return iree_make_status(
IREE_STATUS_INVALID_ARGUMENT,
"output data buffer overflow: data_length=%zu < element_size=%zu",
data_ptr.data_length, element_size);
}
return iree_hal_parse_element_unsafe(data_str, element_type, data_ptr.data);
}
// Converts a sequence of bytes into hex number strings.
static void iree_hal_bytes_to_hex_string(const uint8_t* src, char* dest,
ptrdiff_t num) {
static constexpr char kHexTable[513] =
"000102030405060708090A0B0C0D0E0F"
"101112131415161718191A1B1C1D1E1F"
"202122232425262728292A2B2C2D2E2F"
"303132333435363738393A3B3C3D3E3F"
"404142434445464748494A4B4C4D4E4F"
"505152535455565758595A5B5C5D5E5F"
"606162636465666768696A6B6C6D6E6F"
"707172737475767778797A7B7C7D7E7F"
"808182838485868788898A8B8C8D8E8F"
"909192939495969798999A9B9C9D9E9F"
"A0A1A2A3A4A5A6A7A8A9AAABACADAEAF"
"B0B1B2B3B4B5B6B7B8B9BABBBCBDBEBF"
"C0C1C2C3C4C5C6C7C8C9CACBCCCDCECF"
"D0D1D2D3D4D5D6D7D8D9DADBDCDDDEDF"
"E0E1E2E3E4E5E6E7E8E9EAEBECEDEEEF"
"F0F1F2F3F4F5F6F7F8F9FAFBFCFDFEFF";
for (auto src_ptr = src; src_ptr != (src + num); ++src_ptr, dest += 2) {
const char* hex_p = &kHexTable[*src_ptr * 2];
std::copy(hex_p, hex_p + 2, dest);
}
}
IREE_API_EXPORT iree_status_t IREE_API_CALL iree_hal_format_element(
iree_const_byte_span_t data, iree_hal_element_type_t element_type,
iree_host_size_t buffer_capacity, char* buffer,
iree_host_size_t* out_buffer_length) {
iree_host_size_t element_size = iree_hal_element_byte_count(element_type);
if (data.data_length < element_size) {
return iree_make_status(
IREE_STATUS_OUT_OF_RANGE,
"data buffer underflow: data_length=%zu < element_size=%zu",
data.data_length, element_size);
}
int n = 0;
switch (element_type) {
case IREE_HAL_ELEMENT_TYPE_SINT_8:
n = std::snprintf(buffer, buffer ? buffer_capacity : 0, "%" PRIi8,
*reinterpret_cast<const int8_t*>(data.data));
break;
case IREE_HAL_ELEMENT_TYPE_UINT_8:
n = std::snprintf(buffer, buffer ? buffer_capacity : 0, "%" PRIu8,
*reinterpret_cast<const uint8_t*>(data.data));
break;
case IREE_HAL_ELEMENT_TYPE_SINT_16:
n = std::snprintf(buffer, buffer ? buffer_capacity : 0, "%" PRIi16,
*reinterpret_cast<const int16_t*>(data.data));
break;
case IREE_HAL_ELEMENT_TYPE_UINT_16:
n = std::snprintf(buffer, buffer ? buffer_capacity : 0, "%" PRIu16,
*reinterpret_cast<const uint16_t*>(data.data));
break;
case IREE_HAL_ELEMENT_TYPE_SINT_32:
n = std::snprintf(buffer, buffer ? buffer_capacity : 0, "%" PRIi32,
*reinterpret_cast<const int32_t*>(data.data));
break;
case IREE_HAL_ELEMENT_TYPE_UINT_32:
n = std::snprintf(buffer, buffer ? buffer_capacity : 0, "%" PRIu32,
*reinterpret_cast<const uint32_t*>(data.data));
break;
case IREE_HAL_ELEMENT_TYPE_SINT_64:
n = std::snprintf(buffer, buffer ? buffer_capacity : 0, "%" PRIi64,
*reinterpret_cast<const int64_t*>(data.data));
break;
case IREE_HAL_ELEMENT_TYPE_UINT_64:
n = std::snprintf(buffer, buffer ? buffer_capacity : 0, "%" PRIu64,
*reinterpret_cast<const uint64_t*>(data.data));
break;
case IREE_HAL_ELEMENT_TYPE_FLOAT_16:
n = std::snprintf(buffer, buffer ? buffer_capacity : 0, "%G",
half_float::detail::half2float<float>(
*reinterpret_cast<const uint16_t*>(data.data)));
break;
case IREE_HAL_ELEMENT_TYPE_FLOAT_32:
n = std::snprintf(buffer, buffer ? buffer_capacity : 0, "%G",
*reinterpret_cast<const float*>(data.data));
break;
case IREE_HAL_ELEMENT_TYPE_FLOAT_64:
n = std::snprintf(buffer, buffer ? buffer_capacity : 0, "%G",
*reinterpret_cast<const double*>(data.data));
break;
default: {
// Treat any unknown format as binary.
n = 2 * (int)element_size;
if (buffer && buffer_capacity > n) {
iree_hal_bytes_to_hex_string(data.data, buffer, element_size);
buffer[n] = 0;
}
}
}
if (n < 0) {
return iree_make_status(IREE_STATUS_FAILED_PRECONDITION, "snprintf failed");
} else if (buffer && n >= buffer_capacity) {
buffer = nullptr;
}
if (out_buffer_length) {
*out_buffer_length = n;
}
return buffer ? iree_ok_status()
: iree_status_from_code(IREE_STATUS_OUT_OF_RANGE);
}
IREE_API_EXPORT iree_status_t IREE_API_CALL iree_hal_parse_buffer_elements(
iree_string_view_t data_str, iree_hal_element_type_t element_type,
iree_byte_span_t data_ptr) {
IREE_TRACE_SCOPE0("iree_hal_parse_buffer_elements");
iree_host_size_t element_size = iree_hal_element_byte_count(element_type);
iree_host_size_t element_capacity = data_ptr.data_length / element_size;
if (iree_string_view_is_empty(data_str)) {
memset(data_ptr.data, 0, data_ptr.data_length);
return iree_ok_status();
}
size_t src_i = 0;
size_t dst_i = 0;
size_t token_start = std::string::npos;
while (src_i < data_str.size) {
char c = data_str.data[src_i++];
bool is_separator =
absl::ascii_isspace(c) || c == ',' || c == '[' || c == ']';
if (token_start == std::string::npos) {
if (!is_separator) {
token_start = src_i - 1;
}
continue;
} else if (token_start != std::string::npos && !is_separator) {
continue;
}
if (dst_i >= element_capacity) {
return iree_make_status(
IREE_STATUS_OUT_OF_RANGE,
"output data buffer overflow: element_capacity=%zu < dst_i=%zu+",
element_capacity, dst_i);
}
IREE_RETURN_IF_ERROR(iree_hal_parse_element_unsafe(
iree_string_view_t{data_str.data + token_start,
src_i - 2 - token_start + 1},
element_type, data_ptr.data + dst_i * element_size));
++dst_i;
token_start = std::string::npos;
}
if (token_start != std::string::npos) {
if (dst_i >= element_capacity) {
return iree_make_status(
IREE_STATUS_OUT_OF_RANGE,
"output data overflow: element_capacity=%zu < dst_i=%zu",
element_capacity, dst_i);
}
IREE_RETURN_IF_ERROR(iree_hal_parse_element_unsafe(
iree_string_view_t{data_str.data + token_start,
data_str.size - token_start},
element_type, data_ptr.data + dst_i * element_size));
++dst_i;
}
if (dst_i == 1 && element_capacity > 1) {
// Splat the single value we got to the entire buffer.
uint8_t* p = data_ptr.data + element_size;
for (int i = 1; i < element_capacity; ++i, p += element_size) {
memcpy(p, data_ptr.data, element_size);
}
} else if (dst_i < element_capacity) {
return iree_make_status(
IREE_STATUS_OUT_OF_RANGE,
"input data string underflow: dst_i=%zu < element_capacity=%zu", dst_i,
element_capacity);
}
return iree_ok_status();
}
static iree_status_t iree_hal_format_buffer_elements_recursive(
iree_const_byte_span_t data, const iree_hal_dim_t* shape,
iree_host_size_t shape_rank, iree_hal_element_type_t element_type,
iree_host_size_t* max_element_count, iree_host_size_t buffer_capacity,
char* buffer, iree_host_size_t* out_buffer_length) {
iree_host_size_t buffer_length = 0;
auto append_char = [&](char c) {
if (buffer) {
if (buffer_length < buffer_capacity - 1) {
buffer[buffer_length] = c;
buffer[buffer_length + 1] = '\0';
} else {
buffer = nullptr;
}
}
++buffer_length;
};
if (shape_rank == 0) {
// Scalar value; recurse to get on to the leaf dimension path.
const iree_hal_dim_t one = 1;
return iree_hal_format_buffer_elements_recursive(
data, &one, 1, element_type, max_element_count, buffer_capacity, buffer,
out_buffer_length);
} else if (shape_rank > 1) {
// Nested dimension; recurse into the next innermost dimension.
iree_hal_dim_t dim_length = 1;
for (iree_host_size_t i = 1; i < shape_rank; ++i) {
dim_length *= shape[i];
}
iree_device_size_t dim_stride =
dim_length * iree_hal_element_byte_count(element_type);
if (data.data_length < dim_stride * shape[0]) {
return iree_make_status(
IREE_STATUS_OUT_OF_RANGE,
"input data underflow: data_length=%zu < expected=%zu",
data.data_length,
static_cast<iree_host_size_t>(dim_stride * shape[0]));
}
iree_const_byte_span_t subdata;
subdata.data = data.data;
subdata.data_length = dim_stride;
for (iree_hal_dim_t i = 0; i < shape[0]; ++i) {
append_char('[');
iree_host_size_t actual_length = 0;
iree_status_t status = iree_hal_format_buffer_elements_recursive(
subdata, shape + 1, shape_rank - 1, element_type, max_element_count,
buffer ? buffer_capacity - buffer_length : 0,
buffer ? buffer + buffer_length : nullptr, &actual_length);
buffer_length += actual_length;
if (iree_status_is_out_of_range(status)) {
buffer = nullptr;
} else if (!iree_status_is_ok(status)) {
return status;
}
subdata.data += dim_stride;
append_char(']');
}
} else {
// Leaf dimension; output data.
iree_host_size_t max_count =
std::min(*max_element_count, static_cast<iree_host_size_t>(shape[0]));
iree_device_size_t element_stride =
iree_hal_element_byte_count(element_type);
if (data.data_length < max_count * element_stride) {
return iree_make_status(
IREE_STATUS_OUT_OF_RANGE,
"input data underflow; data_length=%zu < expected=%zu",
data.data_length,
static_cast<iree_host_size_t>(max_count * element_stride));
}
*max_element_count -= max_count;
iree_const_byte_span_t subdata;
subdata.data = data.data;
subdata.data_length = element_stride;
for (iree_hal_dim_t i = 0; i < max_count; ++i) {
if (i > 0) append_char(' ');
iree_host_size_t actual_length = 0;
iree_status_t status = iree_hal_format_element(
subdata, element_type, buffer ? buffer_capacity - buffer_length : 0,
buffer ? buffer + buffer_length : nullptr, &actual_length);
subdata.data += element_stride;
buffer_length += actual_length;
if (iree_status_is_out_of_range(status)) {
buffer = nullptr;
} else if (!iree_status_is_ok(status)) {
return status;
}
}
if (max_count < shape[0]) {
append_char('.');
append_char('.');
append_char('.');
}
}
if (out_buffer_length) {
*out_buffer_length = buffer_length;
}
return buffer ? iree_ok_status()
: iree_status_from_code(IREE_STATUS_OUT_OF_RANGE);
}
IREE_API_EXPORT iree_status_t IREE_API_CALL iree_hal_format_buffer_elements(
iree_const_byte_span_t data, const iree_hal_dim_t* shape,
iree_host_size_t shape_rank, iree_hal_element_type_t element_type,
iree_host_size_t max_element_count, iree_host_size_t buffer_capacity,
char* buffer, iree_host_size_t* out_buffer_length) {
IREE_TRACE_SCOPE0("iree_hal_format_buffer_elements");
if (out_buffer_length) {
*out_buffer_length = 0;
}
if (buffer && buffer_capacity) {
buffer[0] = '\0';
}
return iree_hal_format_buffer_elements_recursive(
data, shape, shape_rank, element_type, &max_element_count,
buffer_capacity, buffer, out_buffer_length);
}
| 40.281713 | 80 | 0.644391 | OliverScherf |
1fb4d9fcf28e13e998a55d4723163ca30a407d8c | 589 | cpp | C++ | deque.cpp | AbhiRepository/algorithm_codes | 723b9a660084a701b468f98f1c184f9573856521 | [
"MIT"
] | 2 | 2018-09-05T17:12:37.000Z | 2018-09-18T09:27:40.000Z | deque.cpp | AbhiRepository/algorithm_codes | 723b9a660084a701b468f98f1c184f9573856521 | [
"MIT"
] | 8 | 2018-03-24T20:41:25.000Z | 2018-10-19T15:04:20.000Z | deque.cpp | AbhiRepository/algorithm_codes | 723b9a660084a701b468f98f1c184f9573856521 | [
"MIT"
] | 5 | 2018-09-05T17:12:43.000Z | 2018-10-01T09:13:52.000Z | //Program to implement deque for finding the maximum of all suaarays of size k
#include <iostream>
#include <deque>
using namespace std;
int main()
{
int a[]={1,43,23,11,46,22,81,22};
int n=sizeof(a)/sizeof(a[0]);
int k=3;
deque<int> d;
int i;
for (i = 0; i < k; ++i)
{
while(!d.empty() && a[i]>=a[d.back()])
d.pop_back();
d.push_back(i);
}
for (; i < n; ++i)
{
cout<<a[d.front()]<<" ";
while(!d.empty() && d.front()<=i-k)
d.pop_front();
while(!d.empty() && a[i]>=a[d.back()])
d.pop_back();
d.push_back(i);
}
cout<<a[d.front()]<<endl;
return 0;
} | 15.5 | 78 | 0.550085 | AbhiRepository |
1fb570c46f48c50828febe33a93d107e0d4ab239 | 1,124 | cpp | C++ | c++/422.cpp | AkashChandrakar/UVA | b90535c998ecdffe0f30e56fec89411f456b16a5 | [
"Apache-2.0"
] | 2 | 2016-10-23T14:35:13.000Z | 2018-09-16T05:38:47.000Z | c++/422.cpp | AkashChandrakar/UVA | b90535c998ecdffe0f30e56fec89411f456b16a5 | [
"Apache-2.0"
] | null | null | null | c++/422.cpp | AkashChandrakar/UVA | b90535c998ecdffe0f30e56fec89411f456b16a5 | [
"Apache-2.0"
] | null | null | null | #include <bits/stdc++.h>
using namespace std;
typedef long long ll;
typedef pair<ll, ll> ii;
vector<int> v;
map<char, ii> hash;
char s[500];
ll process() {
int len = strlen(s);
ll res = 0;
char chr = 'a';
ii a, b, c;
stack<char> S;
map<char, ii> temphash;
for (int i = 0; i < len; ++i) {
if (s[i] == '(')
S.push('(');
else if (s[i] == ')') {
if (hash.find(S.top()) != hash.end())
b = hash[S.top()];
else
b = temphash[S.top()];
S.pop();
if (hash.find(S.top()) != hash.end())
a = hash[S.top()];
else
a = temphash[S.top()];
S.pop();
if (a.second != b.first)
return -1;
c.first = a.first, c.second = b.second;
res += (a.first * a.second * b.second);
S.pop();
temphash[chr] = c;
S.push(chr);
++chr;
} else {
S.push(s[i]);
}
}
return res;
}
int main() {
int n, row, col;
ll res;
char c;
scanf("%d", &n);
for (int i = 0; i < n; ++i) {
scanf("\n%c %d %d", &c, &row, &col);
hash[c] = ii(row, col);
}
while (scanf("%s", s) != EOF) {
res = process();
if (res == -1)
printf("error\n");
else
printf("%lld\n", res);
}
return 0;
}
| 18.129032 | 42 | 0.495552 | AkashChandrakar |
1fba7a152c610fc21125775f6fc104d260a08888 | 1,895 | cpp | C++ | GeneticAlgorithm/GeneticAlgorithm.cpp | TomaszRewak/BMCP | 99e94b11f70658d9b8de792b36af7ecbb215d665 | [
"MIT"
] | 2 | 2019-11-04T15:09:52.000Z | 2022-01-12T05:41:16.000Z | GeneticAlgorithm/GeneticAlgorithm.cpp | TomaszRewak/BMCP | 99e94b11f70658d9b8de792b36af7ecbb215d665 | [
"MIT"
] | null | null | null | GeneticAlgorithm/GeneticAlgorithm.cpp | TomaszRewak/BMCP | 99e94b11f70658d9b8de792b36af7ecbb215d665 | [
"MIT"
] | 1 | 2020-09-09T12:24:35.000Z | 2020-09-09T12:24:35.000Z | // ========================================
// ======= Created by Tomasz Rewak ========
// ========================================
// ==== https://github.com/TomaszRewak ====
// ========================================
#include <memory>
#include <vector>
#include <algorithm>
#include "GeneticAlgorithm.h"
#include "InitialPopulation.h"
#include "StopCondition.h"
#include "Fitness.h"
#include "Specimen.h"
#include "Component.h"
namespace GA
{
void GeneticAlgorithm::start()
{
startTime = std::chrono::steady_clock::now();
for (auto spec : initialPopulation->generate())
population.push_back(std::move(spec));
for (auto& specimen : population)
if (specimen.fitness <= globalBest.fitness)
globalBest = specimen;
while(true)
{
for (auto stopCondition : stopConditions)
if (stopCondition->checkCondition(*this))
return;
for (auto chainGenerator : chainGenerators)
{
ComponentChainBuilder builder;
chainGenerator(builder);
builder.chain->get(*this);
}
for (auto& specimen : population)
if (specimen.fitness <= globalBest.fitness)
globalBest = specimen;
generation++;
}
}
int GeneticAlgorithm::currentGeneration()
{
return generation;
}
void GeneticAlgorithm::addLog(std::string category, std::string log)
{
logs[category].push_back(log);
}
#pragma region Initialization
GeneticAlgorithm& GeneticAlgorithm::withInitialPopulation(std::shared_ptr<InitialPopulation> initialPopulation)
{
this->initialPopulation = initialPopulation;
return *this;
}
GeneticAlgorithm& GeneticAlgorithm::withStopCondition(std::shared_ptr<StopCondition> stopCondition)
{
stopConditions.push_back(stopCondition);
return *this;
}
GeneticAlgorithm& GeneticAlgorithm::with(std::function<void(ComponentChainBuilder& builder)> chain)
{
chainGenerators.push_back(chain);
return *this;
}
#pragma endregion
} | 22.294118 | 112 | 0.668602 | TomaszRewak |
1fbcd45bf47b41749f66033657b69cdb0ff6a0c8 | 8,032 | cc | C++ | node_modules/@parcel/watcher/src/watchman/BSER.cc | hamsall/hamsall.github.io | dc21c8037c9cd13641c61628ef1ed04c306c7701 | [
"MIT"
] | 346 | 2019-04-08T01:30:31.000Z | 2022-03-24T01:49:04.000Z | node_modules/@parcel/watcher/src/watchman/BSER.cc | hamsall/hamsall.github.io | dc21c8037c9cd13641c61628ef1ed04c306c7701 | [
"MIT"
] | 79 | 2019-04-20T08:00:07.000Z | 2022-03-30T17:24:22.000Z | node_modules/@parcel/watcher/src/watchman/BSER.cc | hamsall/hamsall.github.io | dc21c8037c9cd13641c61628ef1ed04c306c7701 | [
"MIT"
] | 12 | 2019-04-08T08:02:10.000Z | 2022-02-03T05:18:53.000Z | #include <stdint.h>
#include "./BSER.hh"
BSERType decodeType(std::istream &iss) {
int8_t type;
iss.read(reinterpret_cast<char*>(&type), sizeof(type));
return (BSERType) type;
}
void expectType(std::istream &iss, BSERType expected) {
BSERType got = decodeType(iss);
if (got != expected) {
throw std::runtime_error("Unexpected BSER type");
}
}
void encodeType(std::ostream &oss, BSERType type) {
int8_t t = (int8_t)type;
oss.write(reinterpret_cast<char*>(&t), sizeof(t));
}
template<typename T>
class Value : public BSERValue {
public:
T value;
Value(T val) {
value = val;
}
Value() {}
};
class BSERInteger : public Value<int64_t> {
public:
BSERInteger(int64_t value) : Value(value) {}
BSERInteger(std::istream &iss) {
int8_t int8;
int16_t int16;
int32_t int32;
int64_t int64;
BSERType type = decodeType(iss);
switch (type) {
case BSER_INT8:
iss.read(reinterpret_cast<char*>(&int8), sizeof(int8));
value = int8;
break;
case BSER_INT16:
iss.read(reinterpret_cast<char*>(&int16), sizeof(int16));
value = int16;
break;
case BSER_INT32:
iss.read(reinterpret_cast<char*>(&int32), sizeof(int32));
value = int32;
break;
case BSER_INT64:
iss.read(reinterpret_cast<char*>(&int64), sizeof(int64));
value = int64;
break;
default:
throw std::runtime_error("Invalid BSER int type");
}
}
int64_t intValue() override {
return value;
}
void encode(std::ostream &oss) override {
if (value <= INT8_MAX) {
encodeType(oss, BSER_INT8);
int8_t v = (int8_t)value;
oss.write(reinterpret_cast<char*>(&v), sizeof(v));
} else if (value <= INT16_MAX) {
encodeType(oss, BSER_INT16);
int16_t v = (int16_t)value;
oss.write(reinterpret_cast<char*>(&v), sizeof(v));
} else if (value <= INT32_MAX) {
encodeType(oss, BSER_INT32);
int32_t v = (int32_t)value;
oss.write(reinterpret_cast<char*>(&v), sizeof(v));
} else {
encodeType(oss, BSER_INT64);
oss.write(reinterpret_cast<char*>(&value), sizeof(value));
}
}
};
class BSERArray : public Value<BSER::Array> {
public:
BSERArray() : Value() {}
BSERArray(BSER::Array value) : Value(value) {}
BSERArray(std::istream &iss) {
expectType(iss, BSER_ARRAY);
int64_t len = BSERInteger(iss).intValue();
for (int64_t i = 0; i < len; i++) {
value.push_back(BSER(iss));
}
}
BSER::Array arrayValue() override {
return value;
}
void encode(std::ostream &oss) override {
encodeType(oss, BSER_ARRAY);
BSERInteger(value.size()).encode(oss);
for (auto it = value.begin(); it != value.end(); it++) {
it->encode(oss);
}
}
};
class BSERString : public Value<std::string> {
public:
BSERString(std::string value) : Value(value) {}
BSERString(std::istream &iss) {
expectType(iss, BSER_STRING);
int64_t len = BSERInteger(iss).intValue();
value.resize(len);
iss.read(&value[0], len);
}
std::string stringValue() override {
return value;
}
void encode(std::ostream &oss) override {
encodeType(oss, BSER_STRING);
BSERInteger(value.size()).encode(oss);
oss << value;
}
};
class BSERObject : public Value<BSER::Object> {
public:
BSERObject() : Value() {}
BSERObject(BSER::Object value) : Value(value) {}
BSERObject(std::istream &iss) {
expectType(iss, BSER_OBJECT);
int64_t len = BSERInteger(iss).intValue();
for (int64_t i = 0; i < len; i++) {
auto key = BSERString(iss).stringValue();
auto val = BSER(iss);
value.emplace(key, val);
}
}
BSER::Object objectValue() override {
return value;
}
void encode(std::ostream &oss) override {
encodeType(oss, BSER_OBJECT);
BSERInteger(value.size()).encode(oss);
for (auto it = value.begin(); it != value.end(); it++) {
BSERString(it->first).encode(oss);
it->second.encode(oss);
}
}
};
class BSERDouble : public Value<double> {
public:
BSERDouble(double value) : Value(value) {}
BSERDouble(std::istream &iss) {
expectType(iss, BSER_REAL);
iss.read(reinterpret_cast<char*>(&value), sizeof(value));
}
double doubleValue() override {
return value;
}
void encode(std::ostream &oss) override {
encodeType(oss, BSER_REAL);
oss.write(reinterpret_cast<char*>(&value), sizeof(value));
}
};
class BSERBoolean : public Value<bool> {
public:
BSERBoolean(bool value) : Value(value) {}
bool boolValue() override { return value; }
void encode(std::ostream &oss) override {
int8_t t = value == true ? BSER_BOOL_TRUE : BSER_BOOL_FALSE;
oss.write(reinterpret_cast<char*>(&t), sizeof(t));
}
};
class BSERNull : public Value<bool> {
public:
BSERNull() : Value(false) {}
void encode(std::ostream &oss) override {
encodeType(oss, BSER_NULL);
}
};
std::shared_ptr<BSERArray> decodeTemplate(std::istream &iss) {
expectType(iss, BSER_TEMPLATE);
auto keys = BSERArray(iss).arrayValue();
auto len = BSERInteger(iss).intValue();
std::shared_ptr<BSERArray> arr = std::make_shared<BSERArray>();
for (int64_t i = 0; i < len; i++) {
BSER::Object obj;
for (auto it = keys.begin(); it != keys.end(); it++) {
if (iss.peek() == 0x0c) {
iss.ignore(1);
continue;
}
auto val = BSER(iss);
obj.emplace(it->stringValue(), val);
}
arr->value.push_back(obj);
}
return arr;
}
BSER::BSER(std::istream &iss) {
BSERType type = decodeType(iss);
iss.unget();
switch (type) {
case BSER_ARRAY:
m_ptr = std::make_shared<BSERArray>(iss);
break;
case BSER_OBJECT:
m_ptr = std::make_shared<BSERObject>(iss);
break;
case BSER_STRING:
m_ptr = std::make_shared<BSERString>(iss);
break;
case BSER_INT8:
case BSER_INT16:
case BSER_INT32:
case BSER_INT64:
m_ptr = std::make_shared<BSERInteger>(iss);
break;
case BSER_REAL:
m_ptr = std::make_shared<BSERDouble>(iss);
break;
case BSER_BOOL_TRUE:
iss.ignore(1);
m_ptr = std::make_shared<BSERBoolean>(true);
break;
case BSER_BOOL_FALSE:
iss.ignore(1);
m_ptr = std::make_shared<BSERBoolean>(false);
break;
case BSER_NULL:
iss.ignore(1);
m_ptr = std::make_shared<BSERNull>();
break;
case BSER_TEMPLATE:
m_ptr = decodeTemplate(iss);
break;
default:
throw std::runtime_error("unknown BSER type");
}
}
BSER::BSER() : m_ptr(std::make_shared<BSERNull>()) {}
BSER::BSER(BSER::Array value) : m_ptr(std::make_shared<BSERArray>(value)) {}
BSER::BSER(BSER::Object value) : m_ptr(std::make_shared<BSERObject>(value)) {}
BSER::BSER(const char *value) : m_ptr(std::make_shared<BSERString>(value)) {}
BSER::BSER(std::string value) : m_ptr(std::make_shared<BSERString>(value)) {}
BSER::BSER(int64_t value) : m_ptr(std::make_shared<BSERInteger>(value)) {}
BSER::BSER(double value) : m_ptr(std::make_shared<BSERDouble>(value)) {}
BSER::BSER(bool value) : m_ptr(std::make_shared<BSERBoolean>(value)) {}
BSER::Array BSER::arrayValue() { return m_ptr->arrayValue(); }
BSER::Object BSER::objectValue() { return m_ptr->objectValue(); }
std::string BSER::stringValue() { return m_ptr->stringValue(); }
int64_t BSER::intValue() { return m_ptr->intValue(); }
double BSER::doubleValue() { return m_ptr->doubleValue(); }
bool BSER::boolValue() { return m_ptr->boolValue(); }
void BSER::encode(std::ostream &oss) {
m_ptr->encode(oss);
}
int64_t BSER::decodeLength(std::istream &iss) {
char pdu[2];
if (!iss.read(pdu, 2) || pdu[0] != 0 || pdu[1] != 1) {
throw std::runtime_error("Invalid BSER");
}
return BSERInteger(iss).intValue();
}
std::string BSER::encode() {
std::ostringstream oss(std::ios_base::binary);
encode(oss);
std::ostringstream res(std::ios_base::binary);
res.write("\x00\x01", 2);
BSERInteger(oss.str().size()).encode(res);
res << oss.str();
return res.str();
}
| 26.508251 | 78 | 0.631225 | hamsall |
1fbd2a4e5c43d018d88dc7f3bb0039973f32725b | 47 | cpp | C++ | Unreal/CtaCpp/Runtime/Scripts/Combat/IItem.cpp | areilly711/CtaApi | 8c7a80c48f2a6d02fb6680a5d8f62e6ff7da8d4c | [
"MIT"
] | 3 | 2021-06-02T16:44:02.000Z | 2022-01-24T20:20:10.000Z | Unreal/CtaCpp/Runtime/Scripts/Combat/IItem.cpp | areilly711/CtaApi | 8c7a80c48f2a6d02fb6680a5d8f62e6ff7da8d4c | [
"MIT"
] | null | null | null | Unreal/CtaCpp/Runtime/Scripts/Combat/IItem.cpp | areilly711/CtaApi | 8c7a80c48f2a6d02fb6680a5d8f62e6ff7da8d4c | [
"MIT"
] | null | null | null | #include "IItem.h"
namespace Cta::Combat
{
}
| 7.833333 | 21 | 0.659574 | areilly711 |
1fbdb69e6030ee670f300c97ca10550e3effd251 | 8,052 | cpp | C++ | JLITOSL_Liczba_na_slowo/main.cpp | MichalWilczek/spoj-tasks | 6d5d77d750747ecb162c76a2b7eb4b8e8f2c4fc3 | [
"Unlicense"
] | null | null | null | JLITOSL_Liczba_na_slowo/main.cpp | MichalWilczek/spoj-tasks | 6d5d77d750747ecb162c76a2b7eb4b8e8f2c4fc3 | [
"Unlicense"
] | null | null | null | JLITOSL_Liczba_na_slowo/main.cpp | MichalWilczek/spoj-tasks | 6d5d77d750747ecb162c76a2b7eb4b8e8f2c4fc3 | [
"Unlicense"
] | null | null | null | #include <iostream>
#include <map>
#include <vector>
#include <string>
#include <bits/stdc++.h>
using namespace std;
void defineNumberNames(map<int, string> &numbers)
{
numbers[1] = "jeden";
numbers[2] = "dwa";
numbers[3] = "trzy";
numbers[4] = "cztery";
numbers[5] = "piec";
numbers[6] = "szesc";
numbers[7] = "siedem";
numbers[8] = "osiem";
numbers[9] = "dziewiec";
numbers[10] = "dziesiec";
numbers[11] = "jedenascie";
numbers[12] = "dwanascie";
numbers[13] = "trzynascie";
numbers[14] = "czternascie";
numbers[15] = "pietnascie";
numbers[16] = "szesnascie";
numbers[17] = "siedemnascie";
numbers[18] = "osiemnascie";
numbers[19] = "dziewietnascie";
numbers[20] = "dwadziescia";
numbers[30] = "trzydziesci";
numbers[40] = "czterdziesci";
numbers[50] = "piecdziesiat";
numbers[60] = "szescdziesiat";
numbers[70] = "siedemdziesiat";
numbers[80] = "osiemdziesiat";
numbers[90] = "dziewiecdziesiat";
numbers[100] = "sto";
numbers[200] = "dwiescie";
numbers[300] = "trzysta";
numbers[400] = "czterysta";
numbers[500] = "piecset";
numbers[600] = "szescset";
numbers[700] = "siedemset";
numbers[800] = "osiemset";
numbers[900] = "dziewiecset";
numbers[1000] = "tys.";
numbers[1000000] = "mln.";
numbers[1000000000] = "mld.";
numbers[1000000000000] = "bln.";
}
int uploadNumbers(vector<string> &numbers)
{
int numbersAmount;
string number;
cin >> numbersAmount;
for (int i=0; i<numbersAmount; i++)
{
cin >> number;
numbers.push_back(number);
}
return numbersAmount;
}
void printDigitUnities(char digit, map<int, string> &numberNames)
{
switch (digit)
{
case '1':
cout << numberNames[1];
break;
case '2':
cout << numberNames[2];
break;
case '3':
cout << numberNames[3];
break;
case '4':
cout << numberNames[4];
break;
case '5':
cout << numberNames[5];
break;
case '6':
cout << numberNames[6];
break;
case '7':
cout << numberNames[7];
break;
case '8':
cout << numberNames[8];
break;
case '9':
cout << numberNames[9];
break;
}
cout << " ";
}
void printDigitTens(char digitTens, char digitUnities, map<int, string> &numberNames)
{
switch (digitTens)
{
case '0':
break;
case '1':
switch(digitUnities)
{
case '0':
cout << numberNames[10];
break;
case '1':
cout << numberNames[11];
break;
case '2':
cout << numberNames[12];
break;
case '3':
cout << numberNames[13];
break;
case '4':
cout << numberNames[14];
break;
case '5':
cout << numberNames[15];
break;
case '6':
cout << numberNames[16];
break;
case '7':
cout << numberNames[17];
break;
case '8':
cout << numberNames[18];
break;
case '9':
cout << numberNames[19];
break;
}
break;
case '2':
cout << numberNames[20];
break;
case '3':
cout << numberNames[30];
break;
case '4':
cout << numberNames[40];
break;
case '5':
cout << numberNames[50];
break;
case '6':
cout << numberNames[60];
break;
case '7':
cout << numberNames[70];
break;
case '8':
cout << numberNames[80];
break;
case '9':
cout << numberNames[90];
break;
}
cout << " ";
}
void printDigitHundreds(char digit, map<int, string> &numberNames){
switch(digit)
{
case '1':
cout << numberNames[100];
break;
case '2':
cout << numberNames[200];
break;
case '3':
cout << numberNames[300];
break;
case '4':
cout << numberNames[400];
break;
case '5':
cout << numberNames[500];
break;
case '6':
cout << numberNames[600];
break;
case '7':
cout << numberNames[700];
break;
case '8':
cout << numberNames[800];
break;
case '9':
cout << numberNames[900];
break;
}
cout << " ";
}
bool defineNumberFromThreeDigitsSet(string DigitsSet, map<int, string> &numberNames){
int numberUnities;
int numberTens;
int numberHundreds;
int DigitsSetLength = DigitsSet.length();
bool threeZeros = false;
switch (DigitsSetLength)
{
// case when 3 digits occur
case 3:
numberUnities = DigitsSet[2];
numberTens = DigitsSet[1];
numberHundreds = DigitsSet[0];
if (numberUnities == '0' && numberTens == '0' && numberHundreds == '0'){
threeZeros = true;
}
printDigitHundreds(numberHundreds, numberNames);
printDigitTens(numberTens, numberUnities, numberNames);
if (numberTens != '1')
{
printDigitUnities(numberUnities, numberNames);
}
break;
// case when 2 digits occur
case 2:
numberUnities = DigitsSet[1];
numberTens = DigitsSet[0];
printDigitTens(numberTens, numberUnities, numberNames);
if (numberTens != '1')
{
printDigitUnities(numberUnities, numberNames);
}
break;
// case when 1 digit occurs
case 1:
numberUnities = DigitsSet[0];
printDigitUnities(numberUnities, numberNames);
break;
}
return threeZeros;
}
void printNumber(vector<string> &setDigits, map<int, string> &numberNames){
bool threeZeros;
vector<string> thousandElements;
thousandElements.push_back(numberNames[1000000000000]);
thousandElements.push_back(numberNames[1000000000]);
thousandElements.push_back(numberNames[1000000]);
thousandElements.push_back(numberNames[1000]);
int numberThreeDigitsSetsAmount = setDigits.size();
int thousandElementsIterator;
switch (numberThreeDigitsSetsAmount){
case 2:
thousandElementsIterator = 3;
break;
case 3:
thousandElementsIterator = 2;
break;
case 4:
thousandElementsIterator = 1;
break;
case 5:
thousandElementsIterator = 0;
break;
}
for (int i=0; i< numberThreeDigitsSetsAmount; i++){
threeZeros = defineNumberFromThreeDigitsSet(setDigits[i], numberNames);
if (i < numberThreeDigitsSetsAmount-1){
// take the case when only zeros occur into account
if ((threeZeros == false) || (threeZeros == true && i == 0))
{
cout << thousandElements[thousandElementsIterator] << " ";
}
thousandElementsIterator++;
}
}
}
vector<string> divideNumberToSubsets(vector<string> &numbers, int numberPosition)
{
vector<string> setDigits;
string number = numbers[numberPosition];
reverse(number.begin(), number.end());
int numberLength = number.length();
string numberSet;
for (int i = 0; i < numberLength; i += 3){
if (i+3 < numberLength){
numberSet = number.substr(i, 3);
}
else{
numberSet = number.substr(i, numberLength-i);
}
reverse(numberSet.begin(), numberSet.end());
setDigits.insert(setDigits.begin(), numberSet); // add numberSet to the front in the vector
}
return setDigits;
}
int main()
{
map<int, string> numberNames;
defineNumberNames(numberNames);
vector<string> numbers;
int numbersAmount = uploadNumbers(numbers);
for (int i=0; i<numbersAmount; i++){
vector<string> setDigits = divideNumberToSubsets(numbers, i);
printNumber(setDigits, numberNames);
cout << endl;
}
return 0;
}
| 25.241379 | 99 | 0.551788 | MichalWilczek |
1fbeacbdb7e67d4301c5dba000e07850199a0087 | 1,707 | cpp | C++ | examples/google-code-jam/bcurcio/codejamA.cpp | rbenic-fer/progauthfp | d0fd96c31ab0aab1a9acdcb7c75f2b430f51c675 | [
"MIT"
] | null | null | null | examples/google-code-jam/bcurcio/codejamA.cpp | rbenic-fer/progauthfp | d0fd96c31ab0aab1a9acdcb7c75f2b430f51c675 | [
"MIT"
] | null | null | null | examples/google-code-jam/bcurcio/codejamA.cpp | rbenic-fer/progauthfp | d0fd96c31ab0aab1a9acdcb7c75f2b430f51c675 | [
"MIT"
] | null | null | null | #include <iostream>
#include <cstdio>
#include <cstring>
#include <algorithm>
using namespace std;
int in(){int r=0,c;for(c=getchar_unlocked();c<=32;c=getchar_unlocked());if(c=='-') return -in();for(;c>32;r=(r<<1)+(r<<3)+c-'0',c=getchar_unlocked());return r;}
string ans[]={"X won", "O won","Draw","Game has not completed"};
char bd[20];
void solve(){
int state = 2;
int i;
int tx=0,to=0;
for(i=0;i<16;i++){
bd[i]=0;
while(bd[i]<'!')scanf("%c",bd+i);
if(bd[i]=='.') state=3;
if(bd[i]=='X') tx++;
if(bd[i]=='O') to++;
}
//puts("leyo");
//for(i=0;i<16;i++) putchar(bd[i]);
//puts("leyo");
int j;
bool vale;
for(i=0;i<4;i++){
vale=true;
for(j=0;j<4;j++) if(bd[i*4+j]=='X' || bd[i*4+j]=='.') vale=false;
if(vale) state = 1;
vale=true;
for(j=0;j<4;j++) if(bd[j*4+i]=='X' || bd[j*4+i]=='.') vale=false;
if(vale) state = 1;
}
vale=true;
for(j=0;j<4;j++) if(bd[j*4+j]=='X' || bd[j*4+j]=='.') vale=false;
if(vale) state = 1;
vale=true;
for(j=0;j<4;j++) if(bd[j*4+(3-j)]=='X' || bd[j*4+(3-j)]=='.') vale=false;
if(vale) state = 1;
for(i=0;i<4;i++){
vale=true;
for(j=0;j<4;j++) if(bd[i*4+j]=='O' || bd[i*4+j]=='.') vale=false;
if(vale) state = 0;
vale=true;
for(j=0;j<4;j++) if(bd[j*4+i]=='O' || bd[j*4+i]=='.') vale=false;
if(vale) state = 0;
}
vale=true;
for(j=0;j<4;j++) if(bd[j*4+j]=='O' || bd[j*4+j]=='.') vale=false;
if(vale) state = 0;
vale=true;
for(j=0;j<4;j++) if(bd[j*4+(3-j)]=='O' || bd[j*4+(3-j)]=='.') vale=false;
if(vale) state = 0;
cout << ans[state] << endl;
}
int main(){
for(int i=0,T=in();i<T;i++){
cout << "Case #"<<i+1<<": ";
solve();
}
}
| 25.102941 | 160 | 0.485647 | rbenic-fer |
1fbf35864c65425ffcd01c5ce0f7aa92d11ea696 | 13,780 | cpp | C++ | Samples/Animation/Character.cpp | Ravbug/RavEngine-Samples | e9763cfb00758caaed430f38a5c99c0d44f701a7 | [
"Apache-2.0"
] | 4 | 2021-03-05T05:49:34.000Z | 2022-03-30T15:30:46.000Z | Samples/Animation/Character.cpp | Ravbug/RavEngine-Samples | e9763cfb00758caaed430f38a5c99c0d44f701a7 | [
"Apache-2.0"
] | null | null | null | Samples/Animation/Character.cpp | Ravbug/RavEngine-Samples | e9763cfb00758caaed430f38a5c99c0d44f701a7 | [
"Apache-2.0"
] | null | null | null | #include "Character.hpp"
#include <RavEngine/AnimationAsset.hpp>
#include <RavEngine/MeshAssetSkinned.hpp>
#include <RavEngine/BuiltinMaterials.hpp>
#include <RavEngine/SkinnedMeshComponent.hpp>
#include <RavEngine/ScriptComponent.hpp>
#include <RavEngine/ChildEntityComponent.hpp>
#include <RavEngine/StaticMesh.hpp>
using namespace RavEngine;
using namespace std;
enum CharAnims {
Idle,
Walk,
Run,
Fall,
Jump,
PoundBegin,
InPound,
PoundEnd
};
struct CharacterScript : public ScriptComponent, public RavEngine::IPhysicsActor {
Ref<AnimatorComponent> animator;
Ref<RigidBodyDynamicComponent> rigidBody;
bool controlsEnabled = true;
constexpr static decimalType sprintSpeed = 2.5, walkSpeed = 2;
int16_t groundCounter = 0;
CharacterScript(const decltype(animator)& a, const decltype(rigidBody)& r) : animator(a), rigidBody(r) {}
inline bool OnGround() const {
return groundCounter > 0;
}
void Tick(float fpsScale) final {
switch (animator->GetCurrentState()) {
case CharAnims::PoundBegin:
case CharAnims::InPound:
case CharAnims::PoundEnd:
// hit the ground? go to poundEnd
if (OnGround() && animator->GetCurrentState() != PoundEnd) {
animator->Goto(PoundEnd);
}
break;
default: {
auto velocity = rigidBody->GetLinearVelocity();
auto movementVel = velocity;
movementVel.y = 0;
auto xzspeed = glm::length(movementVel);
if (OnGround()) {
if (xzspeed > 0.4 && xzspeed < 2.2) {
animator->Goto(CharAnims::Walk);
}
else if (xzspeed >= 2.2) {
animator->Goto(CharAnims::Run);
}
// not jumping?
else if (velocity.y < 0.3) {
animator->Goto(CharAnims::Idle);
}
}
else {
// falling and not in pound animation?
if (velocity.y < -0.05) {
switch (animator->GetCurrentState()) {
case CharAnims::PoundBegin:
case CharAnims::PoundEnd:
case CharAnims::InPound:
break;
default:
animator->Goto(CharAnims::Fall);
}
}
}
// jumping?
if (velocity.y > 5) {
animator->Goto(CharAnims::Jump);
}
}
}
if (GetTransform()->GetWorldPosition().y < -10) {
GetTransform()->SetWorldPosition(vector3(0, 5, 0));
}
}
inline void Move(const vector3& dir, decimalType speedMultiplier) {
if (controlsEnabled) {
// apply movement only if touching the ground
if (OnGround()) {
// move in direction
auto vec = dir * walkSpeed + dir * (speedMultiplier * sprintSpeed);
vec.y = rigidBody->GetLinearVelocity().y;
rigidBody->SetLinearVelocity(vec, false);
rigidBody->SetAngularVelocity(vector3(0, 0, 0), false);
}
else {
// in the air, you can slightly nudge your character in a direction
rigidBody->AddForce(dir * 5.0);
}
// face direction
auto rot = glm::quatLookAt(dir, GetTransform()->WorldUp());
GetTransform()->SetWorldRotation(glm::slerp(GetTransform()->GetWorldRotation(), rot, 0.2));
}
}
inline void Jump() {
if (controlsEnabled) {
if (OnGround()) {
auto vel = rigidBody->GetLinearVelocity();
vel.y = 10;
rigidBody->SetLinearVelocity(vel, false);
}
}
}
inline void Pound() {
// we can pound if we are jumping or falling
switch (animator->GetCurrentState()) {
case CharAnims::Fall:
case CharAnims::Jump:
animator->Goto(CharAnims::PoundBegin);
rigidBody->ClearAllForces();
rigidBody->SetLinearVelocity(vector3(0,0,0), false);
break;
default:
break;
}
}
void OnColliderEnter(const WeakRef<RavEngine::PhysicsBodyComponent>& other, const ContactPairPoint* contactPoints, size_t numContactPoints) final
{
if (other.lock()->filterGroup & FilterLayers::L0) { // we use filter layer 0 to mark ground
auto worldpos = GetTransform()->GetWorldPosition();
// is this contact point underneath the character?
for (int i = 0; i < numContactPoints; i++) {
auto diff = worldpos.y - contactPoints[i].position.y;
if (diff > -0.3) {
groundCounter++;
break;
}
}
}
}
void OnColliderExit(const WeakRef<RavEngine::PhysicsBodyComponent>& other, const ContactPairPoint* contactPoints, size_t numContactPoints) final
{
if (other.lock()->filterGroup & FilterLayers::L0) {
groundCounter--;
}
}
inline void StartPounding() {
rigidBody->SetGravityEnabled(true);
rigidBody->SetLinearVelocity(vector3(0,-5,0),false);
}
};
Character::Character() {
// setup animation
// note: if you are loading multiple instances
// of an animated character, you will want to load and store
// the assets separately to avoid unnecessary disk i/o and parsing.
auto skeleton = make_shared<SkeletonAsset>("character_anims.fbx");
auto all_clips = make_shared<AnimationAsset>("character_anims.fbx", skeleton);
auto walk_anim = make_shared<AnimationAssetSegment>(all_clips, 0, 47);
auto idle_anim = make_shared<AnimationAssetSegment>(all_clips, 60,120);
auto run_anim = make_shared<AnimationAssetSegment>(all_clips, 131, 149);
auto jump_anim = make_shared<AnimationAssetSegment>(all_clips, 160, 163);
auto fall_anim = make_shared<AnimationAssetSegment>(all_clips, 171, 177);
auto pound_begin_anim = make_shared<AnimationAssetSegment>(all_clips, 180, 195);
auto pound_do_anim = make_shared<AnimationAssetSegment>(all_clips, 196, 200);
auto pound_end_anim = make_shared<AnimationAssetSegment>(all_clips, 201, 207);
auto mesh = make_shared<MeshAssetSkinned>("character_anims.fbx", skeleton);
auto material = make_shared<PBRMaterialInstance>(Material::Manager::Get<PBRMaterial>());
material->SetAlbedoColor({1,0.4,0.2,1});
auto childEntity = make_shared<Entity>(); // I made the animation facing the wrong way
GetTransform()->AddChild(childEntity->GetTransform()); // so I need a child entity to rotate it back
childEntity->GetTransform()->LocalRotateDelta(vector3(0, glm::radians(180.f), 0)); // if your animations are the correct orientation you don't need this
EmplaceComponent<ChildEntityComponent>(childEntity);
// load the mesh and material onto the character
auto cubemesh = childEntity->EmplaceComponent<SkinnedMeshComponent>(skeleton, mesh);
cubemesh->SetMaterial(material);
// load the collider and physics settings
rigidBody = EmplaceComponent<RigidBodyDynamicComponent>(FilterLayers::L0, FilterLayers::L0 | FilterLayers::L1);
EmplaceComponent<CapsuleCollider>(0.6, 1.3, make_shared<PhysicsMaterial>(0.0, 0.5, 0.0),vector3(0,1.7,0),vector3(0,0,glm::radians(90.0)));
rigidBody->SetAxisLock(RigidBodyDynamicComponent::AxisLock::Angular_X | RigidBodyDynamicComponent::AxisLock::Angular_Z);
rigidBody->SetWantsContactData(true);
// load the animation
auto animcomp = childEntity->EmplaceComponent<AnimatorComponent>(skeleton);
// the Sockets feature allows you to expose transforms at bones on an animated skeleton as though they were their own entities.
// this is useful for attaching an object to a character's hand, as shown below.
auto handEntity = make_shared<Entity>();
MeshAssetOptions opt;
opt.scale = 0.4f;
handEntity->EmplaceComponent<StaticMesh>(MeshAsset::Manager::Get("cone.obj", opt),make_shared<PBRMaterialInstance>(Material::Manager::Get<PBRMaterial>()));
auto handChildEntity = EmplaceComponent<ChildEntityComponent>(handEntity);
auto handsocket = animcomp->AddSocket("character:hand_r"); // you must use the name from the importer. To see imported names, have your debugger print animcomp->skeleton->skeleton->joint_names_.data_+n
handsocket->AddChild(handEntity->GetTransform());
// since this is just a normal transform, we can add an additional transformation
handEntity->GetTransform()->LocalTranslateDelta(vector3(0,-0.5,0));
// create the animation state machine
AnimatorComponent::State
idle_state{ CharAnims::Idle, idle_anim },
walk_state{ CharAnims::Walk, walk_anim },
run_state{ CharAnims::Run, run_anim },
fall_state{ CharAnims::Fall, fall_anim },
jump_state{ CharAnims::Jump, jump_anim },
pound_begin_state{ CharAnims::PoundBegin, pound_begin_anim },
pound_do_state{ CharAnims::InPound, pound_do_anim },
pound_end_state{ CharAnims::PoundEnd, pound_end_anim };
// some states should not loop
jump_state.isLooping = false;
fall_state.isLooping = false;
pound_begin_state.isLooping = false;
pound_end_state.isLooping = false;
pound_do_state.isLooping = false;
// adjust the speed of clips
walk_state.speed = 2.0;
// create transitions
// if a transition between A -> B does not exist, the animation will switch instantly.
idle_state.SetTransition(CharAnims::Walk, TweenCurves::LinearCurve, 0.2, AnimatorComponent::State::Transition::TimeMode::BeginNew)
.SetTransition(CharAnims::Fall, TweenCurves::LinearCurve, 0.2, AnimatorComponent::State::Transition::TimeMode::BeginNew)
.SetTransition(CharAnims::Jump, TweenCurves::LinearCurve, 0.2, AnimatorComponent::State::Transition::TimeMode::BeginNew)
.SetTransition(CharAnims::Run, TweenCurves::LinearCurve, 0.2, AnimatorComponent::State::Transition::TimeMode::BeginNew);
walk_state.SetTransition(CharAnims::Idle, TweenCurves::LinearCurve, 0.5, AnimatorComponent::State::Transition::TimeMode::BeginNew)
.SetTransition(CharAnims::Run, TweenCurves::LinearCurve, 0.2, AnimatorComponent::State::Transition::TimeMode::Blended)
.SetTransition(CharAnims::Fall, TweenCurves::LinearCurve, 0.5, AnimatorComponent::State::Transition::TimeMode::BeginNew)
.SetTransition(CharAnims::Jump, TweenCurves::LinearCurve, 0.2, AnimatorComponent::State::Transition::TimeMode::BeginNew);
run_state.SetTransition(CharAnims::Walk, TweenCurves::LinearCurve, 0.2, AnimatorComponent::State::Transition::TimeMode::Blended)
.SetTransition(CharAnims::Fall, TweenCurves::LinearCurve, 0.5, AnimatorComponent::State::Transition::TimeMode::BeginNew)
.SetTransition(CharAnims::Jump, TweenCurves::LinearCurve, 0.2, AnimatorComponent::State::Transition::TimeMode::BeginNew)
.SetTransition(CharAnims::Idle, TweenCurves::LinearCurve, 0.2, AnimatorComponent::State::Transition::TimeMode::BeginNew);
jump_state.SetTransition(CharAnims::Fall, TweenCurves::LinearCurve, 0.2, AnimatorComponent::State::Transition::TimeMode::BeginNew)
.SetTransition(CharAnims::Walk, TweenCurves::LinearCurve, 0.2, AnimatorComponent::State::Transition::TimeMode::BeginNew)
.SetTransition(CharAnims::Run, TweenCurves::LinearCurve, 0.2, AnimatorComponent::State::Transition::TimeMode::BeginNew)
.SetTransition(CharAnims::Idle, TweenCurves::LinearCurve, 0.2, AnimatorComponent::State::Transition::TimeMode::BeginNew)
.SetTransition(CharAnims::PoundBegin, TweenCurves::LinearCurve, 0.1, AnimatorComponent::State::Transition::TimeMode::BeginNew)
;
pound_begin_state.SetTransition(CharAnims::InPound, TweenCurves::LinearCurve, 0.1, AnimatorComponent::State::Transition::TimeMode::BeginNew);
pound_begin_state.SetAutoTransition(CharAnims::InPound);
pound_do_state.SetTransition(CharAnims::PoundEnd, TweenCurves::LinearCurve, 0.1, AnimatorComponent::State::Transition::TimeMode::BeginNew);
pound_end_state.SetAutoTransition(CharAnims::Idle);
pound_end_state.SetTransition(CharAnims::Idle, TweenCurves::LinearCurve, 0.2, AnimatorComponent::State::Transition::TimeMode::BeginNew);
fall_state.SetTransition(CharAnims::Idle, TweenCurves::LinearCurve, 0.2, AnimatorComponent::State::Transition::TimeMode::BeginNew)
.SetTransition(CharAnims::Walk, TweenCurves::LinearCurve, 0.2, AnimatorComponent::State::Transition::TimeMode::BeginNew)
.SetTransition(CharAnims::Run, TweenCurves::LinearCurve, 0.2, AnimatorComponent::State::Transition::TimeMode::BeginNew)
.SetTransition(CharAnims::Jump, TweenCurves::LinearCurve, 0.2, AnimatorComponent::State::Transition::TimeMode::BeginNew)
.SetTransition(CharAnims::PoundBegin, TweenCurves::LinearCurve, 0.2, AnimatorComponent::State::Transition::TimeMode::BeginNew)
;
// this script controls the animation
script = EmplaceComponent<CharacterScript>(animcomp, rigidBody);
rigidBody->AddReceiver(script);
// need to avoid a cyclical reference here
WeakRef<CharacterScript> scriptref(script);
pound_begin_state.SetBeginCallback([scriptref](uint16_t nextState) {
auto ref = scriptref.lock();
ref->rigidBody->SetGravityEnabled(false);
ref->controlsEnabled = false;
});
pound_do_state.SetBeginCallback([=] (uint16_t nextState) {
scriptref.lock()->StartPounding();
});
pound_end_state.SetEndCallback([=] (uint16_t nextState) {
scriptref.lock()->controlsEnabled = true;
});
// add transitions to the animator component
// note that these are copied into the component, so making changes
// to states after insertion will not work!
animcomp->InsertState(walk_state);
animcomp->InsertState(idle_state);
animcomp->InsertState(run_state);
animcomp->InsertState(jump_state);
animcomp->InsertState(fall_state);
animcomp->InsertState(pound_begin_state);
animcomp->InsertState(pound_end_state);
animcomp->InsertState(pound_do_state);
// initialize the state machine
// if an entry state is not set before play, your game will crash.
animcomp->Goto(CharAnims::Idle, true);
// begin playing the animator controller.
// animator controllers are asynchronous to your other code
// so play and pause simply signal the controller to perform an action
animcomp->Play();
animcomp->debugEnabled = true;
}
void Character::Move(const vector3& dir, decimalType speedMultiplier){
script->Move(dir, speedMultiplier);
}
void Character::Jump()
{
script->Jump();
}
void Character::Pound() {
script->Pound();
}
| 42.269939 | 204 | 0.726633 | Ravbug |
1fc001e78659d76aa089e84c6fb9c70ecdce8d35 | 771 | hxx | C++ | src/core/include/ivy/log/ostream_sink.hxx | sikol/ivy | 6365b8783353cf0c79c633bbc7110be95a55225c | [
"BSL-1.0"
] | null | null | null | src/core/include/ivy/log/ostream_sink.hxx | sikol/ivy | 6365b8783353cf0c79c633bbc7110be95a55225c | [
"BSL-1.0"
] | null | null | null | src/core/include/ivy/log/ostream_sink.hxx | sikol/ivy | 6365b8783353cf0c79c633bbc7110be95a55225c | [
"BSL-1.0"
] | null | null | null | /*
* Copyright (c) 2019, 2020, 2021 SiKol Ltd.
* Distributed under the Boost Software License, Version 1.0.
*/
#ifndef IVY_LOG_OSTREAM_SINK_HXX_INCLUDED
#define IVY_LOG_OSTREAM_SINK_HXX_INCLUDED
#include <iosfwd>
#include <ivy/log.hxx>
namespace ivy::log {
class ostream_sink final : public sink {
std::ostream &_stream;
public:
ostream_sink(std::ostream &strm);
auto log_message(std::chrono::system_clock::time_point timestamp,
severity_code severity,
std::string_view message) -> void final;
};
auto make_ostream_sink(std::ostream &) -> std::unique_ptr<ostream_sink>;
} // namespace ivy::log
#endif // IVY_LOG_OSTREAM_SINK_HXX_INCLUDED
| 24.870968 | 77 | 0.64332 | sikol |
1fc4d55393aa617d1b67178c945ac0af91c30c99 | 1,410 | hpp | C++ | 3rdparty/stout/include/stout/os/windows/dup.hpp | ruhip/mesos1.2.0 | 6f6d6786a91ee96fcd7cd435eee8933496c9903e | [
"Apache-2.0"
] | null | null | null | 3rdparty/stout/include/stout/os/windows/dup.hpp | ruhip/mesos1.2.0 | 6f6d6786a91ee96fcd7cd435eee8933496c9903e | [
"Apache-2.0"
] | null | null | null | 3rdparty/stout/include/stout/os/windows/dup.hpp | ruhip/mesos1.2.0 | 6f6d6786a91ee96fcd7cd435eee8933496c9903e | [
"Apache-2.0"
] | null | null | null | // 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 __STOUT_OS_WINDOWS_DUP_HPP__
#define __STOUT_OS_WINDOWS_DUP_HPP__
#include <io.h>
#include <Winsock2.h>
#include <stout/error.hpp>
#include <stout/try.hpp>
#include <stout/unreachable.hpp>
#include <stout/os/windows/fd.hpp>
namespace os {
inline Try<WindowsFD> dup(const WindowsFD& fd)
{
switch (fd.type()) {
case WindowsFD::FD_CRT:
case WindowsFD::FD_HANDLE: {
int result = ::_dup(fd.crt());
if (result == -1) {
return ErrnoError();
}
return result;
}
case WindowsFD::FD_SOCKET: {
WSAPROTOCOL_INFO protInfo;
if (::WSADuplicateSocket(fd, GetCurrentProcessId(), &protInfo) !=
INVALID_SOCKET) {
return WSASocket(0, 0, 0, &protInfo, 0, 0);
};
return SocketError();
}
}
UNREACHABLE();
}
} // namespace os {
#endif // __STOUT_OS_WINDOWS_DUP_HPP__
| 26.603774 | 75 | 0.684397 | ruhip |
1fc902b20a360f4ecad706065ade6472eb397ddb | 752 | hpp | C++ | apps/openmw/mwgui/trainingwindow.hpp | Bodillium/openmw | 5fdd264d0704e33b44b1ccf17ab4fb721f362e34 | [
"Unlicense"
] | null | null | null | apps/openmw/mwgui/trainingwindow.hpp | Bodillium/openmw | 5fdd264d0704e33b44b1ccf17ab4fb721f362e34 | [
"Unlicense"
] | null | null | null | apps/openmw/mwgui/trainingwindow.hpp | Bodillium/openmw | 5fdd264d0704e33b44b1ccf17ab4fb721f362e34 | [
"Unlicense"
] | null | null | null | #ifndef MWGUI_TRAININGWINDOW_H
#define MWGUI_TRAININGWINDOW_H
#include "windowbase.hpp"
#include "referenceinterface.hpp"
namespace MWGui
{
class TrainingWindow : public WindowBase, public ReferenceInterface
{
public:
TrainingWindow();
virtual void open();
virtual void exit();
void startTraining(MWWorld::Ptr actor);
void onFrame(float dt);
protected:
virtual void onReferenceUnavailable ();
void onCancelButtonClicked (MyGUI::Widget* sender);
void onTrainingSelected(MyGUI::Widget* sender);
MyGUI::Widget* mTrainingOptions;
MyGUI::Button* mCancelButton;
MyGUI::TextBox* mPlayerGold;
float mFadeTimeRemaining;
};
}
#endif
| 19.282051 | 71 | 0.667553 | Bodillium |
1fcadab0db2c8335c2dd90aa29cf8d131edce2e2 | 2,184 | hpp | C++ | SbgatGui/include/LCVisualizer.hpp | bbercovici/SBGAT | 93e935baff49eb742470d7d593931f0573f0c062 | [
"MIT"
] | 6 | 2017-11-29T02:47:00.000Z | 2021-09-26T05:25:44.000Z | SbgatGui/include/LCVisualizer.hpp | bbercovici/SBGAT | 93e935baff49eb742470d7d593931f0573f0c062 | [
"MIT"
] | 34 | 2017-02-09T15:38:35.000Z | 2019-04-25T20:53:37.000Z | SbgatGui/include/LCVisualizer.hpp | bbercovici/SBGAT | 93e935baff49eb742470d7d593931f0573f0c062 | [
"MIT"
] | 1 | 2019-03-12T12:20:25.000Z | 2019-03-12T12:20:25.000Z | /** MIT License
Copyright (c) 2018 Benjamin Bercovici and Jay McMahon
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
*/
#ifndef HEADER_LC_VIZUALIZER
#define HEADER_LC_VIZUALIZER
#include "LCWindow.hpp"
#include <QVTKOpenGLWidget.h>
#include <vtkRenderer.h>
#include <vtkImageData.h>
#include <QPushButton>
#include <vtkContextView.h>
#include <QVTKWidget.h>
namespace SBGAT_GUI {
class RadarWindow;
/*!
@class LCVisualizer
\author Benjamin Bercovici
\date March, 2018
\brief LCVisualizer class defining a window where a user can visualize previously computed lightcurves
\details TODO
*/
class LCVisualizer : public QDialog {
Q_OBJECT
public:
/**
Creates the settings window
@param parent pointer to parent window.
@param measurements reference to vector of arrays of (time,luminosity)
*/
LCVisualizer(LCWindow * parent,const std::vector<std::array<double, 2> > & measurements) ;
/**
Initializes the visualizer window
*/
void init(const std::vector<std::array<double, 2> > & measurements);
private slots:
protected:
QVTKOpenGLWidget * qvtkWidget;
LCWindow * parent;
vtkSmartPointer<vtkContextView> view;
QDialogButtonBox * button_box;
};
}
#endif | 25.395349 | 102 | 0.771978 | bbercovici |
1fcbf5611c831db23504fb8b66e189f045a46705 | 1,358 | cpp | C++ | src/toolchain/core/Misc/Location.cpp | layerzero/cc0 | fa3f8f1f7bbc38ca5b6b8864c80223191b3b1f09 | [
"BSD-2-Clause"
] | null | null | null | src/toolchain/core/Misc/Location.cpp | layerzero/cc0 | fa3f8f1f7bbc38ca5b6b8864c80223191b3b1f09 | [
"BSD-2-Clause"
] | null | null | null | src/toolchain/core/Misc/Location.cpp | layerzero/cc0 | fa3f8f1f7bbc38ca5b6b8864c80223191b3b1f09 | [
"BSD-2-Clause"
] | 2 | 2015-03-03T04:36:51.000Z | 2018-10-01T03:04:11.000Z |
#include "Location.h"
Location::Location()
{
this->FileName = "";
this->Line = 0;
this->Column = 0;
}
/*
int Location::ComparesTo(const Location& other) const
{
if (this->FileName != other.FileName)
{
return 0;
}
int diff = this->Line - other.Line;
if (diff != 0)
{
return diff;
}
diff = this->Column - other.Column;
return diff;
}
Location& Location::operator=(const Location & other)
{
this->Line = other.Line;
this->Column = other.Column;
return *this;
}
bool Location::operator==(const Location& other) const
{
return (this->ComparesTo(other) == 0);
}
bool Location::operator!=(const Location& other) const
{
return (this->ComparesTo(other) != 0) || (this->FileName != other.FileName);
}
bool Location::operator>(const Location& other) const
{
return (this->FileName == other.FileName) &&(this->ComparesTo(other) > 0);
}
bool Location::operator>=(const Location& other) const
{
return (this->FileName == other.FileName) &&(this->ComparesTo(other) >= 0);
}
bool Location::operator<(const Location& other) const
{
return (this->FileName == other.FileName) &&(this->ComparesTo(other) < 0);
}
bool Location::operator<=(const Location& other) const
{
return (this->FileName == other.FileName) &&(this->ComparesTo(other) <= 0);
}*/
| 20.892308 | 81 | 0.623711 | layerzero |
1fccc513104b82f2e92b77eb0c65c400e5ced3f2 | 3,461 | cpp | C++ | src/main.cpp | khskarl/tori | 52e07e7b8bdbab7b46c4565a6be9353c0ce59422 | [
"MIT"
] | 2 | 2018-07-05T23:50:20.000Z | 2020-02-07T12:34:05.000Z | src/main.cpp | khskarl/tori | 52e07e7b8bdbab7b46c4565a6be9353c0ce59422 | [
"MIT"
] | null | null | null | src/main.cpp | khskarl/tori | 52e07e7b8bdbab7b46c4565a6be9353c0ce59422 | [
"MIT"
] | null | null | null | // 3rdparty Headers
#include <GL/glew.h>
#include <GLFW/glfw3.h>
#include <glm/glm.hpp>
#include <glm/gtc/matrix_transform.hpp>
// Standard Headers
#include <cstdio>
#include <cstdlib>
#include <iostream>
// Local Headers
#include <ImGui.hpp>
#include <Assets/AssetManager.hpp>
#include "Graphics/Renderer.hpp"
#include "Graphics/Context.hpp"
#include "Graphics/Program.hpp"
#include "Graphics/Mesh.hpp"
#include "Graphics/Camera.hpp"
#include "Graphics/Material.hpp"
#include "GameObject.hpp"
// General variables
const float dt = 1.f / 60.f;
glm::vec2 mLastCursorPosition(0, 0);
glm::ivec2 mWindowSize(1280, 800);
// Camera
Camera mCamera(glm::vec3(0, 5, -5), glm::vec3(0, -1, 1), mWindowSize.x, mWindowSize.y);
static void CursorPositionCallback(GLFWwindow* window, double xpos, double ypos) {
int state = glfwGetMouseButton(window, GLFW_MOUSE_BUTTON_RIGHT);
if (state == GLFW_PRESS && !ImGui::IsMouseHoveringAnyWindow()) {
float dx = xpos - mLastCursorPosition.x;
float dy = ypos - mLastCursorPosition.y;
mCamera.RotatePitch(-dy * 10.f * dt);
mCamera.RotateYaw ( dx * 10.f * dt);
glfwSetCursorPos(window, mWindowSize.x / 2, mWindowSize.y / 2);
}
glfwGetCursorPos(window, &xpos, &ypos);
mLastCursorPosition = { xpos, ypos };
}
int main(int argc, char * argv[]) {
Context::Initialize();
Context::SetCursorPositionCallback(CursorPositionCallback);
// AssetManager::Get().Setup();
Renderer renderer;
renderer.SetActiveCamera(&mCamera);
renderer.Setup();
GameObject* sphere = new GameObject();
sphere->m_model = Model("sphere.obj", "woodfloor.mat");
sphere->m_position = glm::vec3(0, 0, 0);
renderer.Submit(sphere);
// GameObject* bamboo = new GameObject();
// bamboo->m_model = Model("sphere.obj",
// "rusted_albedo.png",
// "rusted_normal.png",
// "rusted_roughness.png",
// "rusted_metalness.png",
// "rusted_ao.png");
// bamboo->m_position = glm::vec3(5, 0, 5);
// renderer.Submit(bamboo);
// Game Loop
while ((Context::ShouldClose() || Context::IsKeyDown(GLFW_KEY_ESCAPE)) == false) {
Context::PollEvents();
{
static bool show_renderer_window = false;
static bool show_texture_window = false;
static bool show_material_window = false;
if (ImGui::BeginMainMenuBar())
{
if (ImGui::BeginMenu("Renderer"))
{
ImGui::MenuItem("Settings", NULL, &show_renderer_window);
ImGui::EndMenu();
}
if (ImGui::BeginMenu("Assets"))
{
ImGui::MenuItem("Textures", NULL, &show_texture_window);
ImGui::MenuItem("Materials", NULL, &show_material_window);
ImGui::EndMenu();
}
ImGui::EndMainMenuBar();
}
if (show_renderer_window) {
renderer.RendererWindow(&show_renderer_window);
}
if (show_texture_window) {
AssetManager::Get().TexturesWindow(&show_texture_window);
}
if (show_material_window) {
AssetManager::Get().MaterialsWindow(&show_material_window);
}
}
if (Context::IsKeyDown(GLFW_KEY_W)) mCamera.MoveForward( 10 * dt);
if (Context::IsKeyDown(GLFW_KEY_A)) mCamera.MoveRight (-10 * dt);
if (Context::IsKeyDown(GLFW_KEY_S)) mCamera.MoveForward(-10 * dt);
if (Context::IsKeyDown(GLFW_KEY_D)) mCamera.MoveRight ( 10 * dt);
if (Context::IsKeyDown(GLFW_KEY_R)) renderer.m_mainProgram->Reload();
renderer.RenderFrame();
Context::SwapBuffers();
}
Context::Destroy();
return 0;
}
| 28.841667 | 87 | 0.672349 | khskarl |
1fd066c758fcecb9c26be0249bce8b5f92170893 | 2,484 | cpp | C++ | src/pca9685_motors.cpp | Mailamaca/motors_interface | c7062e5e6f1de36cfbe8904fa578d6f2bfc3d506 | [
"MIT"
] | null | null | null | src/pca9685_motors.cpp | Mailamaca/motors_interface | c7062e5e6f1de36cfbe8904fa578d6f2bfc3d506 | [
"MIT"
] | null | null | null | src/pca9685_motors.cpp | Mailamaca/motors_interface | c7062e5e6f1de36cfbe8904fa578d6f2bfc3d506 | [
"MIT"
] | 1 | 2021-12-03T16:01:31.000Z | 2021-12-03T16:01:31.000Z | #include "motors_interface/pca9685_motors.h"
// Constructor
PCA9685Motors::PCA9685Motors()
{
}
bool PCA9685Motors::setupPCA9685(bool real_hardware)
{
m_real_hardware = real_hardware;
if (m_real_hardware) {
// Calling wiringPi setup first.
wiringPiSetup();
// Setup with pinbase 300 and i2c location 0x40
int fd0 = pca9685Setup(PCA9685_PIN_BASE , PCA9685_ADDRESS, PCA9685_HERTZ);
if (fd0 < 0)
{
return false;
}
pca9685PWMReset(fd0);
}
return true;
}
void PCA9685Motors::setPwmMotorParams(
PWMMotor **motor,
float output_half_range,
float output_half_dead_range,
float output_center_value)
{
*motor = new PWMMotor(
output_half_range,
output_half_dead_range,
output_center_value,
PCA9685_MAX_PWM
);
}
/**
* @brief trim value between -1 and 1
*
* @param value
* @return float value trimmed [-1,1]
*/
float PCA9685Motors::trim(float value){
if(value > 1.) {
return 1.0;
}
else if(value < -1.) {
return -1.0;
}
else {
return value;
}
}
void PCA9685Motors::setSteeringParams(
float input_max_value,
float output_half_range,
float output_half_dead_range,
float output_center_value)
{
m_max_steering = input_max_value;
setPwmMotorParams(
&m_steering_pwm,
output_half_range,
output_half_dead_range,
output_center_value);
}
void PCA9685Motors::setThrottleParams(
float input_max_value,
float output_half_range,
float output_half_dead_range,
float output_center_value)
{
m_max_throttle = input_max_value;
setPwmMotorParams(
&m_throttle_pwm,
output_half_range,
output_half_dead_range,
output_center_value);
}
float PCA9685Motors::setThrottle(float throttle)
{
throttle = trim(throttle/m_max_throttle);
int th = m_throttle_pwm->calculate(throttle);
if (m_real_hardware) {
pwmWrite(PCA9685_PIN_BASE + PCA9685_THROTTLE_CH, th);
}
return throttle;
}
float PCA9685Motors::setSteering(float steering)
{
steering = trim(steering/m_max_steering);
int st = m_steering_pwm->calculate(steering);
if (m_real_hardware) {
pwmWrite(PCA9685_PIN_BASE + PCA9685_STEERING_DX_CH, st);
pwmWrite(PCA9685_PIN_BASE + PCA9685_STEERING_SX_CH, st);
}
return steering;
} | 22.788991 | 82 | 0.651369 | Mailamaca |
1fd8bc11becb581a448e8784dd7166e27bfe1912 | 1,466 | hpp | C++ | src/coin/coin.hpp | datavetaren/epilog | 7067a4cf5b62dd8eca3ab9395fbb1b85d95a9820 | [
"MIT"
] | null | null | null | src/coin/coin.hpp | datavetaren/epilog | 7067a4cf5b62dd8eca3ab9395fbb1b85d95a9820 | [
"MIT"
] | null | null | null | src/coin/coin.hpp | datavetaren/epilog | 7067a4cf5b62dd8eca3ab9395fbb1b85d95a9820 | [
"MIT"
] | null | null | null | #pragma once
#ifndef _epilog_coin_coin_hpp
#define _epilog_coin_coin_hpp
#include "../interp/interpreter_base.hpp"
namespace epilog { namespace coin {
// Any term that has arity >= 2 and whose functor's name starts with '$'
// is a coin.
// The first argument must be an integer telling its value,
// The second argument is either unbound (unspent) or not (spent.)
static inline bool is_coin(interp::interpreter_base &interp, common::term t) {
if (t.tag() != common::tag_t::STR) {
return false;
}
auto f = interp.functor(t);
if (f.arity() < 2) {
return false;
}
return interp.is_dollar_atom_name(f);
}
static inline bool is_native_coin(interp::interpreter_base &interp, common::term t) {
return interp.is_functor(t, common::con_cell("$coin",2));
}
static inline bool is_coin_spent(interp::interpreter_base &interp, common::term t) {
assert(is_coin(interp, t));
return !interp.arg(t, 1).tag().is_ref();
}
static inline bool spend_coin(interp::interpreter_base &interp, common::term t) {
assert(is_coin(interp, t));
assert(!is_coin_spent(interp, t));
return interp.unify(interp.arg(t, 1), common::term_env::EMPTY_LIST);
}
static inline int64_t coin_value(interp::interpreter_base &interp, common::term t) {
assert(is_coin(interp, t));
common::term v = interp.arg(t, 0);
assert(v.tag() == common::tag_t::INT);
return reinterpret_cast<common::int_cell &>(v).value();
}
}}
#endif
| 29.32 | 85 | 0.688267 | datavetaren |
1fd8d06dc16a83647d55c6c0b1dd1777716d0efb | 2,361 | cpp | C++ | SUAI/C1/LabOP4/sources/seeker_cpp/main.cpp | mersinvald/SUAI-1441 | 0ad15112aa8794e501fd6794db795e3312ae538c | [
"MIT"
] | 1 | 2017-01-23T17:38:59.000Z | 2017-01-23T17:38:59.000Z | SUAI/C1/LabOP4/sources/seeker_cpp/main.cpp | mersinvald/SUAI-1441 | 0ad15112aa8794e501fd6794db795e3312ae538c | [
"MIT"
] | null | null | null | SUAI/C1/LabOP4/sources/seeker_cpp/main.cpp | mersinvald/SUAI-1441 | 0ad15112aa8794e501fd6794db795e3312ae538c | [
"MIT"
] | 1 | 2016-05-28T05:18:04.000Z | 2016-05-28T05:18:04.000Z | #include <stdio.h>
void getInput(int &width,
int &heigth,
int** &bitmap, //array[w][h], initializing in function;
int* &exitPoint, //array[2], 0 - x, 1 - y;
int* &startPoint);
void printBitmap(int **bitmap, int w, int h);
int main()
{
int width, heigth;
int* startPoint;
int* exitPoint;
int** bitmap;
getInput(width, heigth, bitmap, exitPoint, startPoint); //передаем ссылки на массивы и переменные, чтобы ф-я могла в них писать
printBitmap(bitmap, width, heigth);
return 0;
}
void getInput(int &width, int &heigth, int** &bitmap, int* &exitPoint, int* &startPoint) //получаем указатели на переданные переменные
{
unsigned int i, j, x, y, bit, valid = 0; //unsigned, чтобы не было отрицательного ввода. Знаю, сурово, ибо сегфолт.
printf("Enter labyrinth width: ");
scanf("%i", &width);
printf("Enter labyrinth heigth: ");
scanf("%i", &heigth);
//get WxH bitmam
printf("Enter labyrinth bitmap:\n");
bitmap = new int*[heigth]; //резервируем память для $heigth строк
for(i = 0; i < heigth; i++)
{
bitmap[i] = new int[width]; //резервируем память для width ячеек в строке i
for(j = 0; j < width; j++)
scanf("%i", &bitmap[i][j]);
}
while(!valid) //ввод выходной точки
{
printf("\nEnter labyrinth exit point x y: ");
scanf("%i%i", &x, &y);
bit = bitmap[x][y];
if(x <= width && y <= heigth && bit != 0)
valid = 1;
else
printf("Point is out of map bounds or wall!\n");
}
//резервируем 2 ячейки по размеру int и пишем в них xy
exitPoint = new int[2];
exitPoint[0] = x;
exitPoint[1] = y;
valid = 0;
while(!valid) //ввод стартовой позиции
{
printf("\nEnter labyrinth start point x y: ");
scanf("%i%i", &x, &y);
bit = bitmap[x][y];
if(x <= width && y <= heigth && bit != 0)
valid = 1;
else
printf("Point is out of map bounds or wall!\n");
}
//резервируем и пишем xy
startPoint = new int[2];
startPoint[0] = x;
startPoint[1] = y;
}
void printBitmap(int **bitmap, int w, int h)
{
int i, j;
for(i = 0; i < h; i++){
for(j = 0; j < w; j++)
printf("%i", bitmap[i][j]);
printf("\n");
}
}
| 27.776471 | 134 | 0.545108 | mersinvald |
1fd91438fd7dece051485f2ca4a07d1bdca660be | 3,442 | hpp | C++ | mineworld/terminal.hpp | Lollipop-Studio/mineworld | 539897831ddc5e669bdff62f54a29a5d01358aa1 | [
"MIT"
] | 18 | 2019-09-26T16:38:02.000Z | 2022-03-09T06:44:59.000Z | mineworld/terminal.hpp | Lollipop-Studio/mineworld | 539897831ddc5e669bdff62f54a29a5d01358aa1 | [
"MIT"
] | 2 | 2019-12-05T02:15:07.000Z | 2021-11-22T08:33:30.000Z | mineworld/terminal.hpp | Lollipop-Studio/mineworld | 539897831ddc5e669bdff62f54a29a5d01358aa1 | [
"MIT"
] | 7 | 2020-01-13T21:18:37.000Z | 2021-09-07T00:31:33.000Z | #ifndef terminal_hpp
#define terminal_hpp
#include <iostream>
#include <string>
#include <vector>
#include <deque>
#include <GL/glew.h>
#include <GLFW/glfw3.h>
#include <glm/glm.hpp>
#include "shape.hpp"
#include "util.hpp"
#include "cell.hpp"
#include "handler.hpp"
#include "block.hpp"
#include "types.hpp"
namespace mineworld {
struct font_loc_t {
int x, y;
font_loc_t(int x, int y) : x(x), y(y) {}
};
font_loc_t getFontLoc(char c);
rect2D createCharRect(const font_loc_t & fl);
/*
* font
*/
class Font {
rect2D fontset[16 * 6];
public:
GLuint textureID, program;
void load();
rect2D getCharRect(char c) {
if (c <= 32) return fontset[0];
else return fontset[c - 32];
}
~Font() {
glDeleteTextures(1, &textureID);
}
};
/*
* view the screen content as 2D array
* draw again if contents being updated
*/
class Screen {
protected:
int width, height;
int capcity;
glRect2DBuffer * glbuffer;
std::string screencontent;
Font font;
float fontw, fonth;
public:
void init();
int getWidth() {
return width;
}
int getHeight() {
return height;
}
void resize();
void putc(int pos, char c);
void print(int start, int size, const char * str);
void clear();
void flush();
void show();
};
/*
* print message to screen "line by line"
* execute command
*/
class Terminal : public Screen {
std::deque<std::string> lines;
int cursor, tail;
bool edited = false;
public:
Terminal() {}
void init() {
Screen::init();
lines.push_back(std::string("> "));
edited = true;
}
void flush();
void resize() {
Screen::resize();
edited = true;
}
void inputc(unsigned int c) { // input a character
lines.rbegin()->push_back((char)c);
edited = true;
}
void del() { // delete a character
if (lines.rbegin()->size() > 2)
lines.rbegin()->pop_back();
edited = true;
}
void execute(); // execute command
void println(const std::string & str) { // print one line to screen
lines.push_back(str);
std::cout << str << std::endl;
edited = true;
}
};
/*
* display a single line
*/
class Board : public Screen {
std::string displayline;
bool edited = false;
public:
void init() {
Screen::init();
display(std::string(MW_VERSION));
}
void resize() {
Screen::resize();
edited = true;
}
void display(const std::string & str) {
displayline = str;
clear();
print(0, displayline.size(), displayline.c_str());
edited = true;
}
void flush() {
if (edited)
Screen::flush();
}
};
extern Terminal gterminal;
extern Board gboard;
}
#endif /* terminal_hpp */
| 22.496732 | 75 | 0.478501 | Lollipop-Studio |
1fd985113702245f49b83fee1405a750b52fb3d3 | 1,314 | cpp | C++ | src/Parse/BasicTreeVisitor.cpp | Naios/swy | c48f7eb4322aa7fd44a3bb82259787b89292733b | [
"Apache-2.0"
] | 19 | 2017-06-04T09:39:51.000Z | 2021-11-16T10:14:45.000Z | src/Parse/BasicTreeVisitor.cpp | Naios/swy | c48f7eb4322aa7fd44a3bb82259787b89292733b | [
"Apache-2.0"
] | null | null | null | src/Parse/BasicTreeVisitor.cpp | Naios/swy | c48f7eb4322aa7fd44a3bb82259787b89292733b | [
"Apache-2.0"
] | 1 | 2019-03-19T02:24:40.000Z | 2019-03-19T02:24:40.000Z |
/**
Copyright(c) 2016 - 2017 Denis Blank <denis.blank at outlook dot com>
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 "BasicTreeVisitor.hpp"
SourceRange
BasicTreeVisitor::sourceRangeOf(antlr4::tree::TerminalNode* token) const {
return sourceLocationOf(token).extend(token->getText().length());
/*
TODO FIXME interval is returned with { 0, 0 } from antlr.
auto interval = token->getSourceInterval();
auto lower = sourceLocationOf(tokenStream_->get(interval.a));
auto upper = sourceLocationOf(tokenStream_->get(interval.b));
return { lower, upper };
*/
}
SourceRange
BasicTreeVisitor::sourceRangeOf(antlr4::tree::TerminalNode* begin,
antlr4::tree::TerminalNode* end) const {
return SourceRange::concat(sourceRangeOf(begin), sourceRangeOf(end));
}
| 34.578947 | 74 | 0.732116 | Naios |
1fe1e8a508a7b089e04781df67f510873ae5e21f | 885 | cpp | C++ | LightOj/1053 - Higher Math.cpp | MhmdRyhn/Programming-Sloution | be189cbf81b14ac7c10d387e259aa23992ba1016 | [
"MIT"
] | 1 | 2019-07-29T04:05:34.000Z | 2019-07-29T04:05:34.000Z | LightOj/1053 - Higher Math.cpp | MhmdRyhn/Programming-Sloution | be189cbf81b14ac7c10d387e259aa23992ba1016 | [
"MIT"
] | null | null | null | LightOj/1053 - Higher Math.cpp | MhmdRyhn/Programming-Sloution | be189cbf81b14ac7c10d387e259aa23992ba1016 | [
"MIT"
] | null | null | null | #include<cstdio>
#include<cmath>
using namespace std;
int main()
{
int t,a=5,b=10,c;
scanf("%d",&t);
for(int i=0; i<t; i++)
{
scanf("%d%d%d",&a,&b,&c);
/*printf("Direct: %s\n",(a>b and a>c and a*a==(b*b+c*c))? "yes":
((b>a and b>c and b*b==(a*a+c*c))? "yes":((c*c==(a*a+b*b))? "yes":"no")));
*/
printf("Case %d: ",i+1);
if(a>b and a>c)
{
if(a*a==(b*b+c*c))
printf("yes");
else
printf("no");
}
else if(b>c and b>a)
{
if(b*b==(a*a+c*c))
printf("yes");
else
printf("no");
}
else
{
if(c*c==(a*a+b*b))
printf("yes");
else
printf("no");
}
printf("\n");
}
return 0;
}
| 19.666667 | 89 | 0.328814 | MhmdRyhn |
1fe36009b980067522a5cde822fabc2266624f9a | 461 | cpp | C++ | X-Engine/src/XEngine/Core/Window.cpp | JohnMichaelProductions/X-Engine | 218ffcf64bfe5d5aed51b483c6f6986831ceeec4 | [
"Apache-2.0"
] | 4 | 2020-02-17T07:08:26.000Z | 2020-08-07T21:35:12.000Z | X-Engine/src/XEngine/Core/Window.cpp | JohnMichaelProductions/X-Engine | 218ffcf64bfe5d5aed51b483c6f6986831ceeec4 | [
"Apache-2.0"
] | 25 | 2020-03-08T05:35:25.000Z | 2020-07-08T01:59:52.000Z | X-Engine/src/XEngine/Core/Window.cpp | JohnMichaelProductions/X-Engine | 218ffcf64bfe5d5aed51b483c6f6986831ceeec4 | [
"Apache-2.0"
] | 1 | 2020-10-15T12:39:29.000Z | 2020-10-15T12:39:29.000Z | // Source file for Window class, decides to create a window based on the platform
#include "Xpch.h"
#include "XEngine/Core/Window.h"
#ifdef XPLATFORM_WINDOWS
#include "Platforms/OperatingSystems/Windows10/Win10Window.h"
#endif
namespace XEngine
{
Scope<Window> Window::Create(const WindowProps& props)
{
#ifdef XPLATFORM_WINDOWS
return CreateScope<Win10Window>(props);
#else
XCORE_ASSERT(false, "Unknown Platform");
return nullptr;
#endif
}
} | 25.611111 | 81 | 0.759219 | JohnMichaelProductions |
1fe3b07329a19727c15b39fc56ad871b7c105468 | 251 | cpp | C++ | src/events/set_context.cpp | Damdoshi/LibLapin | 800e0f17ed8f3c47797c48feea4c280bb0e4bdc9 | [
"BSD-3-Clause"
] | 38 | 2016-07-30T09:35:19.000Z | 2022-03-04T10:13:48.000Z | src/events/set_context.cpp | Elania-Marvers/LibLapin | 800e0f17ed8f3c47797c48feea4c280bb0e4bdc9 | [
"BSD-3-Clause"
] | 15 | 2017-02-12T19:20:52.000Z | 2021-06-09T09:30:52.000Z | src/events/set_context.cpp | Elania-Marvers/LibLapin | 800e0f17ed8f3c47797c48feea4c280bb0e4bdc9 | [
"BSD-3-Clause"
] | 12 | 2016-10-06T09:06:59.000Z | 2022-03-04T10:14:00.000Z | // Jason Brillante "Damdoshi"
// Hanged Bunny Studio 2014-2018
//
// Lapin Library
#include <string.h>
#include "lapin_private.h"
void bunny_set_context(const t_bunny_context *context)
{
memcpy(&gl_callback, context, sizeof(gl_callback));
}
| 17.928571 | 57 | 0.729084 | Damdoshi |
1fe7df4ecd4330763d3d8f36d2bdad5419d4f07a | 3,499 | cpp | C++ | Asteroids/src/asteroid.cpp | pscompsci/Asteroids | 6e8f0eba2b8b6893ddee80779ef577e4890c947b | [
"MIT"
] | null | null | null | Asteroids/src/asteroid.cpp | pscompsci/Asteroids | 6e8f0eba2b8b6893ddee80779ef577e4890c947b | [
"MIT"
] | null | null | null | Asteroids/src/asteroid.cpp | pscompsci/Asteroids | 6e8f0eba2b8b6893ddee80779ef577e4890c947b | [
"MIT"
] | null | null | null | /**
* Copyright (c) 2019 Peter Stacey
*
* 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 "asteroid.h"
#include <iostream>
#include "config.h"
Asteroid::Asteroid(double x, double y, double angle, int size)
{
position.x = x;
position.y = y;
angle = angle;
acceleration = { 0.0, 0.0 };
this->size_ = size;
velocity.x = ASTEROID_BASE_SPEED * size * 0.5 * sin(angle * M_PI / 180.0f);
velocity.y = ASTEROID_BASE_SPEED * size * 0.5 * -cos(angle * M_PI / 180.0f);
switch (this->size_)
{
case(1):
points_value_ = LARGE_ASTEROID_SCORE;
break;
case(2):
points_value_ = MEDIUM_ASTEROID_SCORE;
break;
case(3):
points_value_ = SMALL_ASTEROID_SCORE;
break;
default:
points_value_ = 0;
}
}
Asteroid::~Asteroid()
{
}
void Asteroid::Update()
{
position.Add(velocity);
if (position.y < 0.0)
position.y = SCREEN_HEIGHT;
if (position.y > SCREEN_HEIGHT)
position.y = 0.0;
if (position.x < 0.0)
position.x = SCREEN_WIDTH;
if (position.x > SCREEN_WIDTH)
position.x = 0.0;
}
void Asteroid::Render(SDL_Renderer * renderer)
{
double x1 = position.x - (30.0 * 1 / size_);
double y1 = position.y + (0.0 * 1 / size_);
double x2 = position.x - (10.0 * 1 / size_);
double y2 = position.y - (25.0 * 1 / size_);
double x3 = position.x + (0.0 * 1 / size_);
double y3 = position.y - (30.0 * 1 / size_);
double x4 = position.x + (25.0 * 1 / size_);
double y4 = position.y - (20.0 * 1 / size_);
double x5 = position.x + (30.0 * 1 / size_);
double y5 = position.y + (0.0 * 1 / size_);
double x6 = position.x + (20.0 * 1 / size_);
double y6 = position.y + (20.0 * 1 / size_);
double x7 = position.x + (0.0 * 1 / size_);
double y7 = position.y + (30.0 * 1 / size_);
double x8 = position.x - (25.0 * 1 / size_);
double y8 = position.y + (25.0 * 1 / size_);
SDL_SetRenderDrawColor(renderer, 255, 255, 255, SDL_ALPHA_OPAQUE);
SDL_RenderDrawLine(renderer, x1, y1, x2, y2);
SDL_RenderDrawLine(renderer, x2, y2, x3, y3);
SDL_RenderDrawLine(renderer, x3, y3, x4, y4);
SDL_RenderDrawLine(renderer, x4, y4, x5, y5);
SDL_RenderDrawLine(renderer, x5, y5, x6, y6);
SDL_RenderDrawLine(renderer, x6, y6, x7, y7);
SDL_RenderDrawLine(renderer, x7, y7, x8, y8);
SDL_RenderDrawLine(renderer, x8, y8, x1, y1);
SDL_SetRenderDrawColor(renderer, 0, 0, 0, SDL_ALPHA_OPAQUE);
}
bool Asteroid::CollidesWith(GameObject * object)
{
return false;
}
int Asteroid::GetSize()
{
return size_;
}
int Asteroid::GetPointsValue()
{
return points_value_;
}
| 29.905983 | 81 | 0.68934 | pscompsci |
1fe9a4a014c4de1d662efc55e8903f248f620597 | 4,554 | cpp | C++ | src/Magnum/Math/Test/AngleTest.cpp | TUZIHULI/magnum | 1f6ae8f359976e5b2f1b9649342434a00a6ccbe1 | [
"MIT"
] | 1 | 2019-05-09T03:31:10.000Z | 2019-05-09T03:31:10.000Z | src/Magnum/Math/Test/AngleTest.cpp | TUZIHULI/magnum | 1f6ae8f359976e5b2f1b9649342434a00a6ccbe1 | [
"MIT"
] | null | null | null | src/Magnum/Math/Test/AngleTest.cpp | TUZIHULI/magnum | 1f6ae8f359976e5b2f1b9649342434a00a6ccbe1 | [
"MIT"
] | null | null | null | /*
This file is part of Magnum.
Copyright © 2010, 2011, 2012, 2013, 2014
Vladimír Vondruš <[email protected]>
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 <sstream>
#include <Corrade/TestSuite/Tester.h>
#include "Magnum/Math/Angle.h"
namespace Magnum { namespace Math { namespace Test {
class AngleTest: public Corrade::TestSuite::Tester {
public:
explicit AngleTest();
void construct();
void literals();
void conversion();
void debugDeg();
void debugRad();
};
typedef Math::Deg<Float> Deg;
typedef Math::Rad<Float> Rad;
#ifndef MAGNUM_TARGET_GLES
typedef Math::Deg<Double> Degd;
typedef Math::Rad<Double> Radd;
#endif
AngleTest::AngleTest() {
addTests({&AngleTest::construct,
&AngleTest::literals,
&AngleTest::conversion,
&AngleTest::debugDeg,
&AngleTest::debugRad});
}
void AngleTest::construct() {
/* Default constructor */
constexpr Deg m;
CORRADE_COMPARE(Float(m), 0.0f);
#ifndef MAGNUM_TARGET_GLES
constexpr Degd a;
CORRADE_COMPARE(Double(a), 0.0);
#else
constexpr Deg a;
CORRADE_COMPARE(Float(a), 0.0f);
#endif
/* Value constructor */
constexpr Deg b(25.0);
CORRADE_COMPARE(Float(b), 25.0f);
#ifndef MAGNUM_TARGET_GLES
constexpr Radd n(3.14);
CORRADE_COMPARE(Double(n), 3.14);
#else
constexpr Rad n(3.14);
CORRADE_COMPARE(Float(n), 3.14f);
#endif
/* Copy constructor */
constexpr Deg c(b);
CORRADE_COMPARE(c, b);
#ifndef MAGNUM_TARGET_GLES
constexpr Radd o(n);
CORRADE_COMPARE(o, n);
#else
constexpr Rad o(n);
CORRADE_COMPARE(o, n);
#endif
/* Conversion operator */
constexpr Rad p(n);
CORRADE_COMPARE(Float(p), 3.14f);
#ifndef MAGNUM_TARGET_GLES
constexpr Degd d(b);
CORRADE_COMPARE(Double(d), 25.0);
#else
constexpr Deg d(b);
CORRADE_COMPARE(Float(d), 25.0f);
#endif
}
void AngleTest::literals() {
#ifndef MAGNUM_TARGET_GLES
constexpr auto a = 25.0_deg;
CORRADE_VERIFY((std::is_same<decltype(a), const Degd>::value));
CORRADE_COMPARE(Double(a), 25.0);
#endif
constexpr auto b = 25.0_degf;
CORRADE_VERIFY((std::is_same<decltype(b), const Deg>::value));
CORRADE_COMPARE(Float(b), 25.0f);
#ifndef MAGNUM_TARGET_GLES
constexpr auto m = 3.14_rad;
CORRADE_VERIFY((std::is_same<decltype(m), const Radd>::value));
CORRADE_COMPARE(Double(m), 3.14);
#endif
constexpr auto n = 3.14_radf;
CORRADE_VERIFY((std::is_same<decltype(n), const Rad>::value));
CORRADE_COMPARE(Float(n), 3.14f);
}
void AngleTest::conversion() {
/* Implicit conversion should be allowed */
constexpr Deg a = Rad(1.57079633f);
CORRADE_COMPARE(Float(a), 90.0f);
constexpr Rad b = Deg(90.0f);
CORRADE_COMPARE(Float(b), 1.57079633f);
}
void AngleTest::debugDeg() {
std::ostringstream o;
Debug(&o) << Deg(90.0f);
CORRADE_COMPARE(o.str(), "Deg(90)\n");
/* Verify that this compiles */
o.str({});
Debug(&o) << Deg(56.0f) - Deg(34.0f);
CORRADE_COMPARE(o.str(), "Deg(22)\n");
}
void AngleTest::debugRad() {
std::ostringstream o;
Debug(&o) << Rad(1.5708f);
CORRADE_COMPARE(o.str(), "Rad(1.5708)\n");
/* Verify that this compiles */
o.str({});
Debug(&o) << Rad(1.5708f) - Rad(3.1416f);
CORRADE_COMPARE(o.str(), "Rad(-1.5708)\n");
}
}}}
CORRADE_TEST_MAIN(Magnum::Math::Test::AngleTest)
| 27.93865 | 78 | 0.658981 | TUZIHULI |
1feeef5effe80b026453b93f9abee6cc83be6c80 | 3,383 | cpp | C++ | sourceCode/dotNet4.6/vb/language/shared/pageprotect.cpp | csoap/csoap.github.io | 2a8db44eb63425deff147652b65c5912f065334e | [
"Apache-2.0"
] | 5 | 2017-03-03T02:13:16.000Z | 2021-08-18T09:59:56.000Z | sourceCode/dotNet4.6/vb/language/shared/pageprotect.cpp | 295007712/295007712.github.io | 25241dbf774427545c3ece6534be6667848a6faf | [
"Apache-2.0"
] | null | null | null | sourceCode/dotNet4.6/vb/language/shared/pageprotect.cpp | 295007712/295007712.github.io | 25241dbf774427545c3ece6534be6667848a6faf | [
"Apache-2.0"
] | 4 | 2016-11-15T05:20:12.000Z | 2021-11-13T16:32:11.000Z | //-------------------------------------------------------------------------------------------------
//
// Copyright (c) Microsoft Corporation. All rights reserved.
//
// Page Heap management. Ruthlessly stolen from the C# team. Please notify [....] and [....]
// about any changes to this file. It is likely the change will need to be mirrored in the C#
// implementation
//
//-------------------------------------------------------------------------------------------------
#include "StdAfx.h"
#include "stdafx.h"
#define PROTECT
#ifdef DEBUGPROTECT
struct ITEM
{
void * a;
size_t sz;
void * np;
size_t nsz;
int ts;
DWORD level;
DWORD origOldLevel;
DWORD oldLevel;
};
static ITEM items[1000];
int g_current = 0;
int g_large = 0;
void dumpItem(void * a, size_t sz, void * np, size_t nsz, DWORD level, DWORD origOld, DWORD oldLevel)
{
items[g_current].a = a;
items[g_current].sz = sz;
items[g_current].np = np;
items[g_current].nsz = nsz;
items[g_current].level = level;
items[g_current].origOldLevel = origOld;
items[g_current].oldLevel = oldLevel;
items[g_current].ts = g_large;
g_current ++;
g_large ++;
if (g_current == 1000)
g_current = 0;
}
#endif // DEBUGPROTECT
ProtectedEntityFlagsEnum const whatIsProtected = ProtectedEntityFlags::Nothing;
void ComputePagesFromAddress(void * addr, size_t size, size_t * pageFrom, size_t * pageTo)
{
size_t SYSTEM_PAGE_SIZE = GetSystemPageSize();
size_t lowerByFrom = ((size_t)addr) % SYSTEM_PAGE_SIZE;
size_t lowerByTo = (((size_t)addr) + size) % SYSTEM_PAGE_SIZE;
*pageFrom = (size_t) addr - lowerByFrom;
*pageTo = ((size_t) addr + size) - lowerByTo;
}
DWORD PageProtect::ToggleWrite(ProtectedEntityFlagsEnum entity, void * p, size_t sz, DWORD level)
{
if (!PageProtect::IsEntityProtected(entity))
return PAGE_READWRITE;
ProtectionToggleLock toggleLock;
size_t SYSTEM_PAGE_SIZE = GetSystemPageSize();
size_t lowerBy = ((size_t)p) % SYSTEM_PAGE_SIZE;
size_t nsz = sz + lowerBy;
nsz = nsz - (nsz % SYSTEM_PAGE_SIZE) + SYSTEM_PAGE_SIZE * ((nsz % SYSTEM_PAGE_SIZE) == 0 ? 0 : 1);
DWORD oldFlags, origOldFlags;
void * np = (void*)(((size_t)p) - lowerBy);
#ifdef PROTECT
BOOL succeeded = VirtualProtect(np, nsz, level, &oldFlags);
VSASSERT(succeeded, "Invalid");
#ifdef DEBUGPROTECT
if (level == PAGE_READWRITE)
{
BYTE oldValue = *(BYTE*)p;
*(BYTE*)p = 0;
*(BYTE*)p = oldValue;
}
#endif // DEBUGPROTECT
#else // PROTECT
oldFlags = PAGE_READWRITE;
#endif // !PROTECT
origOldFlags = oldFlags;
if (oldFlags & (PAGE_NOACCESS | PAGE_EXECUTE))
{
oldFlags = PAGE_NOACCESS;
}
else if (oldFlags & (PAGE_READONLY | PAGE_EXECUTE_READ))
{
oldFlags = PAGE_READONLY;
}
else
{
VSASSERT(oldFlags & (PAGE_READWRITE | PAGE_EXECUTE_READWRITE | PAGE_EXECUTE_WRITECOPY), "Invalid");
oldFlags = PAGE_READWRITE;
}
#ifdef DEBUGPROTECT
dumpItem(p, sz, np, nsz, level, origOldFlags, oldFlags);
#endif
return oldFlags;
}
CTinyLock memoryProtectionLock;
ProtectionToggleLock::ProtectionToggleLock()
{
locked = memoryProtectionLock.Acquire();
}
ProtectionToggleLock::~ProtectionToggleLock()
{
if (locked)
{
memoryProtectionLock.Release();
}
}
| 24.875 | 107 | 0.623116 | csoap |
1fef2a2de06f16ed0641dda067f59fd59ec07813 | 2,758 | hxx | C++ | gunrock/src/sssp/sssp_problem.hxx | aka-chris/mini | 608751ff11f74e1ee59222399cbf6c9ee92208fb | [
"Apache-2.0"
] | 17 | 2016-08-13T07:19:11.000Z | 2021-05-05T15:19:02.000Z | gunrock/src/sssp/sssp_problem.hxx | aka-chris/mini | 608751ff11f74e1ee59222399cbf6c9ee92208fb | [
"Apache-2.0"
] | 6 | 2016-10-19T02:43:21.000Z | 2020-01-05T07:10:59.000Z | gunrock/src/sssp/sssp_problem.hxx | aka-chris/mini | 608751ff11f74e1ee59222399cbf6c9ee92208fb | [
"Apache-2.0"
] | 7 | 2016-08-15T18:53:17.000Z | 2021-11-02T12:05:36.000Z | #pragma once
#include "problem.hxx"
#include <queue>
#include <utility>
namespace gunrock {
namespace sssp {
struct sssp_problem_t : problem_t {
mem_t<float> d_labels;
mem_t<int> d_preds;
mem_t<int> d_visited;
std::vector<float> labels;
std::vector<int> preds;
int src;
struct data_slice_t {
float *d_labels;
int *d_preds;
float *d_weights;
int *d_visited;
void init(mem_t<float> &_labels, mem_t<int> &_preds, mem_t<float> &_weights, mem_t<int> &_visited) {
d_labels = _labels.data();
d_preds = _preds.data();
d_weights = _weights.data();
d_visited = _visited.data();
}
};
mem_t<data_slice_t> d_data_slice;
std::vector<data_slice_t> data_slice;
sssp_problem_t() {}
sssp_problem_t(const sssp_problem_t& rhs) = delete;
sssp_problem_t& operator=(const sssp_problem_t& rhs) = delete;
sssp_problem_t(std::shared_ptr<graph_device_t> rhs, size_t src, standard_context_t& context) :
problem_t(rhs),
src(src),
data_slice( std::vector<data_slice_t>(1) ) {
labels = std::vector<float>(rhs->num_nodes, std::numeric_limits<float>::max());
preds = std::vector<int>(rhs->num_nodes, -1);
labels[src] = 0;
d_labels = to_mem(labels, context);
d_preds = to_mem(preds, context);
d_visited = fill(-1, rhs->num_nodes, context);
data_slice[0].init(d_labels, d_preds, gslice->d_col_values, d_visited);
d_data_slice = to_mem(data_slice, context);
}
void extract() {
mgpu::dtoh(labels, d_labels.data(), gslice->num_nodes);
mgpu::dtoh(preds, d_preds.data(), gslice->num_nodes);
}
void cpu(std::vector<int> &validation_preds,
std::vector<int> &row_offsets,
std::vector<int> &col_indices,
std::vector<float> &col_values) {
// CPU SSSP for validation (Dijkstra's algorithm)
typedef std::pair<int, int> ipair;
// initialize input frontier
std::priority_queue<ipair, std::vector<ipair>, std::greater<ipair> > pq;
std::vector<int> dist(row_offsets.size(), std::numeric_limits<int>::max());
pq.push(std::make_pair(-1, src));
validation_preds[src] = -1;
dist[src] = 0;
while(!pq.empty())
{
int u = pq.top().second;
pq.pop();
for (int i = row_offsets[u]; i < row_offsets[u+1]; ++i) {
int v = col_indices[i];
int w = col_values[i];
if (dist[v] > dist[u] + w) {
validation_preds[v] = u;
dist[v] = dist[u] + w;
pq.push(std::make_pair(dist[u], v));
}
}
}
}
};
} //end sssp
} //end gunrock
| 29.655914 | 106 | 0.583394 | aka-chris |
1ff25378664e776e8db14948e7a4dad23f5604fd | 449 | cpp | C++ | Library/Standard/Primitives/ErrorMessage.cpp | dwhobrey/MindCausalModellingLibrary | 797d716e785d2dcd5c373ab385c20d3a74bbfcb0 | [
"BSD-3-Clause"
] | null | null | null | Library/Standard/Primitives/ErrorMessage.cpp | dwhobrey/MindCausalModellingLibrary | 797d716e785d2dcd5c373ab385c20d3a74bbfcb0 | [
"BSD-3-Clause"
] | null | null | null | Library/Standard/Primitives/ErrorMessage.cpp | dwhobrey/MindCausalModellingLibrary | 797d716e785d2dcd5c373ab385c20d3a74bbfcb0 | [
"BSD-3-Clause"
] | null | null | null | #include "PlatoIncludes.h"
#include "Strings.h"
#include "ErrorMessage.h"
namespace Plato {
ErrorMessage::ErrorMessage(int errorCode, const string& errorMessage) {
mErrorCode = errorCode;
mErrorMessage = &errorMessage;
}
ErrorMessage::~ErrorMessage() {
delete mErrorMessage;
}
string& ErrorMessage::StatusReport() {
return Strings::Format("E%x:%s",mErrorCode,mErrorMessage->c_str());
}
}
| 21.380952 | 75 | 0.659243 | dwhobrey |
1ff82f38a6ab2896e55589947d3c34ae68a56b54 | 929 | cpp | C++ | Chapter2/Section2.1/sort3/sort3.cpp | suzyz/USACO | c7f58850f20693fedfc30ef462f898d20d002396 | [
"MIT"
] | null | null | null | Chapter2/Section2.1/sort3/sort3.cpp | suzyz/USACO | c7f58850f20693fedfc30ef462f898d20d002396 | [
"MIT"
] | null | null | null | Chapter2/Section2.1/sort3/sort3.cpp | suzyz/USACO | c7f58850f20693fedfc30ef462f898d20d002396 | [
"MIT"
] | null | null | null | /*
ID: suzyzha1
PROG: sort3
LANG: C++
*/
#include <iostream>
#include <fstream>
#include <cstring>
#include <cmath>
#include <algorithm>
using namespace std;
int n;
int seq[1010];
int num[4];
int main()
{
fstream fin("sort3.in",ios::in);
fstream fout("sort3.out",ios::out);
fin>>n;
for(int i=1;i<=n;i++)
{
fin>>seq[i];
num[seq[i]]++;
}
int mis21=0,mis31=0,mis1=0,mis23=0,mis32=0,mis12=0,mis13=0;
for(int i=1;i<=n;i++)
{
switch(seq[i])
{
case 1:
if(i>num[1]) mis1++;
if(i>num[1] && i<=num[1]+num[2]) mis12++;
if(i>num[1]+num[2]) mis13++;
break;
case 2:
if(i<=num[1]) mis21++;
else
if(i>num[1]+num[2]) mis23++;
break;
case 3:
if(i<=num[1]) mis31++;
else
if(i<=num[1]+num[2]) mis32++;
break;
}
}
int ans=mis1;
if(mis12>=mis21) ans+=mis32+mis12-mis21;
else ans+=mis23+mis13-mis31;
fout<<ans<<endl;
fin.close();
fout.close();
return 0;
}
| 14.075758 | 60 | 0.559742 | suzyz |
1ffac9eb99f33b232992979ba8096bc5e088038c | 1,273 | hpp | C++ | include/common/logging.hpp | jonas-ellert/gsaca-lyndon | b36110cb270b51f29035f8d53d798d56745deaac | [
"MIT"
] | null | null | null | include/common/logging.hpp | jonas-ellert/gsaca-lyndon | b36110cb270b51f29035f8d53d798d56745deaac | [
"MIT"
] | 1 | 2021-10-03T23:31:07.000Z | 2021-10-31T03:12:07.000Z | include/common/logging.hpp | jonas-ellert/gsaca-lyndon | b36110cb270b51f29035f8d53d798d56745deaac | [
"MIT"
] | null | null | null | #pragma once
#include <string>
#include <sstream>
#define LOG_VERBOSE if constexpr (false) std::cout
#define LOG_STATS if constexpr (true) ::gsaca_lyndon::clog
namespace gsaca_lyndon {
namespace logging_internal {
constexpr uint64_t LOG_LIMIT = 1ULL << 20;
struct temporary_logger {
std::string key;
template<typename T>
void operator<<(T &&);
};
}
struct {
private:
uint64_t size = logging_internal::LOG_LIMIT;
std::stringstream ss;
public:
friend class logging_internal::temporary_logger;
inline auto operator<<(std::string &&str) {
return logging_internal::temporary_logger{std::move(str)};
}
inline std::string get_and_clear_log() {
auto result = ss.str();
size = logging_internal::LOG_LIMIT;
ss = std::stringstream();
return result;
}
} clog;
template<typename T>
void logging_internal::temporary_logger::operator<<(T &&t) {
std::string value = std::to_string(t);
uint64_t add = 2 + key.size() + value.size();
if (clog.size + add < logging_internal::LOG_LIMIT) {
clog.size += add;
clog.ss << " " << std::move(key) << "=" << std::move(value);
} else {
clog.size = 1 + key.size() + value.size();
clog.ss = std::stringstream();
clog.ss << std::move(key) << "=" << std::move(value);
}
}
}
| 21.948276 | 64 | 0.660644 | jonas-ellert |
950717ecbe0d897e317149de011fceba5a33e00d | 1,641 | cpp | C++ | src/gui/DeleteConfig.cpp | faroub/project-qt-cpp-cmake-IO-communication | f116b75766afce99664a6d82f4d6b10317b754a1 | [
"MIT"
] | null | null | null | src/gui/DeleteConfig.cpp | faroub/project-qt-cpp-cmake-IO-communication | f116b75766afce99664a6d82f4d6b10317b754a1 | [
"MIT"
] | null | null | null | src/gui/DeleteConfig.cpp | faroub/project-qt-cpp-cmake-IO-communication | f116b75766afce99664a6d82f4d6b10317b754a1 | [
"MIT"
] | null | null | null | #include <QPushButton>
#include <QHBoxLayout>
#include <QGridLayout>
#include <QListWidget>
#include "DeleteConfig.h"
gui::DeleteConfig::DeleteConfig(QWidget *ap_parent, utils::ConfigData *ap_ConfigData) :
QDialog(ap_parent),
mp_configFileList(new QListWidget(this))
{
mp_configData = ap_ConfigData;
QPushButton *lp_okButton = new QPushButton(tr("OK"));
QPushButton *lp_cancelButton = new QPushButton(tr("Cancel"));
QHBoxLayout *lp_hLayout = new QHBoxLayout();
lp_hLayout->addWidget(lp_okButton);
lp_hLayout->addWidget(lp_cancelButton);
QGridLayout *lp_mainGridLayout = new QGridLayout();
QStringList myStringList = QStringList() << "foo" << "bar" << "baz";
mp_configFileList->addItems(myStringList);
lp_mainGridLayout->addWidget(mp_configFileList,0,0,4,2);
lp_mainGridLayout->addLayout(lp_hLayout,4,1,1,1);
setLayout(lp_mainGridLayout);
setSizePolicy(QSizePolicy::Fixed, QSizePolicy::Fixed);
setFixedSize(sizeHint().width(),sizeHint().height());
setWindowTitle(tr("Delete Configuration"));
}
gui::DeleteConfig::~DeleteConfig()
{
}
void gui::DeleteConfig::open()
{
qInfo("Open delete configuration widget");
QDialog::open();
}
void gui::DeleteConfig::close()
{
qInfo("Close delete configuration widget");
QDialog::close();
}
void gui::DeleteConfig::fillConfigFileList()
{
//QStringList myStringList = QStringList() << "foo" << "bar" << "baz";
mp_configFileList->addItem("farid");
mp_configFileList->addItem("farid");
mp_configFileList->addItem("farid");
}
| 27.813559 | 87 | 0.678854 | faroub |
9507d2fb345fa46173949496ff8f87b669772505 | 3,923 | cpp | C++ | Lab5/1356M_Linux/tools.cpp | HoverWings/HUST_RFID_Labs | 8f824fb21b47cb92f35e1d90c7faaafe97cd38dd | [
"MIT"
] | null | null | null | Lab5/1356M_Linux/tools.cpp | HoverWings/HUST_RFID_Labs | 8f824fb21b47cb92f35e1d90c7faaafe97cd38dd | [
"MIT"
] | 1 | 2019-05-29T02:44:42.000Z | 2019-05-29T02:44:42.000Z | Lab5/1356M_Windows/tools.cpp | HoverWings/HUST_RFID_Labs | 8f824fb21b47cb92f35e1d90c7faaafe97cd38dd | [
"MIT"
] | null | null | null | #include "tools.h"
#include <QDebug>
Tools::Tools(QObject *parent) : QObject(parent)
{
list = new QStringList();
}
//获取当前PC可用的串口名
QStringList Tools::getSerialName()
{
QStringList temp;
foreach (const QSerialPortInfo &info, QSerialPortInfo::availablePorts())
{
QSerialPort serial;
serial.setPort(info);
if (serial.open(QIODevice::ReadWrite))
{
if(! list->contains(info.portName(),Qt::CaseSensitive))
list->insert(0,info.portName());
serial.close();
temp << info.portName();
}
}
for(int i = 0 ; i < list->size() ; i ++)
{
if(!temp.contains(list->at(i)))
list->removeAt(i);
}
return *list;
}
///获取当前日期和时间
QString Tools::CurrentDateTime()
{
QDateTime dt;
QTime time;
QDate date;
dt.setTime(time.currentTime());
dt.setDate(date.currentDate());
return dt.toString("yyyy-MM-dd hh:mm:ss");
}
///获取当前的时间
QString Tools::CurrentTime()
{
QTime time;
return time.currentTime().toString("hh:mm:ss");
}
///获取当前的时间
QString Tools::CurrentMTime()
{
QTime time;
return time.currentTime().toString("hh:mm:ss.zzz");
}
///普通字符串转为16进制字符串
QString Tools::CharStringtoHexString(QString space, const char * src, int len)
{
QString hex = "";
if(space == NULL)
{
for(int i = 0 ; i < len ; i ++)
{
hex += QString("%1").arg(src[i]&0xFF,2,16,QLatin1Char('0'));
}
return hex.toUpper();
}
else
{
for(int i = 0 ; i < len ; i ++)
{
hex += space + QString("%1").arg(src[i]&0xFF,2,16,QLatin1Char('0'));
}
return hex.right(hex.length() - space.length()).toUpper();
}
}
//QString 转 Hex char *
quint8 Tools::StringToHex(QString string, quint8 *hex)
{
QString temp;
quint8 len = string.length();
for(quint8 i=0; i<len; i+=2)
{
temp = string.mid(i, 2);
hex[i/2] = (quint8)temp.toInt(0,16);
}
return len/2;
}
///普通字符串转为16进制字符串
QString Tools::CharStringtoHexString(QString space, const char * src, int start, int end)
{
QString hex = "";
if(space == NULL)
{
for(int i = start ; i < end ; i ++)
{
hex += QString("%1").arg(src[i]&0xFF,2,16,QLatin1Char('0'));
}
return hex.toUpper();
}
else
{
for(int i = start ; i < end ; i ++)
{
hex += space + QString("%1").arg(src[i]&0xFF,2,16,QLatin1Char('0'));
}
return hex.right(hex.length() - space.length()).toUpper();
}
}
//用于导出数据库中的数据到文件,csv格式的文件可以用Excel打开
void Tools::export_table(const QAbstractItemModel &model)
{
QString fileName = QFileDialog::getSaveFileName(0, QObject::tr("保存记录"), "/", "files(*.csv)");
QFile file(fileName);
if(file.open(QFile::WriteOnly|QFile::Truncate)){
QTextStream out(&file);
QString str;
str.clear();
for(int i=0; i<model.columnCount(); i++)
str.append(model.headerData(i, Qt::Horizontal).toString()).append(",");
out<<str<<"\r\n";
for(int row=0; row<model.rowCount(); row++){
str.clear();
for(int col=0; col<model.columnCount(); col++)
str.append(model.data(model.index(row,col)).toString()).append(",");
out<<str<<"\r\n";
}
file.close();
}
}
//两个时间只差与天数的比较
bool Tools::isOverdue(QString borrowTime, QString returnTime, int days)
{
QTime start = QTime::fromString(borrowTime);
QTime end = QTime::fromString(returnTime);
int secs = start.secsTo(end);
qDebug() << secs;
if(days*24*3600 < secs)//未超时
return true;
else
return false;
}
//TODO:两个时间只差与天数的比较
//时间戳到转换为时间
//查询表项
| 26.328859 | 98 | 0.536324 | HoverWings |
950c962c5c01b79bf0009f811ca6a88348499256 | 2,837 | cpp | C++ | src/GameHostStarter.cpp | maximaximal/piga | 54530c208e59eaaf8d44c1f8d640f5ec028d4126 | [
"Zlib"
] | 2 | 2015-01-07T18:36:39.000Z | 2015-01-08T13:54:43.000Z | src/GameHostStarter.cpp | maximaximal/piga | 54530c208e59eaaf8d44c1f8d640f5ec028d4126 | [
"Zlib"
] | null | null | null | src/GameHostStarter.cpp | maximaximal/piga | 54530c208e59eaaf8d44c1f8d640f5ec028d4126 | [
"Zlib"
] | null | null | null | #include <pigaco/GameHostStarter.hpp>
#include <QDir>
#include <easylogging++.h>
namespace pigaco
{
GameHostStarter::GameHostStarter()
: QObject()
{
m_gameProcess = new QProcess(this);
connect(m_gameProcess, SIGNAL(finished(int,QProcess::ExitStatus)), this, SLOT(gameEnded(int,QProcess::ExitStatus)));
connect(m_gameProcess, SIGNAL(started()), this, SLOT(gameStarted()));
connect(m_gameProcess, SIGNAL(error(QProcess::ProcessError)), this, SLOT(gameError(QProcess::ProcessError)));
}
GameHostStarter::~GameHostStarter()
{
if(isRunning(true))
m_gameProcess->terminate();
delete m_gameProcess;
}
bool GameHostStarter::isRunning(bool fsCheck)
{
//FS-Check can be ignored, because the boolean is getting changed by an Qt event in this implementation
//instead of a temporary file check.
return m_running;
}
void GameHostStarter::startGame(const std::string &command, const std::string &arguments)
{
LOG(INFO) << "Starting \"" << getConfig(ConfigValue::Name) << "\" with executable \"" << QDir::currentPath().toStdString() + "/" + command << "\".";
LOG(INFO) << "Using arguments: \"" << arguments << "\"";
m_gameProcess->start(QDir::currentPath() + "/" + QString::fromStdString(command) + " " + QString::fromStdString(arguments));
}
void GameHostStarter::gameEnded(int code, QProcess::ExitStatus status)
{
m_running = false;
QString exitStatus;
switch(status)
{
case QProcess::NormalExit:
exitStatus = "Normal";
break;
case QProcess::CrashExit:
exitStatus = "Crashed";
break;
}
LOG(INFO) << "Exited \"" << getConfig(ConfigValue::Name) << "\" with exit code \"" << exitStatus.toStdString() << "\".";
}
void GameHostStarter::gameStarted()
{
m_running = true;
LOG(INFO) << "Started \"" << getConfig(ConfigValue::Name) << "\"!";
}
void GameHostStarter::gameError(QProcess::ProcessError error)
{
LOG(WARNING) << "There was an error while starting or running \"" << getConfig(ConfigValue::Name) << "\"!";
switch(error)
{
case QProcess::ProcessError::FailedToStart:
LOG(WARNING) << "The executable failed to start.";
break;
case QProcess::ProcessError::Crashed:
LOG(WARNING) << "The game crashed!";
break;
case QProcess::ProcessError::Timedout:
LOG(WARNING) << "The game timed out!";
break;
case QProcess::ProcessError::ReadError:
LOG(WARNING) << "There was a read error!";
break;
case QProcess::ProcessError::WriteError:
LOG(WARNING) << "There was a write error!";
break;
case QProcess::ProcessError::UnknownError:
LOG(WARNING) << "The error was unknown!";
break;
}
}
}
| 30.836957 | 152 | 0.627071 | maximaximal |
950ddcf01a642ac46f2a51c94f79a581ed10ec0b | 160 | cpp | C++ | src/Updatable.cpp | Xansta/SeriousProton | f4f79d28bf292fbacb61a863a427b55da6d49774 | [
"MIT"
] | 62 | 2015-01-07T14:47:47.000Z | 2021-09-06T09:52:29.000Z | src/Updatable.cpp | Xansta/SeriousProton | f4f79d28bf292fbacb61a863a427b55da6d49774 | [
"MIT"
] | 70 | 2015-03-09T07:08:00.000Z | 2022-02-27T07:28:24.000Z | src/Updatable.cpp | Xansta/SeriousProton | f4f79d28bf292fbacb61a863a427b55da6d49774 | [
"MIT"
] | 49 | 2015-03-07T11:42:06.000Z | 2022-02-20T11:06:05.000Z | #include "Updatable.h"
PVector<Updatable> updatableList;
Updatable::Updatable()
{
updatableList.push_back(this);
}
Updatable::~Updatable()
{
//dtor
}
| 13.333333 | 35 | 0.7 | Xansta |
95120dff98db66a662c81530e469b7ea3b900831 | 6,616 | cpp | C++ | src/main.cpp | LiangGuoYu/spoa | 9dbcd7aa223c1e7fa789530c39fcd143d3886d3b | [
"MIT"
] | 1 | 2022-01-13T09:02:18.000Z | 2022-01-13T09:02:18.000Z | src/main.cpp | LiangGuoYu/spoa | 9dbcd7aa223c1e7fa789530c39fcd143d3886d3b | [
"MIT"
] | null | null | null | src/main.cpp | LiangGuoYu/spoa | 9dbcd7aa223c1e7fa789530c39fcd143d3886d3b | [
"MIT"
] | 1 | 2019-08-16T01:17:09.000Z | 2019-08-16T01:17:09.000Z | #include <getopt.h>
#include <cstdint>
#include <string>
#include <iostream>
#include <exception>
#include "sequence.hpp"
#include "spoa/spoa.hpp"
#include "bioparser/bioparser.hpp"
static const std::string version = "v3.0.1";
static struct option options[] = {
{"algorithm", required_argument, nullptr, 'l'},
{"result", required_argument, nullptr, 'r'},
{"dot", required_argument, nullptr, 'd'},
{"version", no_argument, nullptr, 'v'},
{"help", no_argument, nullptr, 'h'},
{nullptr, 0, nullptr, 0}
};
void help();
int main(int argc, char** argv) {
std::int8_t m = 5;
std::int8_t n = -4;
std::int8_t g = -8;
std::int8_t e = -6;
std::int8_t q = -10;
std::int8_t c = -4;
std::uint8_t algorithm = 0;
std::uint8_t result = 0;
std::string dot_path = "";
char opt;
while ((opt = getopt_long(argc, argv, "m:n:g:e:q:c:l:r:d:h", options, nullptr)) != -1) {
switch (opt) {
case 'm': m = atoi(optarg); break;
case 'n': n = atoi(optarg); break;
case 'g': g = atoi(optarg); break;
case 'e': e = atoi(optarg); break;
case 'q': q = atoi(optarg); break;
case 'c': c = atoi(optarg); break;
case 'l': algorithm = atoi(optarg); break;
case 'r': result = atoi(optarg); break;
case 'd': dot_path = optarg; break;
case 'v': std::cout << version << std::endl; return 0;
case 'h': help(); return 0;
default: return 1;
}
}
if (optind >= argc) {
std::cerr << "[spoa::] error: missing input file!" << std::endl;
help();
return 1;
}
std::string sequences_path = argv[optind];
auto is_suffix = [](const std::string& src, const std::string& suffix) -> bool {
if (src.size() < suffix.size()) {
return false;
}
return src.compare(src.size() - suffix.size(), suffix.size(), suffix) == 0;
};
std::unique_ptr<bioparser::Parser<spoa::Sequence>> sparser = nullptr;
if (is_suffix(sequences_path, ".fasta") || is_suffix(sequences_path, ".fa") ||
is_suffix(sequences_path, ".fasta.gz") || is_suffix(sequences_path, ".fa.gz")) {
sparser = bioparser::createParser<bioparser::FastaParser, spoa::Sequence>(
sequences_path);
} else if (is_suffix(sequences_path, ".fastq") || is_suffix(sequences_path, ".fq") ||
is_suffix(sequences_path, ".fastq.gz") || is_suffix(sequences_path, ".fq.gz")) {
sparser = bioparser::createParser<bioparser::FastqParser, spoa::Sequence>(
sequences_path);
} else {
std::cerr << "[spoa::] error: file " << sequences_path <<
" has unsupported format extension (valid extensions: .fasta, "
".fasta.gz, .fa, .fa.gz, .fastq, .fastq.gz, .fq, .fq.gz)!" <<
std::endl;
return 1;
}
std::unique_ptr<spoa::AlignmentEngine> alignment_engine;
try {
alignment_engine = spoa::createAlignmentEngine(
static_cast<spoa::AlignmentType>(algorithm), m, n, g, e, q, c);
} catch(std::invalid_argument& exception) {
std::cerr << exception.what() << std::endl;
return 1;
}
auto graph = spoa::createGraph();
std::vector<std::unique_ptr<spoa::Sequence>> sequences;
sparser->parse(sequences, -1);
std::size_t max_sequence_size = 0;
for (const auto& it: sequences) {
max_sequence_size = std::max(max_sequence_size, it->data().size());
}
alignment_engine->prealloc(max_sequence_size, 4);
for (const auto& it: sequences) {
auto alignment = alignment_engine->align(it->data(), graph);
try {
graph->add_alignment(alignment, it->data(), it->quality());
} catch(std::invalid_argument& exception) {
std::cerr << exception.what() << std::endl;
return 1;
}
}
if (result == 0 || result == 2) {
std::string consensus = graph->generate_consensus();
std::cout << "Consensus (" << consensus.size() << ")" << std::endl;
std::cout << consensus << std::endl;
}
if (result == 1 || result == 2) {
std::vector<std::string> msa;
graph->generate_multiple_sequence_alignment(msa);
std::cout << "Multiple sequence alignment" << std::endl;
for (const auto& it: msa) {
std::cout << it << std::endl;
}
}
graph->print_dot(dot_path);
return 0;
}
void help() {
std::cout <<
"usage: spoa [options ...] <sequences>\n"
"\n"
" <sequences>\n"
" input file in FASTA/FASTQ format (can be compressed with gzip)\n"
" containing sequences\n"
"\n"
" options:\n"
" -m <int>\n"
" default: 5\n"
" score for matching bases\n"
" -n <int>\n"
" default: -4\n"
" score for mismatching bases\n"
" -g <int>\n"
" default: -8\n"
" gap opening penalty (must be non-positive)\n"
" -e <int>\n"
" default: -6\n"
" gap extension penalty (must be non-positive)\n"
" -q <int>\n"
" default: -10\n"
" gap opening penalty of the second affine function\n"
" (must be non-positive)\n"
" -c <int>\n"
" default: -4\n"
" gap extension penalty of the second affine function\n"
" (must be non-positive)\n"
" -l, --algorithm <int>\n"
" default: 0\n"
" alignment mode:\n"
" 0 - local (Smith-Waterman)\n"
" 1 - global (Needleman-Wunsch)\n"
" 2 - semi-global\n"
" -r, --result <int>\n"
" default: 0\n"
" result mode:\n"
" 0 - consensus\n"
" 1 - multiple sequence alignment\n"
" 2 - 0 & 1\n"
" -d, --dot <file>\n"
" output file for the final POA graph in DOT format\n"
" --version\n"
" prints the version number\n"
" -h, --help\n"
" prints the usage\n"
"\n"
" gap mode:\n"
" linear if g >= e\n"
" affine if g <= q or e >= c\n"
" convex otherwise (default)\n";
}
| 34.103093 | 92 | 0.502418 | LiangGuoYu |
95138877d849e1b0def7a93bc119145943a2b669 | 947 | cpp | C++ | kernel/ports.cpp | shockkolate/shockk-os | 1cbe2e14be6a8dd4bbe808e199284b6979dacdff | [
"Apache-2.0"
] | 2 | 2015-11-16T07:30:38.000Z | 2016-03-26T21:14:42.000Z | kernel/ports.cpp | shockkolate/shockk-os | 1cbe2e14be6a8dd4bbe808e199284b6979dacdff | [
"Apache-2.0"
] | null | null | null | kernel/ports.cpp | shockkolate/shockk-os | 1cbe2e14be6a8dd4bbe808e199284b6979dacdff | [
"Apache-2.0"
] | null | null | null | #include <kernel/ports.h>
uint8_t ports_inb(unsigned short port) {
uint8_t result;
__asm__ __volatile__ ("in %1, %0" : "=a" (result) : "d" (port));
return result;
}
uint16_t ports_ins(unsigned short port) {
uint16_t result;
__asm__ __volatile__ ("in %1, %0" : "=a" (result) : "d" (port));
return result;
}
uint32_t ports_inl(unsigned short port) {
uint32_t result;
__asm__ __volatile__ ("in %1, %0" : "=a" (result) : "d" (port));
return result;
}
void ports_str_ins(unsigned short port, volatile uint16_t *buffer, size_t count) {
__asm__ ("rep insw" : : "d" (port), "c" (count), "D" (buffer) : "memory");
}
void ports_outb(unsigned short port, uint8_t data) {
__asm__ ("out %0, %1" : : "a" (data), "d" (port));
}
void ports_outs(unsigned short port, uint16_t data) {
__asm__ ("out %0, %1" : : "a" (data), "d" (port));
}
void ports_outl(unsigned short port, uint32_t data) {
__asm__ ("out %0, %1" : : "a" (data), "d" (port));
}
| 26.305556 | 82 | 0.634636 | shockkolate |
95142327f8d73d2e272de7cd5d192dec4252d33d | 12,654 | hpp | C++ | inc/Services/StorageAndRetrievalService.hpp | ACubeSAT/ecss-services | 92d81c1ff455d9baef9417e656388c98ec552751 | [
"MIT"
] | null | null | null | inc/Services/StorageAndRetrievalService.hpp | ACubeSAT/ecss-services | 92d81c1ff455d9baef9417e656388c98ec552751 | [
"MIT"
] | null | null | null | inc/Services/StorageAndRetrievalService.hpp | ACubeSAT/ecss-services | 92d81c1ff455d9baef9417e656388c98ec552751 | [
"MIT"
] | null | null | null | #ifndef ECSS_SERVICES_STORAGEANDRETRIEVALSERVICE_HPP
#define ECSS_SERVICES_STORAGEANDRETRIEVALSERVICE_HPP
#include "ECSS_Definitions.hpp"
#include "Service.hpp"
#include "ErrorHandler.hpp"
#include "Helpers/PacketStore.hpp"
#include "etl/map.h"
/**
* Implementation of ST[15] Storage and Retrieval Service, as defined in ECSS-E-ST-70-41C.
*
* This Service:
* - provides the capability to select reports generated by other services and store them into packet stores.
* - allows the ground system to manage the reports in the packet stores and request their downlink.
*
* @author Konstantinos Petridis <[email protected]>
*/
class StorageAndRetrievalService : public Service {
public:
/**
* The type of timestamps that the Storage and Retrieval Subservice assigns to each incoming packet.
*/
enum TimeStampType : uint8_t { StorageBased = 0, PacketBased = 1 };
/**
* Different types of packet retrieval from a packet store, relative to a specified time-tag.
*/
enum TimeWindowType : uint8_t { FromTagToTag = 0, AfterTimeTag = 1, BeforeTimeTag = 2 };
/**
* The type of timestamps that the subservice sets to each incoming telemetry packet.
*/
const TimeStampType timeStamping = PacketBased;
private:
typedef String<ECSSPacketStoreIdSize> packetStoreId;
/**
* All packet stores, held by the Storage and Retrieval Service. Each packet store has its ID as key.
*/
etl::map<packetStoreId, PacketStore, ECSSMaxPacketStores> packetStores;
/**
* Helper function that reads the packet store ID string from a TM[15] message
*/
static inline String<ECSSPacketStoreIdSize> readPacketStoreId(Message& message);
/**
* Helper function that, given a time-limit, deletes every packet stored in the specified packet-store, up to the
* requested time.
*
* @param packetStoreId required to access the correct packet store.
* @param timeLimit the limit until which, packets are deleted.
*/
void deleteContentUntil(const String<ECSSPacketStoreIdSize>& packetStoreId, uint32_t timeLimit);
/**
* Copies all TM packets from source packet store to the target packet-store, that fall between the two specified
* time-tags as per 6.15.3.8.4.d(1) of the standard.
*
* @param request used to read the time-tags, the packet store IDs and to raise errors.
*/
void copyFromTagToTag(Message& request);
/**
* Copies all TM packets from source packet store to the target packet-store, whose time-stamp is after the
* specified time-tag as per 6.15.3.8.4.d(2) of the standard.
*
* @param request used to read the time-tag, the packet store IDs and to raise errors.
*/
void copyAfterTimeTag(Message& request);
/**
* Copies all TM packets from source packet store to the target packet-store, whose time-stamp is before the
* specified time-tag as per 6.15.3.8.4.d(3) of the standard.
*
* @param request used to raise errors.
*/
void copyBeforeTimeTag(Message& request);
/**
* Checks if the two requested packet stores exist.
*
* @param fromPacketStoreId the source packet store, whose content is to be copied.
* @param toPacketStoreId the target packet store, which is going to receive the new content.
* @param request used to raise errors.
* @return true if an error has occurred.
*/
bool checkPacketStores(const String<ECSSPacketStoreIdSize>& fromPacketStoreId,
const String<ECSSPacketStoreIdSize>& toPacketStoreId, Message& request);
/**
* Checks whether the time window makes logical sense (end time should be after the start time)
*
* @param request used to raise errors.
*/
static bool checkTimeWindow(uint32_t startTime, uint32_t endTime, Message& request);
/**
* Checks if the destination packet store is empty, in order to proceed with the copying of packets.
*
* @param toPacketStoreId the target packet store, which is going to receive the new content. Needed for error
* checking.
* @param request used to raise errors.
*/
bool checkDestinationPacketStore(const String<ECSSPacketStoreIdSize>& toPacketStoreId, Message& request);
/**
* Checks if there are no stored timestamps that fall between the two specified time-tags.
*
* @param fromPacketStoreId the source packet store, whose content is to be copied. Needed for error checking.
* @param request used to raise errors.
*
* @note
* This function assumes that `startTime` and `endTime` are valid at this point, so any necessary error checking
* regarding these variables, should have already occurred.
*/
bool noTimestampInTimeWindow(const String<ECSSPacketStoreIdSize>& fromPacketStoreId, uint32_t startTime,
uint32_t endTime, Message& request);
/**
* Checks if there are no stored timestamps that fall between the two specified time-tags.
*
* @param isAfterTimeTag true indicates that we are examining the case of AfterTimeTag. Otherwise, we are referring
* to the case of BeforeTimeTag.
* @param request used to raise errors.
* @param fromPacketStoreId the source packet store, whose content is to be copied.
*/
bool noTimestampInTimeWindow(const String<ECSSPacketStoreIdSize>& fromPacketStoreId, uint32_t timeTag,
Message& request, bool isAfterTimeTag);
/**
* Performs all the necessary error checking for the case of FromTagToTag copying of packets.
*
* @param fromPacketStoreId the source packet store, whose content is to be copied.
* @param toPacketStoreId the target packet store, which is going to receive the new content.
* @param request used to raise errors.
* @return true if an error has occurred.
*/
bool failedFromTagToTag(const String<ECSSPacketStoreIdSize>& fromPacketStoreId,
const String<ECSSPacketStoreIdSize>& toPacketStoreId, uint32_t startTime,
uint32_t endTime, Message& request);
/**
* Performs all the necessary error checking for the case of AfterTimeTag copying of packets.
*
* @param fromPacketStoreId the source packet store, whose content is to be copied.
* @param toPacketStoreId the target packet store, which is going to receive the new content.
* @param request used to raise errors.
* @return true if an error has occurred.
*/
bool failedAfterTimeTag(const String<ECSSPacketStoreIdSize>& fromPacketStoreId,
const String<ECSSPacketStoreIdSize>& toPacketStoreId, uint32_t startTime,
Message& request);
/**
* Performs all the necessary error checking for the case of BeforeTimeTag copying of packets.
*
* @param fromPacketStoreId the source packet store, whose content is to be copied.
* @param toPacketStoreId the target packet store, which is going to receive the new content.
* @param request used to raise errors.
* @return true if an error has occurred.
*/
bool failedBeforeTimeTag(const String<ECSSPacketStoreIdSize>& fromPacketStoreId,
const String<ECSSPacketStoreIdSize>& toPacketStoreId, uint32_t endTime,
Message& request);
/**
* Performs the necessary error checking for a request to start the by-time-range retrieval process.
*
* @param request used to raise errors.
* @return true if an error has occurred.
*/
bool failedStartOfByTimeRangeRetrieval(const String<ECSSPacketStoreIdSize>& packetStoreId, Message& request);
/**
* Forms the content summary of the specified packet-store and appends it to a report message.
*/
void createContentSummary(Message& report, const String<ECSSPacketStoreIdSize>& packetStoreId);
public:
inline static const uint8_t ServiceType = 15;
enum MessageType : uint8_t {
EnableStorageInPacketStores = 1,
DisableStorageInPacketStores = 2,
StartByTimeRangeRetrieval = 9,
DeletePacketStoreContent = 11,
ReportContentSummaryOfPacketStores = 12,
PacketStoreContentSummaryReport = 13,
ChangeOpenRetrievalStartingTime = 14,
ResumeOpenRetrievalOfPacketStores = 15,
SuspendOpenRetrievalOfPacketStores = 16,
AbortByTimeRangeRetrieval = 17,
ReportStatusOfPacketStores = 18,
PacketStoresStatusReport = 19,
CreatePacketStores = 20,
DeletePacketStores = 21,
ReportConfigurationOfPacketStores = 22,
PacketStoreConfigurationReport = 23,
CopyPacketsInTimeWindow = 24,
ResizePacketStores = 25,
ChangeTypeToCircular = 26,
ChangeTypeToBounded = 27,
ChangeVirtualChannel = 28
};
StorageAndRetrievalService() = default;
/**
* Adds new packet store into packet stores.
*/
void addPacketStore(const String<ECSSPacketStoreIdSize>& packetStoreId, const PacketStore& packetStore);
/**
* Adds telemetry to the specified packet store and timestamps it.
*/
void addTelemetryToPacketStore(const String<ECSSPacketStoreIdSize>& packetStoreId, uint32_t timestamp);
/**
* Deletes the content from all the packet stores.
*/
void resetPacketStores();
/**
* Returns the number of existing packet stores.
*/
uint16_t currentNumberOfPacketStores();
/**
* Returns the packet store with the specified packet store ID.
*/
PacketStore& getPacketStore(const String<ECSSPacketStoreIdSize>& packetStoreId);
/**
* Returns true if the specified packet store is present in packet stores.
*/
bool packetStoreExists(const String<ECSSPacketStoreIdSize>& packetStoreId);
/**
* Given a request that contains a number N, followed by N packet store IDs, this method calls function on every
* packet store. Implemented to reduce duplication. If N = 0, then function is applied to all packet stores.
* Incorrect packet store IDs are ignored and generate an error.
* @param function the job to be done after the error checking.
*/
void executeOnPacketStores(Message& request, const std::function<void(PacketStore&)>& function);
/**
* TC[15,1] request to enable the packet stores' storage function
*/
void enableStorageFunction(Message& request);
/**
* TC[15,2] request to disable the packet stores' storage function
*/
void disableStorageFunction(Message& request);
/**
* TC[15,9] start the by-time-range retrieval of packet stores
*/
void startByTimeRangeRetrieval(Message& request);
/**
* TC[15,11] delete the packet store content up to the specified time
*/
void deletePacketStoreContent(Message& request);
/**
* This function takes a TC[15,12] 'report the packet store content summary' as argument and responds with a TM[15,
* 13] 'packet store content summary report' report message.
*/
void packetStoreContentSummaryReport(Message& request);
/**
* TC[15,14] change the open retrieval start time tag
*/
void changeOpenRetrievalStartTimeTag(Message& request);
/**
* TC[15,15] resume the open retrieval of packet stores
*/
void resumeOpenRetrievalOfPacketStores(Message& request);
/**
* TC[15,16] suspend the open retrieval of packet stores
*/
void suspendOpenRetrievalOfPacketStores(Message& request);
/**
* TC[15,17] abort the by-time-range retrieval of packet stores
*/
void abortByTimeRangeRetrieval(Message& request);
/**
* This function takes a TC[15,18] 'report the status of packet stores' request as argument and responds with a
* TM[15,19] 'packet stores status' report message.
*/
void packetStoresStatusReport(Message& request);
/**
* TC[15,20] create packet stores
*/
void createPacketStores(Message& request);
/**
* TC[15,21] delete packet stores
*/
void deletePacketStores(Message& request);
/**
* This function takes a TC[15,22] 'report the packet store configuration' as argument and responds with a TM[15,
* 23] 'packet store configuration report' report message.
*/
void packetStoreConfigurationReport(Message& request);
/**
* TC[15,24] copy the packets contained into a packet store, selected by the time window
*/
void copyPacketsInTimeWindow(Message& request);
/**
* TC[15,25] resize packet stores
*/
void resizePacketStores(Message& request);
/**
* TC[15,26] change the packet store type to circular
*/
void changeTypeToCircular(Message& request);
/**
* TC[15,27] change the packet store type to bounded
*/
void changeTypeToBounded(Message& request);
/**
* TC[15,28] change the virtual channel used by a packet store
*/
void changeVirtualChannel(Message& request);
/**
* It is responsible to call the suitable function that executes a telecommand packet. The source of that packet
* is the ground station.
*
* @note This function is called from the main execute() that is defined in the file MessageParser.hpp
* @param request Contains the necessary parameters to call the suitable subservice
*/
void execute(Message& request);
};
#endif
| 35.745763 | 116 | 0.735973 | ACubeSAT |
9516beedad8ae9daf9b1fa96b97b46ecb5df3bf9 | 786 | cpp | C++ | Drivers/CardsDriver.cpp | mdsharif-me/warzone-reloaded | 660194d08422c3d5ffd8c23d00ceb8064b6153ad | [
"MIT"
] | 1 | 2022-02-08T19:08:39.000Z | 2022-02-08T19:08:39.000Z | Drivers/CardsDriver.cpp | mdsharif-me/warzone-reloaded | 660194d08422c3d5ffd8c23d00ceb8064b6153ad | [
"MIT"
] | null | null | null | Drivers/CardsDriver.cpp | mdsharif-me/warzone-reloaded | 660194d08422c3d5ffd8c23d00ceb8064b6153ad | [
"MIT"
] | null | null | null | //
// Created by tigerrrr on 2/13/2022.
//
#include <iostream>
#include "../Headers/Cards.h"
using namespace std;
int main() {
Card* card1 = new Card("Bomb");
Card* card2 = new Card("Airlift");
const char * CardTypes[5] = { "Blockade", "Bomb", "Reinforcement", "Diplomacy", "airlift"};
Deck* deck = new Deck();
deck->addToDeck(card1);
deck->addToDeck(card2);
deck->print();
//Adding 50 cards to complete the deck
for (int i = 0; i < 50; i++)
{
int r = rand() % 5;
Card *card = new Card(CardTypes[r]);
deck->addToDeck(card);
}
//Hand* hand = new Hand();
string name = "Deep";
Player* player = new Player(name);
deck->draw(player);
deck->draw(player);
deck->print();
//hand->print();
}
| 20.153846 | 97 | 0.561069 | mdsharif-me |
9516e154551241d8f72c1d23c5abb7cf3134b3f6 | 858 | cpp | C++ | tests/expected/rect.cpp | div72/py2many | 60277bc13597bd32d078b88a7390715568115fc6 | [
"MIT"
] | 345 | 2021-01-28T17:33:08.000Z | 2022-03-25T16:07:56.000Z | tests/expected/rect.cpp | mkos11/py2many | be6cfaad5af32c43eb24f182cb20ad63b979d4ef | [
"MIT"
] | 291 | 2021-01-31T13:15:06.000Z | 2022-03-23T21:28:49.000Z | tests/expected/rect.cpp | mkos11/py2many | be6cfaad5af32c43eb24f182cb20ad63b979d4ef | [
"MIT"
] | 23 | 2021-02-09T17:15:03.000Z | 2022-02-03T05:57:44.000Z | #include <cassert> // NOLINT(build/include_order)
#include <iostream> // NOLINT(build/include_order)
#include "pycpp/runtime/builtins.h" // NOLINT(build/include_order)
#include "pycpp/runtime/sys.h" // NOLINT(build/include_order)
/* This file implements a rectangle class */
class Rectangle {
public:
int height;
int length;
Rectangle(int height, int length) {
this->height = height;
this->length = length;
}
inline bool is_square() { return this->height == this->length; }
};
inline void show() {
Rectangle r = Rectangle(1, 1);
assert(r.is_square());
r = Rectangle(1, 2);
assert(!(r.is_square()));
std::cout << r.height;
std::cout << std::endl;
std::cout << r.length;
std::cout << std::endl;
}
int main(int argc, char** argv) {
pycpp::sys::argv = std::vector<std::string>(argv, argv + argc);
show();
}
| 24.514286 | 67 | 0.645688 | div72 |
95191f47b17aaae95099d0f6b262c22f923d8bbf | 1,025 | cpp | C++ | test/src/Game_Tests.cpp | gravity981/settlers | 0e2684f2358dbab8fdc70de4a9c94133a324a2b7 | [
"Unlicense"
] | null | null | null | test/src/Game_Tests.cpp | gravity981/settlers | 0e2684f2358dbab8fdc70de4a9c94133a324a2b7 | [
"Unlicense"
] | null | null | null | test/src/Game_Tests.cpp | gravity981/settlers | 0e2684f2358dbab8fdc70de4a9c94133a324a2b7 | [
"Unlicense"
] | null | null | null | #include <gtest/gtest.h>
#include <spdlog/spdlog.h>
#include "mock/MockGameObserver.h"
#include "mock/MockWorld.h"
#include "settlers/Game.h"
TEST(DISABLED_GameTests, startGameShouldChangeState)
{
MockWorld world;
EXPECT_CALL(world, generateFromFile).Times(1);
MockGameObserver observer;
EXPECT_CALL(observer, gameStateChanged).Times(1);
Game game{ world };
EXPECT_EQ(game.getGameState(), Game::GAMESTATE_IDLE);
game.registerGameObserver(&observer);
std::vector<Game::SPlayer> players = { { 1, Player::PLAYERCOLOR_RED },
{ 2, Player::PLAYERCOLOR_BLUE },
{ 3, Player::PLAYERCOLOR_ORANGE } };
ASSERT_TRUE(game.start(players, "some/path", "some/path", "some/path" , 0, 0));
}
int main(int argc, char **argv)
{
spdlog::set_level(spdlog::level::debug); // Set global log level to debug
spdlog::set_pattern("[%H:%M:%S.%e %z][%l][%s][%!()][line %#] %v");
::testing::InitGoogleTest(&argc, argv);
return RUN_ALL_TESTS();
} | 35.344828 | 81 | 0.647805 | gravity981 |
951c798b5eb4a51a53857ca6b839e586966a78a8 | 2,336 | cpp | C++ | code/modules/application/src/application/application.cpp | BrightComposite/RaptureStateToolkit | 6eb3c831540ba6a9d29e903dd3c537aac2e7f91f | [
"MIT"
] | null | null | null | code/modules/application/src/application/application.cpp | BrightComposite/RaptureStateToolkit | 6eb3c831540ba6a9d29e903dd3c537aac2e7f91f | [
"MIT"
] | null | null | null | code/modules/application/src/application/application.cpp | BrightComposite/RaptureStateToolkit | 6eb3c831540ba6a9d29e903dd3c537aac2e7f91f | [
"MIT"
] | null | null | null | //---------------------------------------------------------------------------
#include <application/application.h>
#include <iostream>
#if defined(_MSC_VER) && (defined(_DEBUG) || defined(DEBUG))
//#include <vld.h>
#endif
//---------------------------------------------------------------------------
namespace asd
{
wstring get_dir(const wstring & path);
#ifdef WIN32
int application::main(int argc, wchar_t * argv[]) {
auto & inst = instance();
if (inst.hInstance != nullptr) {
throw std::runtime_error("Application has been already loaded!");
}
inst.hInstance = (HINSTANCE)GetModuleHandle(nullptr);
for (int i = 0; i < argc; ++i)
inst.args.push_back(argv[i]);
STARTUPINFOW info;
GetStartupInfoW(&info);
inst._show_command = check_flag(STARTF_USESHOWWINDOW, info.dwFlags) ? info.wShowWindow : SW_NORMAL;
inst._root_path = get_dir(get_dir(application::getExecutionPath(inst.hInstance)));
return load();
}
HINSTANCE application::windows_instance() {
auto & inst = instance();
return inst.hInstance;
}
#else
int application::main(int argc, wchar_t ** argv) {
auto & inst = instance();
for (int i = 0; i < argc; ++i)
inst.args.push_back(wstring(argv[i]));
inst._root_path = get_dir(get_dir(argv[0]));
return load();
}
#endif
const wstring & application::root_path() {
auto & inst = instance();
return inst._root_path;
}
const array_list<wstring> & application::arguments() {
auto & inst = instance();
return inst.args;
}
int application::show_command() {
auto & inst = instance();
return inst._show_command;
}
int application::load() {
return instance().entrance();
}
#ifdef WIN32
wstring application::getExecutionPath(HINSTANCE hInstance) {
wchar_t buffer[MAX_PATH];
GetModuleFileNameW(hInstance, buffer, MAX_PATH);
return{ buffer, wcslen(buffer) };
}
#endif
void application::pause() {
std::cout << std::endl;
std::cout << "Press Enter to exit...";
getchar();
}
wstring get_dir(const wstring & path) {
return path.substr(0, path.find_last_of(L"/\\"));
}
}
| 25.67033 | 107 | 0.556507 | BrightComposite |
951ddc5c5610781a10b5889ec222a12158def757 | 3,929 | cpp | C++ | src/apps/processcontroller/KernelMemoryBarMenuItem.cpp | Yn0ga/haiku | 74e271b2a286c239e60f0ec261f4f197f4727eee | [
"MIT"
] | 1,338 | 2015-01-03T20:06:56.000Z | 2022-03-26T13:49:54.000Z | src/apps/processcontroller/KernelMemoryBarMenuItem.cpp | Yn0ga/haiku | 74e271b2a286c239e60f0ec261f4f197f4727eee | [
"MIT"
] | 15 | 2015-01-17T22:19:32.000Z | 2021-12-20T12:35:00.000Z | src/apps/processcontroller/KernelMemoryBarMenuItem.cpp | Yn0ga/haiku | 74e271b2a286c239e60f0ec261f4f197f4727eee | [
"MIT"
] | 350 | 2015-01-08T14:15:27.000Z | 2022-03-21T18:14:35.000Z | /*
* Copyright 2000, Georges-Edouard Berenger. All rights reserved.
* Distributed under the terms of the MIT License.
*/
#include "KernelMemoryBarMenuItem.h"
#include "Colors.h"
#include "MemoryBarMenu.h"
#include "ProcessController.h"
#include <stdio.h>
#include <Catalog.h>
#include <StringForSize.h>
#undef B_TRANSLATION_CONTEXT
#define B_TRANSLATION_CONTEXT "ProcessController"
KernelMemoryBarMenuItem::KernelMemoryBarMenuItem(system_info& systemInfo)
: BMenuItem(B_TRANSLATE("System resources & caches" B_UTF8_ELLIPSIS), NULL)
{
fLastSum = -1;
fGrenze1 = -1;
fGrenze2 = -1;
fPhysicalMemory = (int64)systemInfo.max_pages * B_PAGE_SIZE / 1024LL;
fCommittedMemory = (int64)systemInfo.used_pages * B_PAGE_SIZE / 1024LL;
fCachedMemory = (int64)systemInfo.cached_pages * B_PAGE_SIZE / 1024LL;
}
void
KernelMemoryBarMenuItem::DrawContent()
{
DrawBar(true);
Menu()->MovePenTo(ContentLocation());
BMenuItem::DrawContent();
}
void
KernelMemoryBarMenuItem::UpdateSituation(int64 committedMemory,
int64 cachedMemory)
{
fCommittedMemory = committedMemory;
fCachedMemory = cachedMemory;
DrawBar(false);
}
void
KernelMemoryBarMenuItem::DrawBar(bool force)
{
bool selected = IsSelected();
BRect frame = Frame();
BMenu* menu = Menu();
rgb_color highColor = menu->HighColor();
BFont font;
menu->GetFont(&font);
BRect cadre = bar_rect(frame, &font);
// draw the bar itself
if (fLastSum < 0)
force = true;
if (force) {
if (selected)
menu->SetHighColor(gFrameColorSelected);
else
menu->SetHighColor(gFrameColor);
menu->StrokeRect (cadre);
}
cadre.InsetBy(1, 1);
BRect r = cadre;
double grenze1 = cadre.left + (cadre.right - cadre.left)
* fCachedMemory / fPhysicalMemory;
double grenze2 = cadre.left + (cadre.right - cadre.left)
* fCommittedMemory / fPhysicalMemory;
if (grenze1 > cadre.right)
grenze1 = cadre.right;
if (grenze2 > cadre.right)
grenze2 = cadre.right;
r.right = grenze1;
if (!force)
r.left = fGrenze1;
if (r.left < r.right) {
if (selected)
menu->SetHighColor(gKernelColorSelected);
else
menu->SetHighColor(gKernelColor);
menu->FillRect (r);
}
r.left = grenze1;
r.right = grenze2;
if (!force) {
if (fGrenze2 > r.left && r.left >= fGrenze1)
r.left = fGrenze2;
if (fGrenze1 < r.right && r.right <= fGrenze2)
r.right = fGrenze1;
}
if (r.left < r.right) {
if (selected)
menu->SetHighColor(tint_color (kLavender, B_HIGHLIGHT_BACKGROUND_TINT));
else
menu->SetHighColor(kLavender);
menu->FillRect (r);
}
r.left = grenze2;
r.right = cadre.right;
if (!force)
r.right = fGrenze2;
if (r.left < r.right) {
if (selected)
menu->SetHighColor(gWhiteSelected);
else
menu->SetHighColor(kWhite);
menu->FillRect(r);
}
menu->SetHighColor(highColor);
fGrenze1 = grenze1;
fGrenze2 = grenze2;
// draw the value
double sum = fCachedMemory * FLT_MAX + fCommittedMemory;
if (force || sum != fLastSum) {
if (selected) {
menu->SetLowColor(gMenuBackColorSelected);
menu->SetHighColor(gMenuBackColorSelected);
} else {
menu->SetLowColor(gMenuBackColor);
menu->SetHighColor(gMenuBackColor);
}
BRect trect(cadre.left - kMargin - gMemoryTextWidth, frame.top,
cadre.left - kMargin, frame.bottom);
menu->FillRect(trect);
menu->SetHighColor(highColor);
char infos[128];
string_for_size(fCachedMemory * 1024.0, infos, sizeof(infos));
BPoint loc(cadre.left, cadre.bottom + 1);
loc.x -= kMargin + gMemoryTextWidth / 2 + menu->StringWidth(infos);
menu->DrawString(infos, loc);
string_for_size(fCommittedMemory * 1024.0, infos, sizeof(infos));
loc.x = cadre.left - kMargin - menu->StringWidth(infos);
menu->DrawString(infos, loc);
fLastSum = sum;
}
}
void
KernelMemoryBarMenuItem::GetContentSize(float* _width, float* _height)
{
BMenuItem::GetContentSize(_width, _height);
if (*_height < 16)
*_height = 16;
*_width += 20 + kBarWidth + kMargin + gMemoryTextWidth;
}
| 23.957317 | 76 | 0.709086 | Yn0ga |
95282ab90877db8fc56209b874837ed43ce97156 | 6,458 | cpp | C++ | util/summation_test.cpp | RedBeard0531/mongo_utils | 402c2023df7d67609ce9da8e405bf13cdd270e20 | [
"Apache-2.0"
] | 1 | 2018-03-14T21:48:43.000Z | 2018-03-14T21:48:43.000Z | util/summation_test.cpp | RedBeard0531/mongo_utils | 402c2023df7d67609ce9da8e405bf13cdd270e20 | [
"Apache-2.0"
] | null | null | null | util/summation_test.cpp | RedBeard0531/mongo_utils | 402c2023df7d67609ce9da8e405bf13cdd270e20 | [
"Apache-2.0"
] | null | null | null | /**
* Copyright (C) 2016 MongoDB 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 "mongo/platform/basic.h"
#include <cmath>
#include <limits>
#include <vector>
#include "mongo/unittest/unittest.h"
#include "mongo/util/summation.h"
namespace mongo {
namespace {
using limits = std::numeric_limits<long long>;
std::vector<long long> longValues = {
limits::min(),
limits::min() + 1,
limits::min() / 2,
-(1LL << 53),
-(1LL << 52),
-(1LL << 32),
-0x100,
-0xff,
-0xaa,
-0x55,
-1,
0,
1,
2,
0x55,
0x80,
0xaa,
0x100,
512,
1024,
2048,
1LL << 31,
1LL << 32,
1LL << 52,
1LL << 53,
limits::max() / 2,
#pragma warning(push)
// C4308: negative integral constant converted to unsigned type
#pragma warning(disable : 4308)
static_cast<long long>(1ULL << 63) - (1ULL << (63 - 53 - 1)), // Halfway between two doubles
#pragma warning(pop)
limits::max() - 1,
limits::max()};
std::vector<double> doubleValues = {
1.4831356930199802e-05, -3.121724665346865, 3041897608700.073, 1001318343149.7166,
-1714.6229586696593, 1731390114894580.8, 6.256645803154374e-08, -107144114533844.25,
-0.08839485091750919, -265119153.02185738, -0.02450615965231944, 0.0002684331017079073,
32079040427.68358, -0.04733295911845742, 0.061381859083076085, -25329.59126796951,
-0.0009567520620034965, -1553879364344.9932, -2.1101077525869814e-08, -298421079729.5547,
0.03182394834273594, 22.201944843278916, -33.35667991109125, 11496013.960449915,
-40652595.33210472, 3.8496066090328163, 2.5074042398147304e-08, -0.02208724071782122,
-134211.37290639878, 0.17640433666616578, 4.463787499171126, 9.959669945399718,
129265976.35224283, 1.5865526187526546e-07, -4746011.710555799, -712048598925.0789,
582214206210.4034, 0.025236204812875362, 530078170.91147506, -14.865307666195053,
1.6727994895185032e-05, -113386276.03121366, -6.135827207137054, 10644945799901.145,
-100848907797.1582, 2.2404406961625282e-08, 1.315662618424494e-09, -0.832190208349044,
-9.779323414999364, -546522170658.2997};
const double doubleValuesSum = 1636336982012512.5; // simple summation will yield wrong result
std::vector<double> specialValues = {-std::numeric_limits<double>::infinity(),
std::numeric_limits<double>::infinity(),
std::numeric_limits<double>::quiet_NaN()};
} // namespace
TEST(Summation, AddLongs) {
int iter = 0;
for (auto x : longValues) {
for (auto y : longValues) {
for (auto z : longValues) {
iter++;
DoubleDoubleSummation sum;
// This checks for correct results mod 2**64, which helps with checking correctness
// around the 2**53 transition between both doubles of the DoubleDouble result in
// int64 additions, as well off-by-one errors.
uint64_t checkUint64 =
static_cast<uint64_t>(x) + static_cast<uint64_t>(y) + static_cast<uint64_t>(z);
sum.addLong(x);
sum.addLong(y);
sum.addLong(z);
ASSERT(sum.isInteger());
if (!sum.fitsLong()) {
ASSERT(std::abs(sum.getDouble()) >= limits::max());
// Reduce sum to fit in a 64-bit integer.
while (!sum.fitsLong()) {
sum.addDouble(sum.getDouble() < 0 ? std::ldexp(1, 64) : -std::ldexp(1, 64));
}
}
ASSERT_EQUALS(static_cast<uint64_t>(sum.getLong()), checkUint64);
}
}
}
}
TEST(Summation, AddSpecial) {
for (auto x : specialValues) {
DoubleDoubleSummation sum;
// Check that a special number will result in that special number.
sum.addLong(-42);
sum.addLong(100);
sum.addDouble(x);
ASSERT(!sum.fitsLong());
ASSERT(!sum.isInteger());
if (std::isnan(x)) {
ASSERT(std::isnan(sum.getDouble()));
} else {
ASSERT_EQUALS(sum.getDouble(), x);
}
// Check that adding more numbers doesn't reset the special value.
sum.addDouble(-1E22);
sum.addLong(limits::min());
ASSERT(!sum.fitsLong());
if (std::isnan(x)) {
ASSERT(std::isnan(sum.getDouble()));
} else {
ASSERT_EQUALS(sum.getDouble(), x);
}
}
}
TEST(Summation, AddInvalid) {
DoubleDoubleSummation sum;
sum.addDouble(std::numeric_limits<double>::infinity());
sum.addDouble(-std::numeric_limits<double>::infinity());
ASSERT(std::isnan(sum.getDouble()));
ASSERT(!sum.fitsLong());
ASSERT(!sum.isInteger());
}
TEST(Summation, LongOverflow) {
DoubleDoubleSummation positive;
// Overflow should result in number no longer fitting in a long.
positive.addLong(limits::max());
positive.addLong(limits::max());
ASSERT(!positive.fitsLong());
// However, actual stored overflow should not overflow or lose precision.
positive.addLong(-limits::max());
ASSERT_EQUALS(positive.getLong(), limits::max());
DoubleDoubleSummation negative;
// Similarly for negative numbers.
negative.addLong(limits::min());
negative.addLong(-1);
ASSERT(!negative.fitsLong());
negative.addDouble(-1.0 * limits::min());
ASSERT_EQUALS(negative.getLong(), -1);
}
TEST(Summation, AddDoubles) {
DoubleDoubleSummation sum;
double straightSum = 0.0;
for (auto x : doubleValues) {
sum.addDouble(x);
straightSum += x;
}
ASSERT_EQUALS(sum.getDouble(), doubleValuesSum);
ASSERT(straightSum != sum.getDouble());
}
} // namespace mongo
| 33.117949 | 100 | 0.611025 | RedBeard0531 |
9528a92fec5fbccd7dd5027b2c2771880c85cfef | 37,860 | cpp | C++ | Plugins/MadaraLibrary/Source/ThirdParty/madara/transport/Transport.cpp | jredmondson/GamsPlugins | d133f86c263997a55f11b3b3d3344faeee60d726 | [
"BSD-2-Clause"
] | 3 | 2020-03-25T01:59:20.000Z | 2020-06-02T17:58:05.000Z | Plugins/MadaraLibrary/Source/ThirdParty/madara/transport/Transport.cpp | jredmondson/GamsPlugins | d133f86c263997a55f11b3b3d3344faeee60d726 | [
"BSD-2-Clause"
] | null | null | null | Plugins/MadaraLibrary/Source/ThirdParty/madara/transport/Transport.cpp | jredmondson/GamsPlugins | d133f86c263997a55f11b3b3d3344faeee60d726 | [
"BSD-2-Clause"
] | 1 | 2020-11-05T23:04:05.000Z | 2020-11-05T23:04:05.000Z | #include "Transport.h"
#include "madara/utility/Utility.h"
#include "madara/expression/Interpreter.h"
#include "madara/knowledge/ContextGuard.h"
#include <algorithm>
namespace madara
{
namespace transport
{
Base::Base(const std::string& id, TransportSettings& new_settings,
knowledge::ThreadSafeContext& context)
: is_valid_(false),
shutting_down_(false),
id_(id),
settings_(new_settings),
context_(context)
#ifndef _MADARA_NO_KARL_
,
on_data_received_(context.get_logger())
#endif // _MADARA_NO_KARL_
{
settings_.attach(&context_);
packet_scheduler_.attach(&settings_);
}
Base::~Base() {}
int Base::setup(void)
{
// check for an on_data_received ruleset
if(settings_.on_data_received_logic.length() != 0)
{
madara_logger_log(context_.get_logger(), logger::LOG_MAJOR,
"transport::Base::setup"
" setting rules to %s\n",
settings_.on_data_received_logic.c_str());
#ifndef _MADARA_NO_KARL_
expression::Interpreter interpreter;
on_data_received_ =
interpreter.interpret(context_, settings_.on_data_received_logic);
#endif // _MADARA_NO_KARL_
}
else
{
madara_logger_log(context_.get_logger(), logger::LOG_MAJOR,
"transport::Base::setup"
" no permanent rules were set\n");
}
// setup the send buffer
if(settings_.queue_length > 0)
buffer_ = new char[settings_.queue_length];
// if read domains has not been set, then set to write domain
if(settings_.num_read_domains() == 0)
{
madara_logger_log(context_.get_logger(), logger::LOG_MAJOR,
"transport::Base::setup"
" no read domains set. Adding write domain (%s)\n",
settings_.write_domain.c_str());
settings_.add_read_domain(settings_.write_domain);
}
else
{
madara_logger_log(context_.get_logger(), logger::LOG_MAJOR,
"transport::Base::setup"
" settings configured with %d read domains\n",
settings_.num_read_domains());
}
if(settings_.num_read_domains() > 0 &&
context_.get_logger().get_level() >= logger::LOG_MAJOR)
{
std::vector<std::string> domains;
settings_.get_read_domains(domains);
std::stringstream buffer;
for(unsigned int i = 0; i < domains.size(); ++i)
{
buffer << domains[i];
if(i != domains.size() - 1)
{
buffer << ", ";
}
}
madara_logger_log(context_.get_logger(), logger::LOG_MAJOR,
"transport::Base::setup"
" Write domain: %s. Read domains: %s\n",
settings_.write_domain.c_str(), buffer.str().c_str());
}
return validate_transport();
}
void Base::close(void)
{
invalidate_transport();
}
int process_received_update(const char* buffer, uint32_t bytes_read,
const std::string& id, knowledge::ThreadSafeContext& context,
const QoSTransportSettings& settings, BandwidthMonitor& send_monitor,
BandwidthMonitor& receive_monitor,
knowledge::KnowledgeMap& rebroadcast_records,
#ifndef _MADARA_NO_KARL_
knowledge::CompiledExpression& on_data_received,
#endif // _MADARA_NO_KARL_
const char* print_prefix, const char* remote_host, MessageHeader*& header)
{
// reset header to 0, so it is safe to delete
header = 0;
int max_buffer_size = (int)bytes_read;
// tell the receive bandwidth monitor about the transaction
receive_monitor.add(bytes_read);
madara_logger_log(context.get_logger(), logger::LOG_MAJOR,
"%s:"
" Receive bandwidth = %" PRIu64 " B/s\n",
print_prefix, receive_monitor.get_bytes_per_second());
bool is_reduced = false;
bool is_fragment = false;
madara_logger_log(context.get_logger(), logger::LOG_MAJOR,
"%s:"
" calling decode filters on %" PRIu32 " bytes\n",
print_prefix, bytes_read);
// call decodes, if applicable
bytes_read = (uint32_t)settings.filter_decode(
(char*)buffer, max_buffer_size, max_buffer_size);
madara_logger_log(context.get_logger(), logger::LOG_MAJOR,
"%s:"
" Decoding resulted in %" PRIu32 " final bytes\n",
print_prefix, bytes_read);
// setup buffer remaining, used by the knowledge record read method
int64_t buffer_remaining = (int64_t)bytes_read;
// clear the rebroadcast records
rebroadcast_records.clear();
// receive records will be what we pass to the aggregate filter
knowledge::KnowledgeMap updates;
// if a key appears multiple times, keep to add to buffer history
std::map<std::string, std::vector<knowledge::KnowledgeRecord>> past_updates;
// check the buffer for a reduced message header
if(bytes_read >= ReducedMessageHeader::static_encoded_size() &&
ReducedMessageHeader::reduced_message_header_test(buffer))
{
madara_logger_log(context.get_logger(), logger::LOG_MINOR,
"%s:"
" processing reduced KaRL message from %s\n",
print_prefix, remote_host);
header = new ReducedMessageHeader();
is_reduced = true;
}
else if(bytes_read >= MessageHeader::static_encoded_size() &&
MessageHeader::message_header_test(buffer))
{
madara_logger_log(context.get_logger(), logger::LOG_MINOR,
"%s:"
" processing KaRL message from %s\n",
print_prefix, remote_host);
header = new MessageHeader();
}
else if(bytes_read >= FragmentMessageHeader::static_encoded_size() &&
FragmentMessageHeader::fragment_message_header_test(buffer))
{
madara_logger_log(context.get_logger(), logger::LOG_MINOR,
"%s:"
" processing KaRL fragment message from %s\n",
print_prefix, remote_host);
header = new FragmentMessageHeader();
is_fragment = true;
}
else if(bytes_read >= 8 + MADARA_IDENTIFIER_LENGTH)
{
// get the text that appears as identifier.
char identifier[MADARA_IDENTIFIER_LENGTH];
strncpy(identifier, buffer + 8, MADARA_IDENTIFIER_LENGTH);
identifier[7] = 0;
madara_logger_log(context.get_logger(), logger::LOG_MINOR,
"%s:"
" dropping non-KaRL message with id %s from %s\n",
print_prefix, identifier, remote_host);
return -1;
}
else
{
madara_logger_log(context.get_logger(), logger::LOG_MINOR,
"%s:"
" dropping too short message from %s (length %i)\n",
print_prefix, remote_host, bytes_read);
return -1;
}
const char* update = header->read(buffer, buffer_remaining);
madara_logger_log(context.get_logger(), logger::LOG_MINOR,
"%s:"
" header info: %s\n",
print_prefix, header->to_string().c_str());
if(header->size < bytes_read)
{
madara_logger_log(context.get_logger(), logger::LOG_MAJOR,
"%s:"
" Message header.size (%" PRIu64 " bytes) is less than actual"
" bytes read (%" PRIu32 " bytes). Dropping message.\n",
print_prefix, header->size, bytes_read);
return -1;
}
if(is_fragment && exists(header->originator, header->clock,
((FragmentMessageHeader*)header)->update_number,
settings.fragment_map))
{
madara_logger_log(context.get_logger(), logger::LOG_MAJOR,
"%s:"
" Fragment already exists in fragment map. Dropping.\n",
print_prefix);
return -1;
}
if(!is_reduced)
{
// reject the message if it is us as the originator (no update necessary)
if(id == header->originator)
{
madara_logger_log(context.get_logger(), logger::LOG_MAJOR,
"%s:"
" dropping message from ourself\n",
print_prefix);
return -2;
}
else
{
madara_logger_log(context.get_logger(), logger::LOG_DETAILED,
"%s:"
" remote id (%s) is not our own\n",
print_prefix, remote_host);
}
if(settings.is_trusted(remote_host))
{
madara_logger_log(context.get_logger(), logger::LOG_DETAILED,
"%s: remote id (%s) is trusted\n", print_prefix, remote_host);
}
else
{
madara_logger_log(context.get_logger(), logger::LOG_MAJOR,
"%s:"
" dropping message from untrusted peer (%s\n",
print_prefix, remote_host);
// delete the header and continue to the svc loop
return -3;
}
std::string originator(header->originator);
if(settings.is_trusted(originator))
{
madara_logger_log(context.get_logger(), logger::LOG_MINOR,
"%s:"
" originator (%s) is trusted\n",
print_prefix, originator.c_str());
}
else
{
madara_logger_log(context.get_logger(), logger::LOG_MAJOR,
"%s:"
" dropping message from untrusted originator (%s)\n",
print_prefix, originator.c_str());
return -4;
}
// reject the message if it is from a different domain
if(!settings.is_reading_domain(header->domain))
{
madara_logger_log(context.get_logger(), logger::LOG_MAJOR,
"%s:"
" remote id (%s) has an untrusted domain (%s). Dropping message.\n",
print_prefix, remote_host, header->domain);
// delete the header and continue to the svc loop
return -5;
}
else
{
madara_logger_log(context.get_logger(), logger::LOG_MINOR,
"%s:"
" remote id (%s) message is in our domain\n",
print_prefix, remote_host);
}
}
// fragments are special cases
if(is_fragment)
{
// grab the fragment header
FragmentMessageHeader* frag_header =
dynamic_cast<FragmentMessageHeader*>(header);
// total size of the fragmented packet
uint64_t total_size = 0;
madara_logger_log(context.get_logger(), logger::LOG_MAJOR,
"%s:"
" Processing fragment %" PRIu32 " of %s:%" PRIu64 ".\n",
print_prefix, frag_header->update_number, frag_header->originator,
frag_header->clock);
// add the fragment and attempt to defrag the message
char* message = transport::add_fragment(frag_header->originator,
frag_header->clock, frag_header->update_number, buffer,
settings.fragment_queue_length, settings.fragment_map, total_size, true);
// if we have no return message, we may have previously defragged it
if(!message || total_size == 0)
{
return 0;
}
// copy the intermediate buffer to the user-allocated buffer
char* buffer_override = (char*)buffer;
memcpy(buffer_override, message, total_size);
// cleanup the old buffer. We should really have a zero-copy
delete[] message;
int decode_result = (uint32_t)settings.filter_decode(
(char*)buffer, total_size, settings.queue_length);
if (decode_result <= 0)
{
madara_logger_log(context.get_logger(), logger::LOG_MAJOR,
"%s:"
" ERROR: Unable to decode fragments. Likely incorrect filters.\n",
print_prefix);
return 0;
}
else
{
madara_logger_log(context.get_logger(), logger::LOG_MAJOR,
"%s:"
" Message has been pieced together from fragments. Processing...\n",
print_prefix);
/**
* if we defragged the message, then we need to process the message.
* In order to do that, we need to overwrite buffer with message
* so it can be processed normally.
**/
buffer_remaining = (int64_t)decode_result;
if(buffer_remaining <= settings.queue_length &&
buffer_remaining > (int64_t)MessageHeader::static_encoded_size ())
{
delete header;
// check the buffer for a reduced message header
if(ReducedMessageHeader::reduced_message_header_test(buffer))
{
madara_logger_log(context.get_logger(), logger::LOG_MINOR,
"%s:"
" processing reduced KaRL message from %s\n",
print_prefix, remote_host);
header = new ReducedMessageHeader();
is_reduced = true;
update = header->read(buffer, buffer_remaining);
}
else if(MessageHeader::message_header_test(buffer))
{
madara_logger_log(context.get_logger(), logger::LOG_MINOR,
"%s:"
" processing KaRL message from %s\n",
print_prefix, remote_host);
header = new MessageHeader();
update = header->read(buffer, buffer_remaining);
}
else
{
madara_logger_log(context.get_logger(), logger::LOG_MINOR,
"%s:"
" ERROR: defrag resulted in unknown message header.\n",
print_prefix);
return 0;
}
madara_logger_log(context.get_logger(),
logger::LOG_MAJOR, "%s:"
" past fragment header create.\n",
print_prefix);
} // end if buffer remaining
} // end if decode didn't break
} // end if is fragment
int actual_updates = 0;
uint64_t current_time = utility::get_time();
double deadline = settings.get_deadline();
madara_logger_log(context.get_logger(),
logger::LOG_MAJOR, "%s:"
" create transport_context with: "
"originator(%s), domain(%s), remote(%s), time(%" PRIu64 ").\n",
print_prefix, header->originator, header->domain, remote_host,
header->timestamp);
TransportContext transport_context(TransportContext::RECEIVING_OPERATION,
receive_monitor.get_bytes_per_second(),
send_monitor.get_bytes_per_second(), header->timestamp, current_time,
header->domain, header->originator, remote_host);
madara_logger_log(context.get_logger(),
logger::LOG_MAJOR, "%s:"
" past transport_context create.\n",
print_prefix);
uint64_t latency(0);
if(deadline >= 1.0)
{
if(header->timestamp < current_time)
{
latency = current_time - header->timestamp;
if(latency > deadline)
{
madara_logger_log(context.get_logger(), logger::LOG_MAJOR,
"%s:"
" deadline violation (latency is %" PRIu64 ", deadline is %f).\n",
print_prefix, latency, deadline);
return -6;
}
}
else
{
madara_logger_log(context.get_logger(), logger::LOG_MINOR,
"%s:"
" Cannot compute message latency."
" Message header timestamp is in the future."
" message.timestamp = %" PRIu64 ", cur_timestamp = %" PRIu64 ".\n",
print_prefix, header->timestamp, current_time);
}
}
madara_logger_log(context.get_logger(), logger::LOG_MINOR,
"%s:"
" iterating over the %" PRIu32 " updates\n",
print_prefix, header->updates);
// temporary record for reading from the updates buffer
knowledge::KnowledgeRecord record;
record.quality = header->quality;
record.clock = header->clock;
std::string key;
bool dropped = false;
if(send_monitor.is_bandwidth_violated(settings.get_send_bandwidth_limit()))
{
dropped = true;
madara_logger_log(context.get_logger(), logger::LOG_MAJOR,
"%s:"
" Send monitor has detected violation of bandwidth limit."
" Dropping packet from rebroadcast list\n",
print_prefix);
}
else if(receive_monitor.is_bandwidth_violated(
settings.get_total_bandwidth_limit()))
{
dropped = true;
madara_logger_log(context.get_logger(), logger::LOG_MAJOR,
"%s:"
" Receive monitor has detected violation of bandwidth limit."
" Dropping packet from rebroadcast list...\n",
print_prefix);
}
else if(settings.get_participant_ttl() < header->ttl)
{
dropped = true;
madara_logger_log(context.get_logger(), logger::LOG_MAJOR,
"%s:"
" Transport participant TTL is lower than header ttl."
" Dropping packet from rebroadcast list...\n",
print_prefix);
}
madara_logger_log(context.get_logger(), logger::LOG_MAJOR,
"%s:"
" Applying %" PRIu32 " updates\n",
print_prefix, header->updates);
const auto add_record = [&](const std::string& key,
knowledge::KnowledgeRecord rec) {
auto& entry = updates[key];
if(entry.exists())
{
using std::swap;
swap(rec, entry);
past_updates[key].emplace_back(std::move(rec));
}
else
{
entry = std::move(rec);
}
};
// iterate over the updates
for(uint32_t i = 0; i < header->updates; ++i)
{
// read converts everything into host format from the update stream
update = record.read(update, key, buffer_remaining);
if(buffer_remaining < 0)
{
madara_logger_log(context.get_logger(), logger::LOG_EMERGENCY,
"%s:"
" unable to process message. Buffer remaining is negative."
" Server is likely being targeted by custom KaRL tools.\n",
print_prefix);
// we do not delete the header as this will be cleaned up later
break;
}
else
{
madara_logger_log(context.get_logger(), logger::LOG_MINOR,
"%s:"
" Applying receive filter to %s (clk %i, qual %i) = %s\n",
print_prefix, key.c_str(), record.clock, record.quality,
record.to_string().c_str());
record = settings.filter_receive(record, key, transport_context);
if(record.exists())
{
madara_logger_log(context.get_logger(), logger::LOG_MINOR,
"%s:"
" Filter results for %s were %s\n",
print_prefix, key.c_str(), record.to_string().c_str());
add_record(key, record);
}
else
{
madara_logger_log(context.get_logger(), logger::LOG_MINOR,
"%s:"
" Filter resulted in dropping %s\n",
print_prefix, key.c_str());
}
}
}
const knowledge::KnowledgeMap& additionals = transport_context.get_records();
if(additionals.size() > 0)
{
madara_logger_log(context.get_logger(), logger::LOG_MAJOR,
"%s:"
" %lld additional records being handled after receive.\n",
print_prefix, (long long)additionals.size());
for(knowledge::KnowledgeMap::const_iterator i = additionals.begin();
i != additionals.end(); ++i)
{
add_record(i->first, i->second);
}
transport_context.clear_records();
if(header->ttl < 2)
header->ttl = 2;
// modify originator to indicate we are the originator of modifications
strncpy(header->originator, id.c_str(), sizeof(header->originator) - 1);
}
// apply aggregate receive filters
if(settings.get_number_of_receive_aggregate_filters() > 0 &&
(updates.size() > 0 || header->type == transport::REGISTER))
{
madara_logger_log(context.get_logger(), logger::LOG_MAJOR,
"%s:"
" Applying aggregate receive filters.\n",
print_prefix);
settings.filter_receive(updates, transport_context);
}
else
{
madara_logger_log(context.get_logger(), logger::LOG_MINOR,
"%s:"
" No aggregate receive filters were applied...\n",
print_prefix);
}
madara_logger_log(context.get_logger(), logger::LOG_MINOR,
"%s:"
" Locking the context to apply updates.\n",
print_prefix);
{
knowledge::ContextGuard guard(context);
madara_logger_log(context.get_logger(), logger::LOG_MINOR,
"%s:"
" Applying updates to context.\n",
print_prefix);
uint64_t now = utility::get_time();
// apply updates from the update list
for(knowledge::KnowledgeMap::iterator i = updates.begin();
i != updates.end(); ++i)
{
const auto apply = [&](knowledge::KnowledgeRecord& record) {
int result = 0;
record.set_toi(now);
result = record.apply(
context, i->first, header->quality, header->clock, false);
++actual_updates;
if(result != 1)
{
madara_logger_log(context.get_logger(), logger::LOG_MAJOR,
"%s:"
" update %s=%s was rejected\n",
print_prefix, key.c_str(), record.to_string().c_str());
}
else
{
madara_logger_log(context.get_logger(), logger::LOG_MAJOR,
"%s:"
" update %s=%s was accepted\n",
print_prefix, key.c_str(), record.to_string().c_str());
}
};
auto iter = past_updates.find(i->first);
if(iter != past_updates.end())
{
for(auto& cur : iter->second)
{
if(cur.exists())
{
apply(cur);
}
}
}
apply(i->second);
}
}
context.set_changed();
if(!dropped)
{
transport_context.set_operation(TransportContext::REBROADCASTING_OPERATION);
madara_logger_log(context.get_logger(), logger::LOG_MINOR,
"%s:"
" Applying rebroadcast filters to receive results.\n",
print_prefix);
// create a list of rebroadcast records from the updates
for(knowledge::KnowledgeMap::iterator i = updates.begin();
i != updates.end(); ++i)
{
i->second =
settings.filter_rebroadcast(i->second, i->first, transport_context);
if(i->second.exists())
{
if(i->second.to_string() != "")
{
madara_logger_log(context.get_logger(), logger::LOG_MINOR,
"%s:"
" Filter results for key %s were %s\n",
print_prefix, i->first.c_str(), i->second.to_string().c_str());
}
rebroadcast_records[i->first] = i->second;
}
else
{
madara_logger_log(context.get_logger(), logger::LOG_MINOR,
"%s:"
" Filter resulted in dropping %s\n",
print_prefix, i->first.c_str());
}
}
const knowledge::KnowledgeMap& additionals =
transport_context.get_records();
for(knowledge::KnowledgeMap::const_iterator i = additionals.begin();
i != additionals.end(); ++i)
{
rebroadcast_records[i->first] = i->second;
}
madara_logger_log(context.get_logger(), logger::LOG_MAJOR,
"%s:"
" Applying aggregate rebroadcast filters to %d records.\n",
print_prefix, rebroadcast_records.size());
// apply aggregate filters to the rebroadcast records
if(settings.get_number_of_rebroadcast_aggregate_filters() > 0 &&
rebroadcast_records.size() > 0)
{
settings.filter_rebroadcast(rebroadcast_records, transport_context);
}
else
{
madara_logger_log(context.get_logger(), logger::LOG_MINOR,
"%s:"
" No aggregate rebroadcast filters were applied...\n",
print_prefix);
}
madara_logger_log(context.get_logger(), logger::LOG_MINOR,
"%s:"
" Returning to caller with %d rebroadcast records.\n",
print_prefix, rebroadcast_records.size());
}
else
{
madara_logger_log(context.get_logger(), logger::LOG_MINOR,
"%s:"
" Rebroadcast packet was dropped...\n",
print_prefix);
}
// before we send to others, we first execute rules
if(settings.on_data_received_logic.length() != 0)
{
#ifndef _MADARA_NO_KARL_
madara_logger_log(context.get_logger(), logger::LOG_MAJOR,
"%s:"
" evaluating rules in %s\n",
print_prefix, settings.on_data_received_logic.c_str());
context.evaluate(on_data_received);
#endif // _MADARA_NO_KARL_
}
else
{
madara_logger_log(context.get_logger(), logger::LOG_MINOR,
"%s:"
" no permanent rules were set\n",
print_prefix);
}
return actual_updates;
}
int prep_rebroadcast(knowledge::ThreadSafeContext& context, char* buffer,
int64_t& buffer_remaining, const QoSTransportSettings& settings,
const char* print_prefix, MessageHeader* header,
const knowledge::KnowledgeMap& records, PacketScheduler& packet_scheduler)
{
int result = 0;
if(header->ttl > 0 && records.size() > 0 && packet_scheduler.add())
{
// keep track of the message_size portion of buffer
uint64_t* message_size = (uint64_t*)buffer;
int max_buffer_size = (int)buffer_remaining;
// the number of updates will be the size of the records map
header->updates = uint32_t(records.size());
// set the update to the end of the header
char* update = header->write(buffer, buffer_remaining);
for(knowledge::KnowledgeMap::const_iterator i = records.begin();
i != records.end(); ++i)
{
update = i->second.write(update, i->first, buffer_remaining);
}
if(buffer_remaining > 0)
{
int size = (int)(settings.queue_length - buffer_remaining);
*message_size = utility::endian_swap((uint64_t)size);
madara_logger_log(context.get_logger(), logger::LOG_MINOR,
"%s:"
" %" PRIu64 " bytes prepped for rebroadcast packet\n",
print_prefix, size);
result = size;
madara_logger_log(context.get_logger(), logger::LOG_MAJOR,
"%s:"
" calling encode filters\n",
print_prefix);
settings.filter_encode(buffer, result, max_buffer_size);
}
else
{
madara_logger_log(context.get_logger(), logger::LOG_MAJOR,
"%s:"
" Not enough buffer for rebroadcasting packet\n",
print_prefix);
result = -2;
}
}
else
{
madara_logger_log(context.get_logger(), logger::LOG_MINOR,
"%s:"
" No rebroadcast necessary.\n",
print_prefix);
result = -1;
}
packet_scheduler.print_status(logger::LOG_DETAILED, print_prefix);
return result;
}
long Base::prep_send(const knowledge::KnowledgeMap& orig_updates,
const char* print_prefix)
{
// check to see if we are shutting down
long ret = this->check_transport();
if(-1 == ret)
{
madara_logger_log(context_.get_logger(), logger::LOG_MAJOR,
"%s: transport has been told to shutdown", print_prefix);
return ret;
}
else if(-2 == ret)
{
madara_logger_log(context_.get_logger(), logger::LOG_MAJOR,
"%s: transport is not valid", print_prefix);
return ret;
}
// get the maximum quality from the updates
uint32_t quality = knowledge::max_quality(orig_updates);
uint64_t latest_toi = 0;
bool reduced = false;
knowledge::KnowledgeMap filtered_updates;
madara_logger_log(context_.get_logger(), logger::LOG_MINOR,
"%s:"
" Applying filters to %zu updates before sending...\n",
print_prefix, orig_updates.size());
TransportContext transport_context(TransportContext::SENDING_OPERATION,
receive_monitor_.get_bytes_per_second(),
send_monitor_.get_bytes_per_second(), (uint64_t)utility::get_time(),
(uint64_t)utility::get_time(), settings_.write_domain, id_);
bool dropped = false;
if(send_monitor_.is_bandwidth_violated(settings_.get_send_bandwidth_limit()))
{
dropped = true;
madara_logger_log(context_.get_logger(), logger::LOG_MAJOR,
"%s:"
" Send monitor has detected violation of bandwidth limit."
" Dropping packet...\n",
print_prefix);
}
else if(receive_monitor_.is_bandwidth_violated(
settings_.get_total_bandwidth_limit()))
{
dropped = true;
madara_logger_log(context_.get_logger(), logger::LOG_MAJOR,
"%s:"
" Receive monitor has detected violation of bandwidth limit."
" Dropping packet...\n",
print_prefix);
}
if(!dropped && packet_scheduler_.add())
{
if(settings_.get_number_of_send_filtered_types() > 0)
{
/**
* filter the updates according to the filters specified by
* the user in QoSTransportSettings (if applicable)
**/
for(auto e : orig_updates)
{
madara_logger_log(context_.get_logger(), logger::LOG_MAJOR,
"%s:"
" Calling filter chain of %s.\n",
print_prefix, e.first.c_str());
const auto record = e.second;
if(record.toi() > latest_toi)
{
latest_toi = record.toi();
}
// filter the record according to the send filter chain
knowledge::KnowledgeRecord result =
settings_.filter_send(record, e.first, transport_context);
madara_logger_log(context_.get_logger(), logger::LOG_MAJOR,
"%s:"
" Filter returned for %s.\n",
print_prefix, e.first.c_str());
// allow updates of 0. Exists probably isn't right here.
if(result.exists() || !record.exists())
{
madara_logger_log(context_.get_logger(), logger::LOG_MINOR,
"%s:"
" Adding record to update list.\n",
print_prefix);
filtered_updates.emplace(std::make_pair(e.first, result));
}
else
{
madara_logger_log(context_.get_logger(), logger::LOG_MAJOR,
"%s:"
" Filter removed record from update list.\n",
print_prefix);
}
}
madara_logger_log(context_.get_logger(), logger::LOG_DETAILED,
"%s:"
" Through individual record filters. Proceeding to add update "
"list.\n",
print_prefix);
const knowledge::KnowledgeMap& additionals =
transport_context.get_records();
for(knowledge::KnowledgeMap::const_iterator i = additionals.begin();
i != additionals.end(); ++i)
{
madara_logger_log(context_.get_logger(), logger::LOG_MAJOR,
"%s:"
" Filter added a record %s to the update list.\n",
print_prefix, i->first.c_str());
filtered_updates.emplace(std::make_pair(i->first, i->second));
}
}
else
{
for(auto e : orig_updates)
{
const auto record = e.second;
if(record.toi() > latest_toi)
{
latest_toi = record.toi();
}
madara_logger_log(context_.get_logger(), logger::LOG_MINOR,
"%s:"
" Adding record %s to update list.\n",
print_prefix, e.first.c_str());
filtered_updates.emplace(std::make_pair(e.first, record));
// Youtube tutorial is currently throwing this. Need to check GAMS
// else
// {
// std::stringstream message;
// message << print_prefix;
// message << ": record " << e.first << " produced a null record ";
// message << "from get_record_unsafe ()\n";
// madara_logger_log(
// context_.get_logger(), logger::LOG_ERROR, message.str().c_str());
// throw exceptions::MemoryException(message.str());
// }
}
}
}
else
{
madara_logger_log(context_.get_logger(), logger::LOG_MAJOR,
"%s:"
" Packet scheduler has dropped packet...\n",
print_prefix);
return 0;
}
madara_logger_log(context_.get_logger(), logger::LOG_MINOR,
"%s:"
" Applying %d aggregate update send filters to %d updates...\n",
print_prefix, (int)settings_.get_number_of_send_aggregate_filters(),
(int)filtered_updates.size());
// apply the aggregate filters
if(settings_.get_number_of_send_aggregate_filters() > 0 &&
filtered_updates.size() > 0)
{
settings_.filter_send(filtered_updates, transport_context);
}
else
{
madara_logger_log(context_.get_logger(), logger::LOG_MINOR,
"%s:"
" No aggregate send filters were applied...\n",
print_prefix);
}
packet_scheduler_.print_status(logger::LOG_DETAILED, print_prefix);
madara_logger_log(context_.get_logger(), logger::LOG_MINOR,
"%s:"
" Finished applying filters before sending...\n",
print_prefix);
if(filtered_updates.size() == 0)
{
madara_logger_log(context_.get_logger(), logger::LOG_MINOR,
"%s:"
" Filters removed all data. Nothing to send.\n",
print_prefix);
return 0;
}
// allocate a buffer to send
char* buffer = buffer_.get_ptr();
int64_t buffer_remaining = settings_.queue_length;
if(buffer == 0)
{
madara_logger_log(context_.get_logger(), logger::LOG_EMERGENCY,
"%s:"
" Unable to allocate buffer of size %" PRIu32 ". Exiting thread.\n",
print_prefix, settings_.queue_length);
return -3;
}
// set the header to the beginning of the buffer
MessageHeader* header = 0;
if(settings_.send_reduced_message_header)
{
madara_logger_log(context_.get_logger(), logger::LOG_MINOR,
"%s:"
" Preparing message with reduced message header.\n",
print_prefix);
header = new ReducedMessageHeader();
reduced = true;
}
else
{
madara_logger_log(context_.get_logger(), logger::LOG_MINOR,
"%s:"
" Preparing message with normal message header.\n",
print_prefix);
header = new MessageHeader();
}
// get the clock
header->clock = context_.get_clock();
if(!reduced)
{
// copy the domain from settings
strncpy(header->domain, this->settings_.write_domain.c_str(),
sizeof(header->domain) - 1);
// get the quality of the key
header->quality = quality;
// copy the message originator (our id)
strncpy(header->originator, id_.c_str(), sizeof(header->originator) - 1);
// send data is generally an assign type. However, MessageHeader is
// flexible enough to support both, and this will simply our read thread
// handling
header->type = MULTIASSIGN;
}
// set the time-to-live
header->ttl = settings_.get_rebroadcast_ttl();
header->updates = uint32_t(filtered_updates.size());
// compute size of this header
header->size = header->encoded_size();
// keep track of the maximum buffer size for encoding
int max_buffer_size = (int)buffer_remaining;
// set the update to the end of the header
char* update = header->write(buffer, buffer_remaining);
uint64_t* message_size = (uint64_t*)buffer;
uint32_t* message_updates = (uint32_t*)(buffer + 116);
// Message header format
// [size|id|domain|originator|type|updates|quality|clock|list of updates]
/**
* size = buffer[0] (unsigned 64 bit)
* transport id = buffer[8] (8 byte)
* domain = buffer[16] (32 byte domain name)
* originator = buffer[48] (64 byte originator host:port)
* type = buffer[112] (unsigned 32 bit type of message--usually MULTIASSIGN)
* updates = buffer[116] (unsigned 32 bit number of updates)
* quality = buffer[120] (unsigned 32 bit quality of message)
* clock = buffer[124] (unsigned 64 bit clock for this message)
* ttl = buffer[132] (the new knowledge starts here)
* knowledge = buffer[133] (the new knowledge starts here)
**/
// zero out the memory
// memset(buffer, 0, MAX_PACKET_SIZE);
// Message update format
// [key|value]
int j = 0;
uint32_t actual_updates = 0;
for(knowledge::KnowledgeMap::const_iterator i = filtered_updates.begin();
i != filtered_updates.end(); ++i)
{
const auto& key = i->first;
const auto& rec = i->second;
const auto do_write = [&](const knowledge::KnowledgeRecord& rec) {
if(!rec.exists())
{
madara_logger_log(context_.get_logger(), logger::LOG_MINOR,
"%s:"
" update[%d] => value is empty\n",
print_prefix, j, key.c_str());
return;
}
update = rec.write(update, key, buffer_remaining);
if(buffer_remaining > 0)
{
madara_logger_log(context_.get_logger(), logger::LOG_MINOR,
"%s:"
" update[%d] => encoding %s of type %" PRId32 " and size %" PRIu32
" @%" PRIu64 "\n",
print_prefix, j, key.c_str(), rec.type(), rec.size(), rec.toi());
++actual_updates;
++j;
}
else
{
madara_logger_log(context_.get_logger(), logger::LOG_EMERGENCY,
"%s:"
" unable to encode update[%d] => %s of type %" PRId32
" and size %" PRIu32 "\n",
print_prefix, j, key.c_str(), rec.type(), rec.size());
}
};
if(!settings_.send_history || !rec.has_history())
{
do_write(rec);
}
else
{
auto buf = rec.share_circular_buffer();
auto end = buf->end();
auto cur = buf->begin();
if(last_toi_sent_ > 0)
{
cur = std::upper_bound(cur, end, last_toi_sent_,
[](uint64_t lhs, const knowledge::KnowledgeRecord& rhs) {
return lhs < rhs.toi();
});
}
for(; cur != end; ++cur)
{
do_write(*cur);
}
}
}
long size(0);
if(buffer_remaining > 0)
{
size = (long)(settings_.queue_length - buffer_remaining);
header->size = size;
*message_size = utility::endian_swap((uint64_t)size);
header->updates = actual_updates;
*message_updates = utility::endian_swap(actual_updates);
// before we send to others, we first execute rules
if(settings_.on_data_received_logic.length() != 0)
{
#ifndef _MADARA_NO_KARL_
madara_logger_log(context_.get_logger(), logger::LOG_MAJOR,
"%s:"
" evaluating rules in %s\n",
print_prefix, settings_.on_data_received_logic.c_str());
on_data_received_.evaluate();
madara_logger_log(context_.get_logger(), logger::LOG_MAJOR,
"%s:"
" rules have been successfully evaluated\n",
print_prefix);
#endif // _MADARA_NO_KARL_
}
else
{
madara_logger_log(context_.get_logger(), logger::LOG_MINOR,
"%s:"
" no permanent rules were set\n",
print_prefix);
}
}
madara_logger_log(context_.get_logger(), logger::LOG_MAJOR,
"%s:"
" calling encode filters\n",
print_prefix);
// buffer is ready encoding
size = (long)settings_.filter_encode(
buffer_.get_ptr(), (int)size, max_buffer_size);
madara_logger_log(context_.get_logger(), logger::LOG_MINOR,
"%s:"
" header info before encode: %s\n",
print_prefix, header->to_string().c_str());
delete header;
last_toi_sent_ = latest_toi;
return size;
}
}
}
| 29.371606 | 82 | 0.624459 | jredmondson |
952dc2242669efa197fd26b56f945f40a3137c0d | 2,850 | hpp | C++ | include/LIEF/ART/enums.hpp | ahawad/LIEF | 88931ea405d9824faa5749731427533e0c27173e | [
"Apache-2.0"
] | null | null | null | include/LIEF/ART/enums.hpp | ahawad/LIEF | 88931ea405d9824faa5749731427533e0c27173e | [
"Apache-2.0"
] | null | null | null | include/LIEF/ART/enums.hpp | ahawad/LIEF | 88931ea405d9824faa5749731427533e0c27173e | [
"Apache-2.0"
] | null | null | null | /* Copyright 2017 - 2022 R. Thomas
* Copyright 2017 - 2022 Quarkslab
*
* 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 LIEF_ART_ENUMS_H_
#define LIEF_ART_ENUMS_H_
namespace LIEF {
namespace ART {
enum STORAGE_MODES {
STORAGE_UNCOMPRESSED = 0,
STORAGE_LZ4 = 1,
STORAGE_LZ4HC = 2,
};
namespace ART_17 {
enum IMAGE_METHODS {
RESOLUTION_METHOD = 0,
IMT_CONFLICT_METHOD = 1,
IMT_UNIMPLEMENTED_METHOD = 2,
CALLEE_SAVE_METHOD = 3,
REFS_ONLY_SAVE_METHOD = 4,
REFS_AND_ARGS_SAVE_METHOD = 5,
};
enum IMAGE_SECTIONS {
SECTION_OBJECTS = 0,
SECTION_ART_FIELDS = 1,
SECTION_ART_METHODS = 2,
SECTION_INTERNED_STRINGS = 3,
SECTION_IMAGE_BITMAP = 4,
};
enum IMAGE_ROOTS {
DEX_CACHES = 0,
CLASS_ROOTS = 1,
};
} // Namespace ART_17
namespace ART_29 {
using ART_17::IMAGE_METHODS;
using ART_17::IMAGE_ROOTS;
enum IMAGE_SECTIONS {
SECTION_OBJECTS = 0,
SECTION_ART_FIELDS = 1,
SECTION_ART_METHODS = 2,
SECTION_RUNTIME_METHODS = 3, // New in ART 29
SECTION_IMT_CONFLICT_TABLES = 4, // New in ART 29
SECTION_DEX_CACHE_ARRAYS = 5, // New in ART 29
SECTION_INTERNED_STRINGS = 6,
SECTION_CLASS_TABLE = 7, // New in ART 29
SECTION_IMAGE_BITMAP = 8,
};
} // Namespace ART_29
namespace ART_30 {
using ART_29::IMAGE_METHODS;
using ART_29::IMAGE_ROOTS;
enum IMAGE_SECTIONS {
SECTION_OBJECTS = 0,
SECTION_ART_FIELDS = 1,
SECTION_ART_METHODS = 2,
SECTION_RUNTIME_METHODS = 3,
SECTION_IM_TABLES = 4, // New in ART 30
SECTION_IMT_CONFLICT_TABLES = 5,
SECTION_DEX_CACHE_ARRAYS = 6,
SECTION_INTERNED_STRINGS = 7,
SECTION_CLASS_TABLE = 8,
SECTION_IMAGE_BITMAP = 9,
};
} // Namespace ART_30
namespace ART_44 {
using ART_30::IMAGE_SECTIONS;
enum IMAGE_METHODS {
RESOLUTION_METHOD = 0,
IMT_CONFLICT_METHOD = 1,
IMT_UNIMPLEMENTED_METHOD = 2,
SAVE_ALL_CALLEE_SAVES_METHOD = 3, // New in ART 44
SAVE_REFS_ONLY_METHOD = 4, // New in ART 44
SAVE_REFS_AND_ARGS_METHOD = 5, // New in ART 44
SAVE_EVERYTHING_METHOD = 6, // New in ART 44
};
enum IMAGE_ROOTS {
DEX_CACHES = 0,
CLASS_ROOTS = 1,
CLASS_LOADER = 2, // New in ART 44
};
} // Namespace ART_44
namespace ART_46 {
using ART_30::IMAGE_METHODS;
using ART_30::IMAGE_ROOTS;
using ART_30::IMAGE_SECTIONS;
} // Namespace ART_46
} // namespace ART
} // namespace LIEF
#endif
| 22.619048 | 75 | 0.720702 | ahawad |
9530cad32c3d43378b6b6ea63c9c34fa820f333e | 4,087 | cpp | C++ | Algorithms/Data Structure/Segment Tree/Segment Tree (all-in-one version).cpp | purhan/mindsport | d14fe8917c64b475589f494d98b74e99c9e064e5 | [
"MIT"
] | null | null | null | Algorithms/Data Structure/Segment Tree/Segment Tree (all-in-one version).cpp | purhan/mindsport | d14fe8917c64b475589f494d98b74e99c9e064e5 | [
"MIT"
] | null | null | null | Algorithms/Data Structure/Segment Tree/Segment Tree (all-in-one version).cpp | purhan/mindsport | d14fe8917c64b475589f494d98b74e99c9e064e5 | [
"MIT"
] | 1 | 2021-07-19T08:39:38.000Z | 2021-07-19T08:39:38.000Z | // Segment Tree (all-in-one version)
// It supports range update, range adjust, range min query, range max query, range sum query with lazy propagation
// Reference: https://noiref.codecla.ws/ds/
#include <bits/stdc++.h>
using namespace std;
const int INF = 1 << 30;
const int MAX_N = 100000 + 5;
const int MAX_L = 20; // ~ Log N
const long long MOD = 1e9 + 7;
typedef long long ll;
typedef vector<int> vi;
typedef pair<int,int> ii;
typedef vector<ii> vii;
typedef vector<vi> vvi;
#define LSOne(S) (S & (-S))
#define isBitSet(S, i) ((S >> i) & 1)
int N, Q, arr[MAX_N];
struct node {
int s, e;
ll mn, mx, sum; // min, max, sum
bool lset;
ll add_val, set_val;
node *l, *r;
node (int _s, int _e, int A[] = NULL): s(_s), e(_e), mn(0), mx(0), sum(0), lset(0), add_val(0), set_val(0), l(NULL), r(NULL) {
if (A == NULL) return;
if (s == e) mn = mx = sum = A[s];
else {
l = new node(s, (s+e)>>1, A), r = new node((s+e+2)>>1, e, A);
combine();
}
}
void create_children() {
if (s == e) return;
if (l != NULL) return;
int m = (s+e)>>1;
l = new node(s, m);
r = new node(m+1, e);
}
void self_set(ll v) {
lset = 1;
mn = mx = set_val = v;
sum = v * (e-s+1);
add_val = 0;
}
void self_add(ll v) {
if (lset) { self_set(v + set_val); return; }
mn += v, mx += v, add_val += v;
sum += v*(e-s+1);
}
void lazy_propagate() {
if (s == e) return;
if (lset) {
l->self_set(set_val), r->self_set(set_val);
lset = set_val = 0;
}
if (add_val != 0) {
l->self_add(add_val), r->self_add(add_val);
add_val = 0;
}
}
void combine() {
if (l == NULL) return;
sum = l->sum + r->sum;
mn = min(l->mn, r->mn);
mx = max(l->mx, r->mx);
}
void add(int x, int y, ll v) {
if (s == x && e == y) { self_add(v); return; }
int m = (s+e)>>1;
create_children(); lazy_propagate();
if (x <= m) l->add(x, min(y, m), v);
if (y > m) r->add(max(x, m+1), y, v);
combine();
}
void set(int x, int y, ll v) {
if (s == x && e == y) { self_set(v); return; }
int m = (s+e)>>1;
create_children(); lazy_propagate();
if (x <= m) l->set(x, min(y, m), v);
if (y > m) r->set(max(x, m+1), y, v);
combine();
}
ll range_sum(int x, int y) {
if (s == x && e == y) return sum;
if (l == NULL || lset) return (sum / (e-s+1)) * (y-x+1);
int m = (s+e)>>1;
lazy_propagate();
if (y <= m) return l->range_sum(x, y);
if (x > m) return r->range_sum(x, y);
return l->range_sum(x, m) + r->range_sum(m+1, y);
}
ll range_min(int x, int y) {
if (s == x && e == y) return mn;
if (l == NULL || lset) return mn;
int m = (s+e)>>1;
lazy_propagate();
if (y <= m) return l->range_min(x, y);
if (x > m) return r->range_min(x, y);
return min(l->range_min(x, m), r->range_min(m+1, y));
}
ll range_max(int x, int y) {
if (s == x && e == y) return mx;
if (l == NULL || lset) return mx;
int m = (s+e)>>1;
lazy_propagate();
if (y <= m) return l->range_max(x, y);
if (x > m) return r->range_max(x, y);
return max(l->range_max(x, m), r->range_max(m+1, y));
}
~node() {
if (l != NULL) delete l;
if (r != NULL) delete r;
}
} *root;
int main() {
ios_base::sync_with_stdio(0);
cin.tie(0); cout.tie(0);
//freopen("input.txt", "r", stdin);
//freopen("output.txt", "w", stdout);
cin >> N >> Q;
for(int i = 0; i < N; i++) cin >> arr[i];
root = new node(0, N - 1, arr);
/*
root->add(0, 5000, 3);
root->add(3000, 9000, -2);
root->set(7000, 10000, 5);
root->range_max(0, 10000);
root->range_min(0, 10000);
root->range_sum(0, 10000);
*/
}
| 28.78169 | 130 | 0.465867 | purhan |
953140c982d145318fcd52bb87a782273f158fcf | 4,569 | cpp | C++ | X-Engine/src/Platforms/OperatingSystems/Windows10/Win10Window.cpp | JohnMichaelProductions/X-Engine | 218ffcf64bfe5d5aed51b483c6f6986831ceeec4 | [
"Apache-2.0"
] | 4 | 2020-02-17T07:08:26.000Z | 2020-08-07T21:35:12.000Z | X-Engine/src/Platforms/OperatingSystems/Windows10/Win10Window.cpp | JohnMichaelProductions/X-Engine | 218ffcf64bfe5d5aed51b483c6f6986831ceeec4 | [
"Apache-2.0"
] | 25 | 2020-03-08T05:35:25.000Z | 2020-07-08T01:59:52.000Z | X-Engine/src/Platforms/OperatingSystems/Windows10/Win10Window.cpp | JohnMichaelProductions/X-Engine | 218ffcf64bfe5d5aed51b483c6f6986831ceeec4 | [
"Apache-2.0"
] | 1 | 2020-10-15T12:39:29.000Z | 2020-10-15T12:39:29.000Z | // Source file for Win10Window class functions, configured for Windows 10, also derived from window class
#include "Xpch.h"
#include <wtypes.h>
#include "XEngine/Core/Input.h"
#include "XEngine/EventSystem/KeyEvent.h"
#include "XEngine/EventSystem/MouseEvent.h"
#include "XEngine/EventSystem/ApplicationEvent.h"
#include "XEngine/Renderer/RendererAPI/Renderer.h"
#include "Platforms/RenderingAPIs/OpenGL/OpenGlContext.h"
#include "Platforms/OperatingSystems/Windows10/Win10Window.h"
namespace XEngine
{
static uint8_t GLFWWindowCount = 0;
static void GLFWErrorCallback(int error, const char* description)
{ XCORE_ERROR("GLFW Error ({0}): {1}", error, description); };
Win10Window::Win10Window(const WindowProps& props)
{
XPROFILE_FUNCTION();
XCORE_INFO("Using Windows 10 Window Class");
Init(props);
}
Win10Window::~Win10Window()
{
XPROFILE_FUNCTION();
Shutdown();
}
void Win10Window::Init(const WindowProps& props)
{
XPROFILE_FUNCTION();
SetConsoleTitle(TEXT("X-Engine Console"));
m_WindowData.Title = props.Title;
m_WindowData.Width = props.Width;
m_WindowData.Height = props.Height;
if (GLFWWindowCount == 0)
{
int success = glfwInit();
XCORE_ASSERT(success, "Could not initialize GLFW");
glfwSetErrorCallback(GLFWErrorCallback);
XCORE_INFO("GLFW intialized");
}
{
XPROFILE_SCOPE("glfwCreateWindow");
#if defined(XDEBUG)
if (Renderer::GetAPI() == RendererAPI::API::OpenGL)
glfwWindowHint(GLFW_OPENGL_DEBUG_CONTEXT, GLFW_TRUE);
#endif
m_Window = glfwCreateWindow((int)props.Width, (int)props.Height, m_WindowData.Title.c_str(), nullptr, nullptr);
++GLFWWindowCount;
}
m_WindowContext = GraphicsContext::Create(m_Window);
m_WindowContext->Init();
glfwSetWindowUserPointer(m_Window, &m_WindowData);
SetVSync(false);
glfwSetWindowSizeCallback(m_Window, [](GLFWwindow* window, int width, int height)
{
WindowData& data = *(WindowData*)glfwGetWindowUserPointer(window);
data.Width = width;
data.Height = height;
WindowResizeEvent event(width, height);
data.EventCallback(event);
});
glfwSetWindowCloseCallback(m_Window, [](GLFWwindow* window)
{
WindowData& data = *(WindowData*)glfwGetWindowUserPointer(window);
WindowCloseEvent event;
data.EventCallback(event);
});
glfwSetKeyCallback(m_Window, [](GLFWwindow* window, int key, int scancode, int action, int mods)
{
WindowData& data = *(WindowData*)glfwGetWindowUserPointer(window);
switch (action)
{
case GLFW_PRESS:
{
KeyPressedEvent event(key, 0);
data.EventCallback(event);
break;
}
case GLFW_RELEASE:
{
KeyReleasedEvent event(key);
data.EventCallback(event);
break;
}
case GLFW_REPEAT:
{
KeyPressedEvent event(key, 1);
data.EventCallback(event);
break;
}
}
});
glfwSetCharCallback(m_Window, [](GLFWwindow* window, uint32_t keycode)
{
WindowData& data = *(WindowData*)glfwGetWindowUserPointer(window);
KeyTypedEvent event(keycode);
data.EventCallback(event);
});
glfwSetMouseButtonCallback(m_Window, [](GLFWwindow* window, int button, int action, int mods)
{
WindowData& data = *(WindowData*)glfwGetWindowUserPointer(window);
switch (action)
{
case GLFW_PRESS:
{
MouseButtonPressedEvent event(button);
data.EventCallback(event);
break;
}
case GLFW_RELEASE:
{
MouseButtonReleasedEvent event(button);
data.EventCallback(event);
break;
}
}
});
glfwSetScrollCallback(m_Window, [](GLFWwindow* window, double xOffset, double yOffset)
{
WindowData& data = *(WindowData*)glfwGetWindowUserPointer(window);
MouseScrolledEvent event((float)xOffset, (float)yOffset);
data.EventCallback(event);
});
glfwSetCursorPosCallback(m_Window, [](GLFWwindow* window, double xPos, double yPos)
{
WindowData& data = *(WindowData*)glfwGetWindowUserPointer(window);
MouseMovedEvent event((float)xPos, (float)yPos);
data.EventCallback(event);
});
}
void Win10Window::Shutdown()
{
XPROFILE_FUNCTION();
glfwDestroyWindow(m_Window);
--GLFWWindowCount;
if (GLFWWindowCount == 0)
{
XCORE_INFO("Terminating GLFW");
glfwTerminate();
}
}
void Win10Window::OnUpdate()
{
XPROFILE_FUNCTION();
glfwPollEvents();
m_WindowContext->SwapBuffers();
}
void Win10Window::SetVSync(bool enabled)
{
XPROFILE_FUNCTION();
if (enabled)
glfwSwapInterval(1);
else
glfwSwapInterval(0);
m_WindowData.VSync = enabled;
}
bool Win10Window::IsVSync() const
{ return m_WindowData.VSync; }
} | 28.735849 | 115 | 0.712629 | JohnMichaelProductions |
95422c9e7bdf98658f44e29ca7208534c93cb106 | 4,314 | cpp | C++ | src/qt/qtbase/src/sql/doc/snippets/code/src_sql_kernel_qsqldatabase.cpp | power-electro/phantomjs-Gohstdriver-DIY-openshift | a571d301a9658a4c1b524d07e15658b45f8a0579 | [
"BSD-3-Clause"
] | 1 | 2020-04-30T15:47:35.000Z | 2020-04-30T15:47:35.000Z | src/qt/qtbase/src/sql/doc/snippets/code/src_sql_kernel_qsqldatabase.cpp | power-electro/phantomjs-Gohstdriver-DIY-openshift | a571d301a9658a4c1b524d07e15658b45f8a0579 | [
"BSD-3-Clause"
] | null | null | null | src/qt/qtbase/src/sql/doc/snippets/code/src_sql_kernel_qsqldatabase.cpp | power-electro/phantomjs-Gohstdriver-DIY-openshift | a571d301a9658a4c1b524d07e15658b45f8a0579 | [
"BSD-3-Clause"
] | null | null | null | /****************************************************************************
**
** Copyright (C) 2015 The Qt Company Ltd.
** Contact: http://www.qt.io/licensing/
**
** This file is part of the documentation of the Qt Toolkit.
**
** $QT_BEGIN_LICENSE:BSD$
** You may use this file under the terms of the BSD license as follows:
**
** "Redistribution and use in source and binary forms, with or without
** modification, are permitted provided that the following conditions are
** met:
** * Redistributions of source code must retain the above copyright
** notice, this list of conditions and the following disclaimer.
** * Redistributions in binary form must reproduce the above copyright
** notice, this list of conditions and the following disclaimer in
** the documentation and/or other materials provided with the
** distribution.
** * Neither the name of The Qt Company Ltd nor the names of its
** contributors may be used to endorse or promote products derived
** from this software without specific prior written permission.
**
**
** THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
** "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
** LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
** A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
** OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
** SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
** LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
** DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
** THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
** (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
** OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE."
**
** $QT_END_LICENSE$
**
****************************************************************************/
//! [0]
// WRONG
QSqlDatabase db = QSqlDatabase::database("sales");
QSqlQuery query("SELECT NAME, DOB FROM EMPLOYEES", db);
QSqlDatabase::removeDatabase("sales"); // will output a warning
// "db" is now a dangling invalid database connection,
// "query" contains an invalid result set
//! [0]
//! [1]
{
QSqlDatabase db = QSqlDatabase::database("sales");
QSqlQuery query("SELECT NAME, DOB FROM EMPLOYEES", db);
}
// Both "db" and "query" are destroyed because they are out of scope
QSqlDatabase::removeDatabase("sales"); // correct
//! [1]
//! [2]
QSqlDatabase::registerSqlDriver("MYDRIVER",
new QSqlDriverCreator<MyDatabaseDriver>);
QSqlDatabase db = QSqlDatabase::addDatabase("MYDRIVER");
//! [2]
//! [3]
...
db = QSqlDatabase::addDatabase("QODBC");
db.setDatabaseName("DRIVER={Microsoft Access Driver (*.mdb)};FIL={MS Access};DBQ=myaccessfile.mdb");
if (db.open()) {
// success!
}
...
//! [3]
//! [4]
...
// MySQL connection
db.setConnectOptions("SSL_KEY=client-key.pem;SSL_CERT=client-cert.pem;SSL_CA=ca-cert.pem;CLIENT_IGNORE_SPACE=1"); // use an SSL connection to the server
if (!db.open()) {
db.setConnectOptions(); // clears the connect option string
...
}
...
// PostgreSQL connection
db.setConnectOptions("requiressl=1"); // enable PostgreSQL SSL connections
if (!db.open()) {
db.setConnectOptions(); // clear options
...
}
...
// ODBC connection
db.setConnectOptions("SQL_ATTR_ACCESS_MODE=SQL_MODE_READ_ONLY;SQL_ATTR_TRACE=SQL_OPT_TRACE_ON"); // set ODBC options
if (!db.open()) {
db.setConnectOptions(); // don't try to set this option
...
}
//! [4]
//! [5]
#include "qtdir/src/sql/drivers/psql/qsql_psql.cpp"
//! [5]
//! [6]
PGconn *con = PQconnectdb("host=server user=bart password=simpson dbname=springfield");
QPSQLDriver *drv = new QPSQLDriver(con);
QSqlDatabase db = QSqlDatabase::addDatabase(drv); // becomes the new default connection
QSqlQuery query;
query.exec("SELECT NAME, ID FROM STAFF");
...
//! [6]
//! [7]
unix:LIBS += -lpq
win32:LIBS += libpqdll.lib
//! [7]
//! [8]
QSqlDatabase db;
qDebug() << db.isValid(); // Returns false
db = QSqlDatabase::database("sales");
qDebug() << db.isValid(); // Returns \c true if "sales" connection exists
QSqlDatabase::removeDatabase("sales");
qDebug() << db.isValid(); // Returns false
//! [8]
| 31.720588 | 152 | 0.677793 | power-electro |
9542867f11b893d6483e1abe821d62884990acfd | 8,466 | hpp | C++ | tracing/api/sys/trace/Logger.hpp | dterletskiy/carpc | c98d84e5bce69fb30a0f34e7b6cd82b4c98ba9b5 | [
"MIT"
] | 6 | 2022-03-24T15:40:03.000Z | 2022-03-30T09:40:20.000Z | tracing/api/sys/trace/Logger.hpp | dterletskiy/carpc | c98d84e5bce69fb30a0f34e7b6cd82b4c98ba9b5 | [
"MIT"
] | 7 | 2022-03-24T18:53:52.000Z | 2022-03-30T10:15:50.000Z | tracing/api/sys/trace/Logger.hpp | dterletskiy/carpc | c98d84e5bce69fb30a0f34e7b6cd82b4c98ba9b5 | [
"MIT"
] | 1 | 2022-03-20T21:22:09.000Z | 2022-03-20T21:22:09.000Z | #pragma once
#include <string.h>
#include <map>
#include "api/sys/trace/Types.hpp"
namespace carpc::trace {
const std::size_t s_buffer_size = 2 * 1024;
const char* const s_build_msg_error = "----- build message error -----\n";
const std::size_t s_build_msg_error_len = strlen( s_build_msg_error );
class Logger
{
private:
Logger( );
Logger( const eLogStrategy&, const std::string& app_name, const std::size_t buffer_size = s_buffer_size );
static Logger* mp_instance;
public:
~Logger( );
static Logger& instance( );
static Logger& instance( const eLogStrategy&, const std::string& app_name, const std::size_t buffer_size = s_buffer_size );
static bool init( const eLogStrategy&, const std::string& app_name, const std::size_t buffer_size = s_buffer_size );
static bool deinit( );
template< typename... Args >
void message( const eLogLevel& log_level, const char* const format, Args... args )
{
char message_buffer[ m_buffer_size ];
std::size_t size = ::snprintf( message_buffer, m_buffer_size, format, args... );
char* p_buffer = const_cast< char* >( message_buffer );
if( 0 >= size )
{
size = s_build_msg_error_len;
p_buffer = const_cast< char* >( s_build_msg_error );
}
else if( size >= m_buffer_size )
{
size = m_buffer_size;
p_buffer[ size - 2 ] = '\n';
p_buffer[ size - 1 ] = '\0';
}
switch( m_log_strategy )
{
case eLogStrategy::CONSOLE:
case eLogStrategy::CONSOLE_EXT:
{
::write( STDOUT_FILENO, p_buffer, size );
break;
}
case eLogStrategy::DLT:
{
#ifdef USE_DLT
DLT_LOG( dlt_context( ), to_dlt( log_level ), DLT_SIZED_CSTRING( p_buffer, size ) );
#endif // USE_DLT
break;
}
case eLogStrategy::ANDROID_LOGCAT:
{
#if OS_TARGET == OS_ANDROID
__android_log_print( to_android( log_level ), "TAG", "%s", p_buffer );
#endif // OS_TARGET == OS_ANDROID
break;
}
default: break;
}
}
template< typename... Args >
void message_format(
const eLogLevel& log_level,
const char* const file, const char* const function, const int line,
const char* const format, Args... args
)
{
const std::size_t full_format_max_size = 1024;
switch( m_log_strategy )
{
case eLogStrategy::CONSOLE:
{
char full_format[ full_format_max_size ] = { 0 };
strcat( full_format, PREFIX_FORMAT_MICROSECONDS_PID_TID_CODE );
strcat( full_format, to_color( log_level ) );
strcat( full_format, format );
strcat( full_format, RESET );
strcat( full_format, "\n" );
message(
log_level, full_format,
time( eGranularity::microseconds ), getpid( ), pthread_self( ),
file, function, line,
args...
);
break;
}
case eLogStrategy::CONSOLE_EXT:
{
tm* time_tm;
std::size_t milliseconds = 0;
local_time_of_date( time_tm, milliseconds );
char full_format[ full_format_max_size ] = { 0 };
strcat( full_format, PREFIX_FORMAT_DATE_TIME_MILLISECONDS_PID_TID_CODE );
strcat( full_format, to_color( log_level ) );
strcat( full_format, format );
strcat( full_format, RESET );
strcat( full_format, "\n" );
message(
log_level, full_format,
time_tm->tm_year + 1900, time_tm->tm_mon + 1, time_tm->tm_mday,
time_tm->tm_hour, time_tm->tm_min, time_tm->tm_sec, milliseconds,
getpid( ), pthread_self( ),
file, function, line,
args...
);
break;
}
case eLogStrategy::DLT:
{
char full_format[ full_format_max_size ] = { 0 };
strcat( full_format, "[%s:%s:%d] -> " );
strcat( full_format, format );
strcat( full_format, "\n" );
message( log_level, full_format, file, function, line, args... );
break;
}
case eLogStrategy::ANDROID_LOGCAT:
{
char full_format[ full_format_max_size ] = { 0 };
strcat( full_format, "[%s:%s:%d] -> " );
strcat( full_format, format );
strcat( full_format, "\n" );
message( log_level, full_format, file, function, line, args... );
break;
}
default: break;
}
}
template< typename... Args >
static void verbose( const char* const format, Args&... args )
{
instance( ).message( eLogLevel::VERBOSE, format, args... );
}
template< typename... Args >
static void debug( const char* const format, Args&... args )
{
instance( ).message( eLogLevel::DEBUG, format, args... );
}
template< typename... Args >
static void info( const char* const format, Args&... args )
{
instance( ).message( eLogLevel::INFO, format, args... );
}
template< typename... Args >
static void warning( const char* const format, Args&... args )
{
instance( ).message( eLogLevel::WARNING, format, args... );
}
template< typename... Args >
static void error( const char* const format, Args&... args )
{
instance( ).message( eLogLevel::ERROR, format, args... );
}
template< typename... Args >
static void fatal( const char* const format, Args&... args )
{
instance( ).message( eLogLevel::FATAL, format, args... );
}
private:
std::string mp_application_name = nullptr;
std::size_t m_buffer_size = s_buffer_size;
public:
const eLogStrategy& log_strategy( ) const;
void log_strategy( const eLogStrategy& );
private:
#if OS_TARGET == OS_ANDROID
eLogStrategy m_log_strategy = eLogStrategy::ANDROID_LOGCAT;
#else
eLogStrategy m_log_strategy = eLogStrategy::CONSOLE;
#endif
private:
#ifdef USE_DLT
DltContext& dlt_context( );
std::map< pthread_t, DltContext > m_context_map;
#endif
};
inline
const eLogStrategy& Logger::log_strategy( ) const
{
return m_log_strategy;
}
inline
void Logger::log_strategy( const eLogStrategy& _log_strategy )
{
m_log_strategy = _log_strategy;
#ifndef USE_DLT
// Prevent DLT logging startegy in case of DLT is not used
if( eLogStrategy::DLT == m_log_strategy )
{
#if OS_TARGET == OS_ANDROID
m_log_strategy = eLogStrategy::ANDROID_LOGCAT;
#else
m_log_strategy = eLogStrategy::CONSOLE;
#endif
}
#endif
#if OS_TARGET != OS_ANDROID
if( eLogStrategy::ANDROID_LOGCAT == m_log_strategy )
m_log_strategy = eLogStrategy::CONSOLE;
#endif
}
} // namespace carpc::trace
#define CLASS_ABBR "MAIN"
#define TRACE_LOG( LOG_LEVEL, USER_FORMAT, ... ) \
do { \
::carpc::trace::Logger::instance( ).message_format( \
LOG_LEVEL, \
CLASS_ABBR, __FUNCTION__, __LINE__, \
"" USER_FORMAT, ##__VA_ARGS__ \
); \
} while( false )
#undef CLASS_ABBR
| 33.330709 | 132 | 0.502599 | dterletskiy |
95443c4de09f8a89e341dfa094d10714a6c3b863 | 9,767 | cpp | C++ | GameEngine/ResourceManager.cpp | BenMarshall98/Game-Engine-Uni | cb2e0a75953db0960e3d58a054eb9a6e213ae12a | [
"MIT"
] | null | null | null | GameEngine/ResourceManager.cpp | BenMarshall98/Game-Engine-Uni | cb2e0a75953db0960e3d58a054eb9a6e213ae12a | [
"MIT"
] | null | null | null | GameEngine/ResourceManager.cpp | BenMarshall98/Game-Engine-Uni | cb2e0a75953db0960e3d58a054eb9a6e213ae12a | [
"MIT"
] | null | null | null | #define NOMINMAX
#include "ResourceManager.h"
#include "ModelLoader.h"
#include "AudioManager.h"
#include <algorithm>
#include "RenderManager.h"
std::vector<std::string> ResourceManager::usedModels;
std::vector<std::string> ResourceManager::usedTextures;
std::vector<std::string> ResourceManager::usedShaders;
std::vector<std::string> ResourceManager::usedAudios;
std::map<std::string, iModel *> ResourceManager::modelList;
std::map<std::string, Texture *> ResourceManager::textureList;
std::map<std::string, Shader *> ResourceManager::shaderList;
std::map<std::string, Buffer *> ResourceManager::audioBufferList;
std::map<std::string, int> ResourceManager::modelUsage;
std::map<std::string, int> ResourceManager::audioBufferUsage;
std::map<std::string, int> ResourceManager::shaderUsage;
std::map<std::string, int> ResourceManager::textureUsage;
//Loads model into game engine
void ResourceManager::LoadModel(const std::string & modelName, const std::string & fileName)
{
if (find(usedModels.begin(), usedModels.end(), fileName) == usedModels.end())
{
usedModels.push_back(fileName);
}
else
{
//TODO: Log that the model file already exists as a resource
return;
}
if (modelList.find(modelName) != modelList.end())
{
//TODO: Log that the model already exists as a resource
return;
}
iModel * model = ModelLoader::LoadModel(fileName);
if (model == nullptr)
{
//TODO: Log that the model failed to load
return;
}
modelUsage.insert(std::pair<std::string, int>(modelName, 0));
modelList.insert(std::pair<std::string, iModel*>(modelName, model));
}
//Loads texture into game engine
void ResourceManager::LoadTexture(const std::string & textureName, const std::string & fileName)
{
if (find(usedTextures.begin(), usedTextures.end(), fileName) == usedTextures.end())
{
usedTextures.push_back(fileName);
}
else
{
//TODO: Log that the texture file already exists as a resource
return;
}
if (textureList.find(textureName) != textureList.end())
{
//TODO: Log that the texture already exists as a resource
return;
}
Texture * texture = RenderManager::Instance()->CreateTexture(fileName);
if (!texture)
{
//TODO: Log that the texture failed to load
return;
}
textureUsage.insert(std::pair<std::string, int>(textureName, 0));
textureList.insert(std::pair<std::string, Texture *>(textureName, texture));
}
//Loads shader into game engine
void ResourceManager::LoadShader(const std::string & shaderName, const std::string & vertexProgram, const std::string & fragmentProgram, const std::string & geometryProgram)
{
const std::string shaderConcat = vertexProgram + fragmentProgram + geometryProgram;
if(find(usedShaders.begin(), usedShaders.end(), shaderConcat) == usedShaders.end())
{
usedShaders.push_back(shaderConcat);
}
else
{
//TODO: Log that the shader programs already exists as a resource
return;
}
if (shaderList.find(shaderName) != shaderList.end())
{
//TODO: Log that the shader mapping name already exists
return;
}
Shader * shader = RenderManager::Instance()->CreateShader(vertexProgram, fragmentProgram, geometryProgram);
if (!shader)
{
//TODO: Log that the shader failed to compile
return;
}
shaderUsage.insert(std::pair<std::string, int>(shaderName, 0));
shaderList.insert(std::pair<std::string, Shader *>(shaderName, shader));
}
//Loads audio into game engine
void ResourceManager::LoadAudio(const std::string & audioName, const std::string & fileName)
{
if (find(usedAudios.begin(), usedAudios.end(), fileName) == usedAudios.end())
{
usedAudios.push_back(fileName);
}
else
{
//TODO: Log that the audio file already exists as a resource
return;
}
if (audioBufferList.find(audioName) != audioBufferList.end())
{
//TODO: Log that the audio already exists as a resource
return;
}
Buffer * buffer = AudioManager::Instance()->GenerateBuffer(fileName);
if (!buffer)
{
//TODO: Log that buffer failed to be created
}
audioBufferUsage.insert(std::pair<std::string, int>(audioName, 0));
audioBufferList.insert(std::pair<std::string, Buffer *>(audioName, buffer));
}
//Gets model by model identity
iModel * ResourceManager::GetModel(const std::string & model)
{
const std::map<std::string, iModel *>::iterator it = modelList.find(model);
const std::map<std::string, int>::iterator count = modelUsage.find(model);
if (it != modelList.end())
{
count->second++;
return it->second;
}
return nullptr;
}
//Gets shader by shader identity
Shader * ResourceManager::GetShader(const std::string & shader)
{
const std::map<std::string, Shader *>::iterator it = shaderList.find(shader);
const std::map<std::string, int>::iterator count = shaderUsage.find(shader);
if (it != shaderList.end())
{
count->second++;
return it->second;
}
return nullptr;
}
//Gets texture by texture identity
Texture * ResourceManager::GetTexture(const std::string & texture)
{
const std::map<std::string, Texture *>::iterator it = textureList.find(texture);
const std::map<std::string, int>::iterator count = textureUsage.find(texture);
if (it != textureList.end())
{
count->second++;
return it->second;
}
return nullptr;
}
//Gets audio by audio identity
Source * ResourceManager::GetAudio(const std::string & audio)
{
const std::map<std::string, Buffer *>::iterator it = audioBufferList.find(audio);
const std::map<std::string, int>::iterator count = audioBufferUsage.find(audio);
if (it != audioBufferList.end())
{
count->second++;
Source * const source = AudioManager::Instance()->GenerateSource(it->second);
return source;
}
return nullptr;
}
//Removes model
void ResourceManager::RemoveModel(const iModel * const model)
{
std::map<std::string, iModel *>::iterator it;
std::string modelName = "";
for (it = modelList.begin(); it != modelList.end(); it++)
{
if (it->second == model)
{
modelName = it->first;
break;
}
}
const std::map<std::string, int>::iterator count = modelUsage.find(modelName);
if (count != modelUsage.end())
{
count->second--;
}
}
//Removes Shader
void ResourceManager::RemoveShader(const Shader * const shader)
{
std::map<std::string, Shader *>::iterator it;
std::string shaderName = "";
for (it = shaderList.begin(); it != shaderList.end(); it++)
{
if (it->second == shader)
{
shaderName = it->first;
break;
}
}
const std::map<std::string, int>::iterator count = shaderUsage.find(shaderName);
if (count != shaderUsage.end())
{
count->second--;
}
}
//Removes texture
void ResourceManager::RemoveTexture(const Texture * const texture)
{
std::map<std::string, Texture *>::iterator it;
std::string textureName = "";
for (it = textureList.begin(); it != textureList.end(); it++)
{
if (it->second == texture)
{
textureName = it->first;
break;
}
}
const std::map<std::string, int>::iterator count = textureUsage.find(textureName);
if (count != textureUsage.end())
{
count->second--;
}
}
//Removes audio
void ResourceManager::RemoveAudio(const void * const audio)
{
std::map<std::string, Buffer *>::iterator it;
std::string audioName = "";
for (it = audioBufferList.begin(); it != audioBufferList.end(); it++)
{
if (it->second == audio)
{
audioName = it->first;
break;
}
}
const std::map<std::string, int>::iterator count = audioBufferUsage.find(audioName);
if (count != audioBufferUsage.end())
{
count->second--;
}
}
//Removes resources that are unused
void ResourceManager::ClearResources()
{
usedModels.clear();
usedShaders.clear();
usedTextures.clear();
usedAudios.clear();
{
std::map<std::string, iModel *>::iterator it;
for (it = modelList.begin(); it != modelList.end();)
{
const std::map<std::string, int>::iterator count = modelUsage.find(it->first);
if (count->second == 0)
{
delete it->second;
it->second = nullptr;
modelList.erase(it);
modelUsage.erase(count);
it = modelList.begin();
}
else
{
it++;
}
}
}
{
std::map<std::string, Texture *>::iterator it;
for (it = textureList.begin(); it != textureList.end();)
{
const std::map<std::string, int>::iterator count = textureUsage.find(it->first);
if (count->second == 0)
{
delete it->second;
it->second = nullptr;
textureList.erase(it);
textureUsage.erase(count);
it = textureList.begin();
}
else
{
it++;
}
}
}
{
std::map<std::string, Shader *>::iterator it;
for (it = shaderList.begin(); it != shaderList.end();)
{
const std::map<std::string, int>::iterator count = shaderUsage.find(it->first);
if (count->second == 0)
{
delete it->second;
it->second = nullptr;
shaderList.erase(it);
shaderUsage.erase(count);
it = shaderList.begin();
}
else
{
it++;
}
}
}
}
//Deletes all resources
void ResourceManager::FinalClearResources()
{
usedModels.clear();
usedShaders.clear();
usedTextures.clear();
usedAudios.clear();
{
std::map<std::string, iModel *>::iterator it;
for (it = modelList.begin(); it != modelList.end(); it++)
{
delete it->second;
it->second = nullptr;
}
modelList.clear();
}
{
std::map<std::string, Texture *>::iterator it;
for (it = textureList.begin(); it != textureList.end(); it++)
{
delete it->second;
it->second = nullptr;
}
textureList.clear();
}
{
std::map<std::string, Shader *>::iterator it;
for (it = shaderList.begin(); it != shaderList.end(); it++)
{
delete it->second;
it->second = nullptr;
}
shaderList.clear();
}
{
std::map<std::string, Buffer *>::iterator it;
for (it = audioBufferList.begin(); it != audioBufferList.end(); it++)
{
AudioManager::Instance()->DeleteBuffer(it->second);
it->second = nullptr;
}
audioBufferList.clear();
}
} | 22.661253 | 173 | 0.674516 | BenMarshall98 |
95446e064c181e163d487889a847d6b6795e482a | 10,654 | cpp | C++ | project1-tetris/project1-tetris/Source/ScreenDiffSelect.cpp | lSara-MM/project1-tetris | ab7bad2ee97a168eb547df1c1ad0419b265293e8 | [
"MIT"
] | null | null | null | project1-tetris/project1-tetris/Source/ScreenDiffSelect.cpp | lSara-MM/project1-tetris | ab7bad2ee97a168eb547df1c1ad0419b265293e8 | [
"MIT"
] | null | null | null | project1-tetris/project1-tetris/Source/ScreenDiffSelect.cpp | lSara-MM/project1-tetris | ab7bad2ee97a168eb547df1c1ad0419b265293e8 | [
"MIT"
] | null | null | null | #include "ScreenDiffSelect.h"
#include "Application.h"
#include "ModuleTextures.h"
#include "ModuleRender.h"
#include "ModuleAudio.h"
#include "ModuleInput.h"
#include "ModuleFadeToBlack.h"
#include "ModuleParticles.h"
#include <iostream>
using namespace std;
uint Time = 0;
uint delta_Time = 0;
uint last_TickTime = 0;
ScreenDiffSelect::ScreenDiffSelect(bool startEnabled) : Module(startEnabled)
{
}
ScreenDiffSelect::~ScreenDiffSelect()
{
}
// Load assets
bool ScreenDiffSelect::Start()
{
LOG("Loading background assets");
bool ret = true;
bg_texture = App->textures->Load("Assets/Diff_Select.png");
arrowleft_texture = App->textures->Load("Assets/arrow_left.png");
arrowright_texture = App->textures->Load("Assets/arrow_right.png");
App->render->camera.x = 0;
App->render->camera.y = 0;
p_pos.x = p_x;
p_pos.y = p_y;
p_pos2.x = p2_x;
p_pos2.y = p2_y;
yellow_rect_texture = App->textures->Load("Assets/Rect/yellow_rect.png");
orange_rect_texture = App->textures->Load("Assets/Rect/orange_rect.png");
white_rect_texture = App->textures->Load("Assets/Rect/white_rect.png");
pink_rect_texture = App->textures->Load("Assets/Rect/pink_rect.png");
red_rect_texture = App->textures->Load("Assets/Rect/red_rect.png");
fxAdd_Press_L_R = App->audio->LoadFx("Assets/Audio/FX/diff_selection_arrow.wav");
fxAdd_PressEnter = App->audio->LoadFx("Assets/Audio/FX/diff_selection_enter.wav");
return ret;
}
update_status ScreenDiffSelect::Update()
{
Time = SDL_GetTicks();
delta_Time += Time - last_TickTime;
last_TickTime = Time;
App->render->Blit(bg_texture, 0, 3, NULL);
//key commands
if (App->input->keys[SDL_SCANCODE_A] == KEY_STATE::KEY_DOWN) {
switch (Index)
{
case 0:
if (Index < 2)
{
Index++;
p_x -= 235;
p2_x -= 205;
App->audio->PlayFx(fxAdd_Press_L_R);
//Colour random
pos_x = 245;
pos_y = 130;
pos_x1 = 245;
pos_y1 = 244;
pos_x2 = 245;
pos_y2 = 365;
pos_x3 = 422;
pos_y3 = 365;
pos_x4 = 422;
pos_y4 = 365;
pos_x5 = 422;
pos_y5 = 130;
}
break;
case 1:
if (Index < 2)
{
Index++;
p_x -= 210;
p2_x -= 244;
App->audio->PlayFx(fxAdd_Press_L_R);
//Colour random
pos_x = 22;
pos_y = 130;
pos_x1 = 22;
pos_y1 = 244;
pos_x2 = 22;
pos_y2 = 365;
pos_x3 = 200;
pos_y3 = 365;
pos_x4 = 200;
pos_y4 = 365;
pos_x5 = 200;
pos_y5 = 130;
}
break;
}
}
if (App->input->keys[SDL_SCANCODE_D] == KEY_STATE::KEY_DOWN) {
switch (Index)
{
case 1:
if (Index > 0)
{
Index--;
p_x += 235;
p2_x += 205;
App->audio->PlayFx(fxAdd_Press_L_R);
//Colour random
pos_x = 470;
pos_y = 130;
pos_x1 = 470;
pos_y1 = 244;
pos_x2 = 470;
pos_y2 = 365;
pos_x3 = 648;
pos_y3 = 365;
pos_x4 = 648;
pos_y4 = 365;
pos_x5 = 648;
pos_y5 = 130;
}
case 2:
if (Index > 0)
{
Index--;
p_x += 210;
p2_x += 244;
App->audio->PlayFx(fxAdd_Press_L_R);
pos_x = 245;
pos_y = 130;
pos_x1 = 245;
pos_y1 = 244;
pos_x2 = 245;
pos_y2 = 365;
pos_x3 = 422;
pos_y3 = 365;
pos_x4 = 422;
pos_y4 = 365;
pos_x5 = 422;
pos_y5 = 130;
}
}
}
if (App->input->keys[SDL_SCANCODE_SPACE] == KEY_STATE::KEY_DOWN)
{
if (Index == Easy)
{
App->fade->FadeToBlack(this, (Module*)App->sLvl_1, 0);
App->audio->PlayFx(fxAdd_PressEnter);
}
}
ColourRandom();
return update_status::UPDATE_CONTINUE;
}
int ScreenDiffSelect::ColourRandom()
{
Time = SDL_GetTicks();
delta_Time += Time - last_TickTime;
last_TickTime = Time;
colour = rand() % 9;
if ((delta_Time >= 0) && (delta_Time <= 50))
{
LOG("Loading");
if (colour == 1)
{
App->render->Blit(green_rect_texture, pos_x, pos_y, NULL);
}
else if (colour == 2)
{
App->render->Blit(blue_rect_texture, pos_x, pos_y, NULL);
}
else if (colour == 3)
{
App->render->Blit(orange_rect_texture, pos_x, pos_y, NULL);
}
else if (colour == 4)
{
App->render->Blit(white_rect_texture, pos_x, pos_y, NULL);
}
else if (colour == 5)
{
App->render->Blit(yellow_rect_texture, pos_x, pos_y, NULL);
}
else if (colour == 6)
{
App->render->Blit(pink_rect_texture, pos_x, pos_y, NULL);
}
else if (colour == 7)
{
App->render->Blit(bluedark_rect_texture, pos_x, pos_y, NULL);
}
else if (colour == 8)
{
App->render->Blit(red_rect_texture, pos_x, pos_y, NULL);
}
}
colour = rand() % 9;
if ((delta_Time >= 50) && (delta_Time <= 100))
{
if (colour == 1)
{
App->render->Blit(green_rect_texture, pos_x1, pos_y1, NULL);
}
else if (colour == 2)
{
App->render->Blit(blue_rect_texture, pos_x1, pos_y1, NULL);
}
else if (colour == 3)
{
App->render->Blit(orange_rect_texture, pos_x1, pos_y1, NULL);
}
else if (colour == 4)
{
App->render->Blit(white_rect_texture, pos_x1, pos_y1, NULL);
}
else if (colour == 5)
{
App->render->Blit(yellow_rect_texture, pos_x1, pos_y1, NULL);
}
else if (colour == 6)
{
App->render->Blit(pink_rect_texture, pos_x1, pos_y1, NULL);
}
else if (colour == 7)
{
App->render->Blit(bluedark_rect_texture, pos_x1, pos_y1, NULL);
}
else if (colour == 8)
{
App->render->Blit(red_rect_texture, pos_x1, pos_y1, NULL);
}
}
colour = rand() % 9;
if ((delta_Time >= 100) && (delta_Time <= 150))
{
if (colour == 1)
{
App->render->Blit(green_rect_texture, pos_x2, pos_y2, NULL);
}
else if (colour == 2)
{
App->render->Blit(blue_rect_texture, pos_x2, pos_y2, NULL);
}
else if (colour == 3)
{
App->render->Blit(orange_rect_texture, pos_x2, pos_y2, NULL);
}
else if (colour == 4)
{
App->render->Blit(white_rect_texture, pos_x2, pos_y2, NULL);
}
else if (colour == 5)
{
App->render->Blit(yellow_rect_texture, pos_x2, pos_y2, NULL);
}
else if (colour == 6)
{
App->render->Blit(pink_rect_texture, pos_x2, pos_y2, NULL);
}
else if (colour == 7)
{
App->render->Blit(bluedark_rect_texture, pos_x2, pos_y2, NULL);
}
else if (colour == 8)
{
App->render->Blit(red_rect_texture, pos_x2, pos_y2, NULL);
}
}
colour = rand() % 9;
if ((delta_Time >= 150) && (delta_Time <= 200))
{
if (colour == 1)
{
App->render->Blit(green_rect_texture, pos_x3, pos_y3, NULL);
}
else if (colour == 2)
{
App->render->Blit(blue_rect_texture, pos_x3, pos_y3, NULL);
}
else if (colour == 3)
{
App->render->Blit(orange_rect_texture, pos_x3, pos_y3, NULL);
}
else if (colour == 4)
{
App->render->Blit(white_rect_texture, pos_x3, pos_y3, NULL);
}
else if (colour == 5)
{
App->render->Blit(yellow_rect_texture, pos_x3, pos_y3, NULL);
}
else if (colour == 6)
{
App->render->Blit(pink_rect_texture, pos_x3, pos_y3, NULL);
}
else if (colour == 7)
{
App->render->Blit(bluedark_rect_texture, pos_x3, pos_y3, NULL);
}
else if (colour == 8)
{
App->render->Blit(red_rect_texture, pos_x3, pos_y3, NULL);
}
}
colour = rand() % 9;
if ((delta_Time >= 200) && (delta_Time <= 250))
{
if (colour == 1)
{
App->render->Blit(green_rect_texture, pos_x4, pos_y4, NULL);
}
else if (colour == 2)
{
App->render->Blit(blue_rect_texture, pos_x4, pos_y4, NULL);
}
else if (colour == 3)
{
App->render->Blit(orange_rect_texture, pos_x4, pos_y4, NULL);
}
else if (colour == 4)
{
App->render->Blit(white_rect_texture, pos_x4, pos_y4, NULL);
}
else if (colour == 5)
{
App->render->Blit(yellow_rect_texture, pos_x4, pos_y4, NULL);
}
else if (colour == 6)
{
App->render->Blit(pink_rect_texture, pos_x4, pos_y4, NULL);
}
else if (colour == 7)
{
App->render->Blit(bluedark_rect_texture, pos_x4, pos_y4, NULL);
}
else if (colour == 8)
{
App->render->Blit(red_rect_texture, pos_x4, pos_y4, NULL);
}
}
colour = rand() % 9;
if ((delta_Time >= 250) && (delta_Time <= 300))
{
if (colour == 1)
{
App->render->Blit(green_rect_texture, pos_x5, pos_y5, NULL);
}
else if (colour == 2)
{
App->render->Blit(blue_rect_texture, pos_x5, pos_y5, NULL);
}
else if (colour == 3)
{
App->render->Blit(orange_rect_texture, pos_x5, pos_y5, NULL);
}
else if (colour == 4)
{
App->render->Blit(white_rect_texture, pos_x5, pos_y5, NULL);
}
else if (colour == 5)
{
App->render->Blit(yellow_rect_texture, pos_x5, pos_y5, NULL);
}
else if (colour == 6)
{
App->render->Blit(bluedark_rect_texture, pos_x5, pos_y5, NULL);
}
else if (colour == 7)
{
App->render->Blit(pink_rect_texture, pos_x5, pos_y5, NULL);
}
else if (colour == 8)
{
App->render->Blit(red_rect_texture, pos_x5, pos_y5, NULL);
}
}
if ((delta_Time >= 350) && (delta_Time <= 400))
{
delta_Time = 400;
}
if ((delta_Time > 400))
{
delta_Time = 0;
}
return 0;
}
// Update: draw background
update_status ScreenDiffSelect::PostUpdate()
{
App->render->Blit(arrowleft_texture, p_x, p_y, NULL);
App->render->Blit(arrowright_texture, p2_x, p2_y, NULL);
App->render->TextDraw("DIFFICULTY SELECT", 185, 12, 255, 0, 0, 255, 20);
App->render->TextDraw("EASY", 82, 64, 255, 255, 255, 255, 15);
App->render->TextDraw("MEDIUM", 292, 64, 255, 255, 255, 255, 15);
App->render->TextDraw("HARD", 528, 64, 255, 255, 255, 255, 15);
App->render->TextDraw("HANDICAP", 274, 208, 250, 250, 255, 255, 15);
App->render->TextDraw("START", 306, 240, 255, 250, 250, 255, 15);
App->render->TextDraw("RANDOM", 512, 208, 255, 250, 250, 255, 15);
App->render->TextDraw("BLOCKS", 530, 240, 255, 250, 250, 255, 15);
App->render->TextDraw("ROUND 1", 50, 432, 255, 255, 255, 255, 15);
App->render->TextDraw("NO BONUS", 50, 448, 255, 255, 255, 255, 15);
App->render->TextDraw("ROUND 4", 272, 432, 255, 255, 255, 255, 15);
App->render->TextDraw("20000 BONUS", 242, 448, 255, 255, 255, 255, 15);
App->render->TextDraw("ROUND 7", 496, 432, 255, 255, 255, 255, 15);
App->render->TextDraw("40000 BONUS", 464, 448, 255, 255, 255, 255, 15);
return update_status::UPDATE_CONTINUE;
}
bool ScreenDiffSelect::CleanUp()
{
App->textures->Unload(bg_texture);
App->textures->Unload(arrowleft_texture);
App->textures->Unload(arrowright_texture);
App->textures->Unload(green_rect_texture);
App->textures->Unload(blue_rect_texture);
App->textures->Unload(bluedark_rect_texture);
App->textures->Unload(yellow_rect_texture);
App->textures->Unload(orange_rect_texture);
App->textures->Unload(white_rect_texture);
//audio?
return true;
}
| 16.416025 | 83 | 0.61667 | lSara-MM |
954623115fb0ddd595dc1d9579026aa66c136ca0 | 402 | cpp | C++ | Object Oriented Programming Concepts/CPP OOPS 2 - Classes, Data Members and Functions.cpp | sgpritam/cbcpp | 192b55d8d6930091d1ceb883f6dccf06735a391f | [
"MIT"
] | 2 | 2019-11-11T17:16:52.000Z | 2020-10-04T06:05:49.000Z | Object Oriented Programming Concepts/CPP OOPS 2 - Classes, Data Members and Functions.cpp | codedevmdu/cbcpp | 85c94d81d6e491f67e3cc1ea12534065b7cde16e | [
"MIT"
] | null | null | null | Object Oriented Programming Concepts/CPP OOPS 2 - Classes, Data Members and Functions.cpp | codedevmdu/cbcpp | 85c94d81d6e491f67e3cc1ea12534065b7cde16e | [
"MIT"
] | 4 | 2019-10-24T16:58:10.000Z | 2020-10-04T06:05:47.000Z | #include<iostream>
using namespace std;
class Car
{
public:
int price;
int model_no;
char name[20];
void start()
{
cout<<"Grr... starting the car "<<name<<endl;
}
};
int main()
{
Car C;
//Initialization
C.price=500;
C.model_no=1001;
C.name[0]='B';
C.name[1]='M';
C.name[2]='W';
C.name[3]='\0';
C.start();
}
| 14.888889 | 54 | 0.482587 | sgpritam |
954817ef00825813b9ec30d4471c2531bd2f4848 | 6,469 | cpp | C++ | env_brdf.cpp | hypernewbie/pbr_baker | 2664582786ef4facdac89d56d94f831175deac7f | [
"Unlicense"
] | 14 | 2019-10-15T08:42:19.000Z | 2021-01-05T01:56:27.000Z | env_brdf.cpp | vinjn/pbr_baker | 2664582786ef4facdac89d56d94f831175deac7f | [
"Unlicense"
] | null | null | null | env_brdf.cpp | vinjn/pbr_baker | 2664582786ef4facdac89d56d94f831175deac7f | [
"Unlicense"
] | 2 | 2020-12-31T13:42:28.000Z | 2022-02-23T06:09:29.000Z | /*
Copyright 2019 Xi Chen
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 "env_brdf.h"
using namespace glm;
#include <hammersley/hammersley.h>
#include <hammersley/hammersley.c>
#define ENVBRDF_SAMPLE_SIZE 1024
#define HAMMERSLEY_SEQUENCE_M 2
#define TEST_HAMMERSLEY false
static bool MULTISCATTER_ENVBRDF = false;
// Gloss parameterization similar to Call of Duty: Advanced Warfare
//
float ggx_GlossToAlpha2( float gloss )
{
return 2.0f / ( 1.0f + pow( 2.0f, 18.0f * gloss ) );
}
// src : https://cdn2.unrealengine.com/Resources/files/2013SiggraphPresentationsNotes-26915738.pdf
//
vec3 ggx_ImportanceSampleGGX( vec2 xi, float alpha2, vec3 N )
{
float phi = 2.0f * PI * xi.x;
float cosTheta = sqrt( ( 1 - xi.y ) / ( 1 + ( alpha2 - 1 ) * xi.y ) );
float sinTheta = sqrt( 1 - cosTheta * cosTheta );
vec3 H( sinTheta * cos( phi ), sinTheta * sin( phi ), cosTheta );
vec3 up = abs( N.z ) < 0.999f ? vec3( 0, 0, 1 ) : vec3( 1, 0, 0 );
vec3 tangentX = normalize( cross( up, N ) );
vec3 tangentY = cross( N, tangentX );
return tangentX * H.x + tangentY * H.y + N * H.z;
}
// src: https://people.sc.fsu.edu/~jburkardt/cpp_src/hammersley/hammersley.html
//
vec2 noise_getHammersleyAtIdx( int idx, int N )
{
static std::vector< vec2 > hmValues;
if ( hmValues.size() != N ) {
// Pre-calculate hammersley sequence.
hmValues.resize( N );
auto v = hammersley_sequence( 0, N, HAMMERSLEY_SEQUENCE_M, N );
assert( v );
for( int i = 0; i < N; i++ )
{
hmValues[i].x = v[i * 2 + 0];
hmValues[i].y = v[i * 2 + 1];
}
free( v );
}
return hmValues[ idx % N ];
}
// src: https://schuttejoe.github.io/post/ggximportancesamplingpart1/
//
float ggx_SmithGeom( float NdotL, float NdotV, float alpha2 )
{
float denomA = NdotV * sqrt( alpha2 + ( 1.0f - alpha2 ) * NdotL * NdotL );
float denomB = NdotL * sqrt( alpha2 + ( 1.0f - alpha2 ) * NdotV * NdotV );
return 2.0f * NdotL * NdotV / ( denomA + denomB );
}
// src : https://cdn2.unrealengine.com/Resources/files/2013SiggraphPresentationsNotes-26915738.pdf
//
vec2 ggx_IntegrateBRDF( float alpha, float NdotV )
{
vec3 V = vec3(
sqrt( 1.0f - NdotV * NdotV ), // sin
0.0f,
NdotV // cos
);
vec3 N = vec3( 0, 0, 1 );
float A = 0.0;
float B = 0.0;
float alpha2 = alpha * alpha;
for( uint i = 0; i < ENVBRDF_SAMPLE_SIZE; i++ )
{
auto xi = noise_getHammersleyAtIdx( i, ENVBRDF_SAMPLE_SIZE );
auto H = ggx_ImportanceSampleGGX( xi, alpha2, N );
vec3 L = 2.0f * dot( V, H ) * H - V;
float NdotL = saturate( L.z );
float NdotH = saturate( H.z );
float VdotH = saturate( dot( V, H ) );
if( NdotL > 0.0f ) {
float G = ggx_SmithGeom( NdotL, NdotV, alpha2 );
float Gvis = G * VdotH / ( NdotH * NdotV );
float Fc = pow( 1 - VdotH, 5.0f );
A += ( 1 - Fc ) * Gvis;
B += ( MULTISCATTER_ENVBRDF ? 1.0f : Fc ) * Gvis;
// printf( "x %f y %f i %d = { A %f B %f G %f Gvis %f Fc %f } { NdotH %f NdotV %f } \n", gloss, NdotV, i, A, B, G, Gvis, Fc, NdotH, NdotV );
}
}
// printf( "x %f y %f = { A %f B %f }\n", gloss, NdotV, A / ENVBRDF_SAMPLE_SIZE, B / ENVBRDF_SAMPLE_SIZE );
return vec2( A, B ) / float( ENVBRDF_SAMPLE_SIZE );
}
vec4 ggx_IntegrateBRDF_Function( float x, float y )
{
float NdotV = max( y, EPS );
float alpha = x;
auto v = ggx_IntegrateBRDF( alpha, NdotV );
return vec4( v.x, v.y, 0.0f, 1.0f );
}
vec4 ggx_EvalGitEnvBRDF( float gloss, float NdotV )
{
float x = NdotV, y = gloss;
float y2 = y * y;
float y3 = y2 * y;
float y4 = y2 * y2;
float y5 = y4 * y;
float p = 109.82183929f * y5 - 291.94656688f * y4 + 262.87670289f * y3 - 88.27433503f * y2 + 11.16956904f * y - 0.87481312f;
float q = -182.32941472f * y5 + 469.90565431f * y4 - 402.67303522f * y3 + 123.83971017f * y2 - 16.59005077f * y + 1.87103872f;
float r = 71.84851046f * y5 - 173.69958023f * y4 + 132.48656983f * y3 - 32.65209286f * y2 + 7.80449807f * y - 1.60302536f;
float z2 = p * x * x + q * x + r;
p = -17.85712754f * y5 + 59.72998797f * y4 - 63.78537961f * y3 + 21.95229787f * y2 - 2.50508609f * y - 0.08256607f;
q = 43.65809225f * y5 - 130.48400716f * y4 + 125.05400347f * y3 - 37.08717555f * y2 + 4.24345391f * y + 0.19560386f;
r = 32.31212079f * y5 + 86.12066514f * y4 - 71.28450854f * y3 + 15.53854696f * y2 - 1.90410394f * y - 0.15284118f;
float z1 = p * x * x + q * x + r;
return clamp( vec4( z1, z2, 0.0f, 1.0f ), vec4( 0 ), vec4( 1 ) );
}
void bake_envBRDF()
{
#if TEST_HAMMERSLEY
for( int i = 0; i < 64; i++ )
{
auto xi = noise_getHammersleyAtIdx( i, 64 );
printf("{ %.2f %.2f }\n", xi.x, xi.y );
}
#endif // #if TEST_HAMMERSLEY
MULTISCATTER_ENVBRDF = false;
baker_imageFunction2D( ggx_IntegrateBRDF_Function, 256, "output/env_brdf.png" );
MULTISCATTER_ENVBRDF = true;
baker_imageFunction2D( ggx_IntegrateBRDF_Function, 256, "output/env_brdf_multiscatter.png" );
baker_imageFunction2D( ggx_EvalGitEnvBRDF, 256, "output/env_brdf_fit.png" );
} | 37.830409 | 215 | 0.602566 | hypernewbie |
954e526da1a6c3d75dd2a3ef48d0c3b6a63fd761 | 2,526 | cpp | C++ | case-studies/PoDoFo/podofo/tools/podofouncompress/podofouncompress.cpp | satya-das/cib | 369333ea58b0530b8789a340e21096ba7d159d0e | [
"MIT"
] | 30 | 2018-03-05T17:35:29.000Z | 2022-03-17T18:59:34.000Z | podofo-0.9.6/tools/podofouncompress/podofouncompress.cpp | zia95/pdf-toolkit-console- | 369d73f66f7d4c74a252e83d200acbb792a6b8d5 | [
"MIT"
] | 2 | 2016-05-26T04:47:13.000Z | 2019-02-15T05:17:43.000Z | podofo-0.9.6/tools/podofouncompress/podofouncompress.cpp | zia95/pdf-toolkit-console- | 369d73f66f7d4c74a252e83d200acbb792a6b8d5 | [
"MIT"
] | 5 | 2019-02-15T05:09:22.000Z | 2021-04-14T12:10:16.000Z | /***************************************************************************
* Copyright (C) 2005 by Dominik Seichter *
* [email protected] *
* *
* This program is free software; you can redistribute it and/or modify *
* it under the terms of the GNU General Public License as published by *
* the Free Software Foundation; either version 2 of the License, or *
* (at your option) any later version. *
* *
* This program is distributed in the hope that it will be useful, *
* but WITHOUT ANY WARRANTY; without even the implied warranty of *
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *
* GNU General Public License for more details. *
* *
* You should have received a copy of the GNU General Public License *
* along with this program; if not, write to the *
* Free Software Foundation, Inc., *
* 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. *
***************************************************************************/
#include "Uncompress.h"
#include <podofo.h>
#include <stdlib.h>
#include <cstdio>
using namespace PoDoFo;
#ifdef _HAVE_CONFIG
#include <config.h>
#endif // _HAVE_CONFIG
void print_help()
{
printf("Usage: podofouncompress [inputfile] [outputfile]\n\n");
printf(" This tool removes all compression from the PDF file.\n");
printf(" It is useful for debugging errors in PDF files or analysing their structure.\n");
printf("\nPoDoFo Version: %s\n\n", PODOFO_VERSION_STRING);
}
int main( int argc, char* argv[] )
{
char* pszInput;
char* pszOutput;
UnCompress unc;
if( argc != 3 )
{
print_help();
exit( -1 );
}
pszInput = argv[1];
pszOutput = argv[2];
// try {
unc.Init( pszInput, pszOutput );
/*
} catch( PdfError & e ) {
fprintf( stderr, "Error: An error %i ocurred during uncompressing the pdf file.\n", e.GetError() );
e.PrintErrorMsg();
return e.GetError();
}
*/
printf("%s was successfully uncompressed to: %s\n", pszInput, pszOutput );
return 0;
}
| 33.68 | 105 | 0.495249 | satya-das |
9555dd25ddadf76ef9a4e41b8add0f407c7fc158 | 104,664 | hpp | C++ | hpx/preprocessed/apply_10.hpp | andreasbuhr/hpx | 4366a90aacbd3e95428a94ab24a1646a67459cc2 | [
"BSL-1.0"
] | null | null | null | hpx/preprocessed/apply_10.hpp | andreasbuhr/hpx | 4366a90aacbd3e95428a94ab24a1646a67459cc2 | [
"BSL-1.0"
] | null | null | null | hpx/preprocessed/apply_10.hpp | andreasbuhr/hpx | 4366a90aacbd3e95428a94ab24a1646a67459cc2 | [
"BSL-1.0"
] | null | null | null | // Copyright (c) 2007-2013 Hartmut Kaiser
// Copyright (c) 2012-2013 Thomas Heller
//
// 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)
// This file has been automatically generated using the Boost.Wave tool.
// Do not edit manually.
namespace hpx
{
template <typename F>
bool apply(threads::executor& sched, BOOST_FWD_REF(F) f)
{
sched.add(boost::forward<F>(f), "hpx::apply");
return false;
}
template <typename F>
bool apply(BOOST_FWD_REF(F) f)
{
threads::register_thread(boost::forward<F>(f), "hpx::apply");
return false;
}
template <typename F, typename A0> typename boost::lazy_enable_if< traits::detail::is_callable_not_action<F , BOOST_FWD_REF(A0)> , boost::mpl::identity<bool> >::type apply(threads::executor& sched, BOOST_FWD_REF(F) f, BOOST_FWD_REF(A0) a0) { sched.add(util::bind(util::protect(boost::forward<F>(f)), boost::forward<A0>( a0 )), "hpx::apply"); return false; } template <typename F, typename A0> typename boost::lazy_enable_if< traits::detail::is_callable_not_action<F , BOOST_FWD_REF(A0)> , boost::mpl::identity<bool> >::type apply(BOOST_FWD_REF(F) f, BOOST_FWD_REF(A0) a0) { threads::register_thread(util::bind( util::protect(boost::forward<F>(f)), boost::forward<A0>( a0 )), "hpx::apply"); return false; } template <typename F, typename A0 , typename A1> typename boost::lazy_enable_if< traits::detail::is_callable_not_action<F , BOOST_FWD_REF(A0) , BOOST_FWD_REF(A1)> , boost::mpl::identity<bool> >::type apply(threads::executor& sched, BOOST_FWD_REF(F) f, BOOST_FWD_REF(A0) a0 , BOOST_FWD_REF(A1) a1) { sched.add(util::bind(util::protect(boost::forward<F>(f)), boost::forward<A0>( a0 ) , boost::forward<A1>( a1 )), "hpx::apply"); return false; } template <typename F, typename A0 , typename A1> typename boost::lazy_enable_if< traits::detail::is_callable_not_action<F , BOOST_FWD_REF(A0) , BOOST_FWD_REF(A1)> , boost::mpl::identity<bool> >::type apply(BOOST_FWD_REF(F) f, BOOST_FWD_REF(A0) a0 , BOOST_FWD_REF(A1) a1) { threads::register_thread(util::bind( util::protect(boost::forward<F>(f)), boost::forward<A0>( a0 ) , boost::forward<A1>( a1 )), "hpx::apply"); return false; } template <typename F, typename A0 , typename A1 , typename A2> typename boost::lazy_enable_if< traits::detail::is_callable_not_action<F , BOOST_FWD_REF(A0) , BOOST_FWD_REF(A1) , BOOST_FWD_REF(A2)> , boost::mpl::identity<bool> >::type apply(threads::executor& sched, BOOST_FWD_REF(F) f, BOOST_FWD_REF(A0) a0 , BOOST_FWD_REF(A1) a1 , BOOST_FWD_REF(A2) a2) { sched.add(util::bind(util::protect(boost::forward<F>(f)), boost::forward<A0>( a0 ) , boost::forward<A1>( a1 ) , boost::forward<A2>( a2 )), "hpx::apply"); return false; } template <typename F, typename A0 , typename A1 , typename A2> typename boost::lazy_enable_if< traits::detail::is_callable_not_action<F , BOOST_FWD_REF(A0) , BOOST_FWD_REF(A1) , BOOST_FWD_REF(A2)> , boost::mpl::identity<bool> >::type apply(BOOST_FWD_REF(F) f, BOOST_FWD_REF(A0) a0 , BOOST_FWD_REF(A1) a1 , BOOST_FWD_REF(A2) a2) { threads::register_thread(util::bind( util::protect(boost::forward<F>(f)), boost::forward<A0>( a0 ) , boost::forward<A1>( a1 ) , boost::forward<A2>( a2 )), "hpx::apply"); return false; } template <typename F, typename A0 , typename A1 , typename A2 , typename A3> typename boost::lazy_enable_if< traits::detail::is_callable_not_action<F , BOOST_FWD_REF(A0) , BOOST_FWD_REF(A1) , BOOST_FWD_REF(A2) , BOOST_FWD_REF(A3)> , boost::mpl::identity<bool> >::type apply(threads::executor& sched, BOOST_FWD_REF(F) f, BOOST_FWD_REF(A0) a0 , BOOST_FWD_REF(A1) a1 , BOOST_FWD_REF(A2) a2 , BOOST_FWD_REF(A3) a3) { sched.add(util::bind(util::protect(boost::forward<F>(f)), boost::forward<A0>( a0 ) , boost::forward<A1>( a1 ) , boost::forward<A2>( a2 ) , boost::forward<A3>( a3 )), "hpx::apply"); return false; } template <typename F, typename A0 , typename A1 , typename A2 , typename A3> typename boost::lazy_enable_if< traits::detail::is_callable_not_action<F , BOOST_FWD_REF(A0) , BOOST_FWD_REF(A1) , BOOST_FWD_REF(A2) , BOOST_FWD_REF(A3)> , boost::mpl::identity<bool> >::type apply(BOOST_FWD_REF(F) f, BOOST_FWD_REF(A0) a0 , BOOST_FWD_REF(A1) a1 , BOOST_FWD_REF(A2) a2 , BOOST_FWD_REF(A3) a3) { threads::register_thread(util::bind( util::protect(boost::forward<F>(f)), boost::forward<A0>( a0 ) , boost::forward<A1>( a1 ) , boost::forward<A2>( a2 ) , boost::forward<A3>( a3 )), "hpx::apply"); return false; } template <typename F, typename A0 , typename A1 , typename A2 , typename A3 , typename A4> typename boost::lazy_enable_if< traits::detail::is_callable_not_action<F , BOOST_FWD_REF(A0) , BOOST_FWD_REF(A1) , BOOST_FWD_REF(A2) , BOOST_FWD_REF(A3) , BOOST_FWD_REF(A4)> , boost::mpl::identity<bool> >::type apply(threads::executor& sched, BOOST_FWD_REF(F) f, BOOST_FWD_REF(A0) a0 , BOOST_FWD_REF(A1) a1 , BOOST_FWD_REF(A2) a2 , BOOST_FWD_REF(A3) a3 , BOOST_FWD_REF(A4) a4) { sched.add(util::bind(util::protect(boost::forward<F>(f)), boost::forward<A0>( a0 ) , boost::forward<A1>( a1 ) , boost::forward<A2>( a2 ) , boost::forward<A3>( a3 ) , boost::forward<A4>( a4 )), "hpx::apply"); return false; } template <typename F, typename A0 , typename A1 , typename A2 , typename A3 , typename A4> typename boost::lazy_enable_if< traits::detail::is_callable_not_action<F , BOOST_FWD_REF(A0) , BOOST_FWD_REF(A1) , BOOST_FWD_REF(A2) , BOOST_FWD_REF(A3) , BOOST_FWD_REF(A4)> , boost::mpl::identity<bool> >::type apply(BOOST_FWD_REF(F) f, BOOST_FWD_REF(A0) a0 , BOOST_FWD_REF(A1) a1 , BOOST_FWD_REF(A2) a2 , BOOST_FWD_REF(A3) a3 , BOOST_FWD_REF(A4) a4) { threads::register_thread(util::bind( util::protect(boost::forward<F>(f)), boost::forward<A0>( a0 ) , boost::forward<A1>( a1 ) , boost::forward<A2>( a2 ) , boost::forward<A3>( a3 ) , boost::forward<A4>( a4 )), "hpx::apply"); return false; } template <typename F, typename A0 , typename A1 , typename A2 , typename A3 , typename A4 , typename A5> typename boost::lazy_enable_if< traits::detail::is_callable_not_action<F , BOOST_FWD_REF(A0) , BOOST_FWD_REF(A1) , BOOST_FWD_REF(A2) , BOOST_FWD_REF(A3) , BOOST_FWD_REF(A4) , BOOST_FWD_REF(A5)> , boost::mpl::identity<bool> >::type apply(threads::executor& sched, BOOST_FWD_REF(F) f, BOOST_FWD_REF(A0) a0 , BOOST_FWD_REF(A1) a1 , BOOST_FWD_REF(A2) a2 , BOOST_FWD_REF(A3) a3 , BOOST_FWD_REF(A4) a4 , BOOST_FWD_REF(A5) a5) { sched.add(util::bind(util::protect(boost::forward<F>(f)), boost::forward<A0>( a0 ) , boost::forward<A1>( a1 ) , boost::forward<A2>( a2 ) , boost::forward<A3>( a3 ) , boost::forward<A4>( a4 ) , boost::forward<A5>( a5 )), "hpx::apply"); return false; } template <typename F, typename A0 , typename A1 , typename A2 , typename A3 , typename A4 , typename A5> typename boost::lazy_enable_if< traits::detail::is_callable_not_action<F , BOOST_FWD_REF(A0) , BOOST_FWD_REF(A1) , BOOST_FWD_REF(A2) , BOOST_FWD_REF(A3) , BOOST_FWD_REF(A4) , BOOST_FWD_REF(A5)> , boost::mpl::identity<bool> >::type apply(BOOST_FWD_REF(F) f, BOOST_FWD_REF(A0) a0 , BOOST_FWD_REF(A1) a1 , BOOST_FWD_REF(A2) a2 , BOOST_FWD_REF(A3) a3 , BOOST_FWD_REF(A4) a4 , BOOST_FWD_REF(A5) a5) { threads::register_thread(util::bind( util::protect(boost::forward<F>(f)), boost::forward<A0>( a0 ) , boost::forward<A1>( a1 ) , boost::forward<A2>( a2 ) , boost::forward<A3>( a3 ) , boost::forward<A4>( a4 ) , boost::forward<A5>( a5 )), "hpx::apply"); return false; } template <typename F, typename A0 , typename A1 , typename A2 , typename A3 , typename A4 , typename A5 , typename A6> typename boost::lazy_enable_if< traits::detail::is_callable_not_action<F , BOOST_FWD_REF(A0) , BOOST_FWD_REF(A1) , BOOST_FWD_REF(A2) , BOOST_FWD_REF(A3) , BOOST_FWD_REF(A4) , BOOST_FWD_REF(A5) , BOOST_FWD_REF(A6)> , boost::mpl::identity<bool> >::type apply(threads::executor& sched, BOOST_FWD_REF(F) f, BOOST_FWD_REF(A0) a0 , BOOST_FWD_REF(A1) a1 , BOOST_FWD_REF(A2) a2 , BOOST_FWD_REF(A3) a3 , BOOST_FWD_REF(A4) a4 , BOOST_FWD_REF(A5) a5 , BOOST_FWD_REF(A6) a6) { sched.add(util::bind(util::protect(boost::forward<F>(f)), boost::forward<A0>( a0 ) , boost::forward<A1>( a1 ) , boost::forward<A2>( a2 ) , boost::forward<A3>( a3 ) , boost::forward<A4>( a4 ) , boost::forward<A5>( a5 ) , boost::forward<A6>( a6 )), "hpx::apply"); return false; } template <typename F, typename A0 , typename A1 , typename A2 , typename A3 , typename A4 , typename A5 , typename A6> typename boost::lazy_enable_if< traits::detail::is_callable_not_action<F , BOOST_FWD_REF(A0) , BOOST_FWD_REF(A1) , BOOST_FWD_REF(A2) , BOOST_FWD_REF(A3) , BOOST_FWD_REF(A4) , BOOST_FWD_REF(A5) , BOOST_FWD_REF(A6)> , boost::mpl::identity<bool> >::type apply(BOOST_FWD_REF(F) f, BOOST_FWD_REF(A0) a0 , BOOST_FWD_REF(A1) a1 , BOOST_FWD_REF(A2) a2 , BOOST_FWD_REF(A3) a3 , BOOST_FWD_REF(A4) a4 , BOOST_FWD_REF(A5) a5 , BOOST_FWD_REF(A6) a6) { threads::register_thread(util::bind( util::protect(boost::forward<F>(f)), boost::forward<A0>( a0 ) , boost::forward<A1>( a1 ) , boost::forward<A2>( a2 ) , boost::forward<A3>( a3 ) , boost::forward<A4>( a4 ) , boost::forward<A5>( a5 ) , boost::forward<A6>( a6 )), "hpx::apply"); return false; } template <typename F, typename A0 , typename A1 , typename A2 , typename A3 , typename A4 , typename A5 , typename A6 , typename A7> typename boost::lazy_enable_if< traits::detail::is_callable_not_action<F , BOOST_FWD_REF(A0) , BOOST_FWD_REF(A1) , BOOST_FWD_REF(A2) , BOOST_FWD_REF(A3) , BOOST_FWD_REF(A4) , BOOST_FWD_REF(A5) , BOOST_FWD_REF(A6) , BOOST_FWD_REF(A7)> , boost::mpl::identity<bool> >::type apply(threads::executor& sched, BOOST_FWD_REF(F) f, BOOST_FWD_REF(A0) a0 , BOOST_FWD_REF(A1) a1 , BOOST_FWD_REF(A2) a2 , BOOST_FWD_REF(A3) a3 , BOOST_FWD_REF(A4) a4 , BOOST_FWD_REF(A5) a5 , BOOST_FWD_REF(A6) a6 , BOOST_FWD_REF(A7) a7) { sched.add(util::bind(util::protect(boost::forward<F>(f)), boost::forward<A0>( a0 ) , boost::forward<A1>( a1 ) , boost::forward<A2>( a2 ) , boost::forward<A3>( a3 ) , boost::forward<A4>( a4 ) , boost::forward<A5>( a5 ) , boost::forward<A6>( a6 ) , boost::forward<A7>( a7 )), "hpx::apply"); return false; } template <typename F, typename A0 , typename A1 , typename A2 , typename A3 , typename A4 , typename A5 , typename A6 , typename A7> typename boost::lazy_enable_if< traits::detail::is_callable_not_action<F , BOOST_FWD_REF(A0) , BOOST_FWD_REF(A1) , BOOST_FWD_REF(A2) , BOOST_FWD_REF(A3) , BOOST_FWD_REF(A4) , BOOST_FWD_REF(A5) , BOOST_FWD_REF(A6) , BOOST_FWD_REF(A7)> , boost::mpl::identity<bool> >::type apply(BOOST_FWD_REF(F) f, BOOST_FWD_REF(A0) a0 , BOOST_FWD_REF(A1) a1 , BOOST_FWD_REF(A2) a2 , BOOST_FWD_REF(A3) a3 , BOOST_FWD_REF(A4) a4 , BOOST_FWD_REF(A5) a5 , BOOST_FWD_REF(A6) a6 , BOOST_FWD_REF(A7) a7) { threads::register_thread(util::bind( util::protect(boost::forward<F>(f)), boost::forward<A0>( a0 ) , boost::forward<A1>( a1 ) , boost::forward<A2>( a2 ) , boost::forward<A3>( a3 ) , boost::forward<A4>( a4 ) , boost::forward<A5>( a5 ) , boost::forward<A6>( a6 ) , boost::forward<A7>( a7 )), "hpx::apply"); return false; } template <typename F, typename A0 , typename A1 , typename A2 , typename A3 , typename A4 , typename A5 , typename A6 , typename A7 , typename A8> typename boost::lazy_enable_if< traits::detail::is_callable_not_action<F , BOOST_FWD_REF(A0) , BOOST_FWD_REF(A1) , BOOST_FWD_REF(A2) , BOOST_FWD_REF(A3) , BOOST_FWD_REF(A4) , BOOST_FWD_REF(A5) , BOOST_FWD_REF(A6) , BOOST_FWD_REF(A7) , BOOST_FWD_REF(A8)> , boost::mpl::identity<bool> >::type apply(threads::executor& sched, BOOST_FWD_REF(F) f, BOOST_FWD_REF(A0) a0 , BOOST_FWD_REF(A1) a1 , BOOST_FWD_REF(A2) a2 , BOOST_FWD_REF(A3) a3 , BOOST_FWD_REF(A4) a4 , BOOST_FWD_REF(A5) a5 , BOOST_FWD_REF(A6) a6 , BOOST_FWD_REF(A7) a7 , BOOST_FWD_REF(A8) a8) { sched.add(util::bind(util::protect(boost::forward<F>(f)), boost::forward<A0>( a0 ) , boost::forward<A1>( a1 ) , boost::forward<A2>( a2 ) , boost::forward<A3>( a3 ) , boost::forward<A4>( a4 ) , boost::forward<A5>( a5 ) , boost::forward<A6>( a6 ) , boost::forward<A7>( a7 ) , boost::forward<A8>( a8 )), "hpx::apply"); return false; } template <typename F, typename A0 , typename A1 , typename A2 , typename A3 , typename A4 , typename A5 , typename A6 , typename A7 , typename A8> typename boost::lazy_enable_if< traits::detail::is_callable_not_action<F , BOOST_FWD_REF(A0) , BOOST_FWD_REF(A1) , BOOST_FWD_REF(A2) , BOOST_FWD_REF(A3) , BOOST_FWD_REF(A4) , BOOST_FWD_REF(A5) , BOOST_FWD_REF(A6) , BOOST_FWD_REF(A7) , BOOST_FWD_REF(A8)> , boost::mpl::identity<bool> >::type apply(BOOST_FWD_REF(F) f, BOOST_FWD_REF(A0) a0 , BOOST_FWD_REF(A1) a1 , BOOST_FWD_REF(A2) a2 , BOOST_FWD_REF(A3) a3 , BOOST_FWD_REF(A4) a4 , BOOST_FWD_REF(A5) a5 , BOOST_FWD_REF(A6) a6 , BOOST_FWD_REF(A7) a7 , BOOST_FWD_REF(A8) a8) { threads::register_thread(util::bind( util::protect(boost::forward<F>(f)), boost::forward<A0>( a0 ) , boost::forward<A1>( a1 ) , boost::forward<A2>( a2 ) , boost::forward<A3>( a3 ) , boost::forward<A4>( a4 ) , boost::forward<A5>( a5 ) , boost::forward<A6>( a6 ) , boost::forward<A7>( a7 ) , boost::forward<A8>( a8 )), "hpx::apply"); return false; } template <typename F, typename A0 , typename A1 , typename A2 , typename A3 , typename A4 , typename A5 , typename A6 , typename A7 , typename A8 , typename A9> typename boost::lazy_enable_if< traits::detail::is_callable_not_action<F , BOOST_FWD_REF(A0) , BOOST_FWD_REF(A1) , BOOST_FWD_REF(A2) , BOOST_FWD_REF(A3) , BOOST_FWD_REF(A4) , BOOST_FWD_REF(A5) , BOOST_FWD_REF(A6) , BOOST_FWD_REF(A7) , BOOST_FWD_REF(A8) , BOOST_FWD_REF(A9)> , boost::mpl::identity<bool> >::type apply(threads::executor& sched, BOOST_FWD_REF(F) f, BOOST_FWD_REF(A0) a0 , BOOST_FWD_REF(A1) a1 , BOOST_FWD_REF(A2) a2 , BOOST_FWD_REF(A3) a3 , BOOST_FWD_REF(A4) a4 , BOOST_FWD_REF(A5) a5 , BOOST_FWD_REF(A6) a6 , BOOST_FWD_REF(A7) a7 , BOOST_FWD_REF(A8) a8 , BOOST_FWD_REF(A9) a9) { sched.add(util::bind(util::protect(boost::forward<F>(f)), boost::forward<A0>( a0 ) , boost::forward<A1>( a1 ) , boost::forward<A2>( a2 ) , boost::forward<A3>( a3 ) , boost::forward<A4>( a4 ) , boost::forward<A5>( a5 ) , boost::forward<A6>( a6 ) , boost::forward<A7>( a7 ) , boost::forward<A8>( a8 ) , boost::forward<A9>( a9 )), "hpx::apply"); return false; } template <typename F, typename A0 , typename A1 , typename A2 , typename A3 , typename A4 , typename A5 , typename A6 , typename A7 , typename A8 , typename A9> typename boost::lazy_enable_if< traits::detail::is_callable_not_action<F , BOOST_FWD_REF(A0) , BOOST_FWD_REF(A1) , BOOST_FWD_REF(A2) , BOOST_FWD_REF(A3) , BOOST_FWD_REF(A4) , BOOST_FWD_REF(A5) , BOOST_FWD_REF(A6) , BOOST_FWD_REF(A7) , BOOST_FWD_REF(A8) , BOOST_FWD_REF(A9)> , boost::mpl::identity<bool> >::type apply(BOOST_FWD_REF(F) f, BOOST_FWD_REF(A0) a0 , BOOST_FWD_REF(A1) a1 , BOOST_FWD_REF(A2) a2 , BOOST_FWD_REF(A3) a3 , BOOST_FWD_REF(A4) a4 , BOOST_FWD_REF(A5) a5 , BOOST_FWD_REF(A6) a6 , BOOST_FWD_REF(A7) a7 , BOOST_FWD_REF(A8) a8 , BOOST_FWD_REF(A9) a9) { threads::register_thread(util::bind( util::protect(boost::forward<F>(f)), boost::forward<A0>( a0 ) , boost::forward<A1>( a1 ) , boost::forward<A2>( a2 ) , boost::forward<A3>( a3 ) , boost::forward<A4>( a4 ) , boost::forward<A5>( a5 ) , boost::forward<A6>( a6 ) , boost::forward<A7>( a7 ) , boost::forward<A8>( a8 ) , boost::forward<A9>( a9 )), "hpx::apply"); return false; } template <typename F, typename A0 , typename A1 , typename A2 , typename A3 , typename A4 , typename A5 , typename A6 , typename A7 , typename A8 , typename A9 , typename A10> typename boost::lazy_enable_if< traits::detail::is_callable_not_action<F , BOOST_FWD_REF(A0) , BOOST_FWD_REF(A1) , BOOST_FWD_REF(A2) , BOOST_FWD_REF(A3) , BOOST_FWD_REF(A4) , BOOST_FWD_REF(A5) , BOOST_FWD_REF(A6) , BOOST_FWD_REF(A7) , BOOST_FWD_REF(A8) , BOOST_FWD_REF(A9) , BOOST_FWD_REF(A10)> , boost::mpl::identity<bool> >::type apply(threads::executor& sched, BOOST_FWD_REF(F) f, BOOST_FWD_REF(A0) a0 , BOOST_FWD_REF(A1) a1 , BOOST_FWD_REF(A2) a2 , BOOST_FWD_REF(A3) a3 , BOOST_FWD_REF(A4) a4 , BOOST_FWD_REF(A5) a5 , BOOST_FWD_REF(A6) a6 , BOOST_FWD_REF(A7) a7 , BOOST_FWD_REF(A8) a8 , BOOST_FWD_REF(A9) a9 , BOOST_FWD_REF(A10) a10) { sched.add(util::bind(util::protect(boost::forward<F>(f)), boost::forward<A0>( a0 ) , boost::forward<A1>( a1 ) , boost::forward<A2>( a2 ) , boost::forward<A3>( a3 ) , boost::forward<A4>( a4 ) , boost::forward<A5>( a5 ) , boost::forward<A6>( a6 ) , boost::forward<A7>( a7 ) , boost::forward<A8>( a8 ) , boost::forward<A9>( a9 ) , boost::forward<A10>( a10 )), "hpx::apply"); return false; } template <typename F, typename A0 , typename A1 , typename A2 , typename A3 , typename A4 , typename A5 , typename A6 , typename A7 , typename A8 , typename A9 , typename A10> typename boost::lazy_enable_if< traits::detail::is_callable_not_action<F , BOOST_FWD_REF(A0) , BOOST_FWD_REF(A1) , BOOST_FWD_REF(A2) , BOOST_FWD_REF(A3) , BOOST_FWD_REF(A4) , BOOST_FWD_REF(A5) , BOOST_FWD_REF(A6) , BOOST_FWD_REF(A7) , BOOST_FWD_REF(A8) , BOOST_FWD_REF(A9) , BOOST_FWD_REF(A10)> , boost::mpl::identity<bool> >::type apply(BOOST_FWD_REF(F) f, BOOST_FWD_REF(A0) a0 , BOOST_FWD_REF(A1) a1 , BOOST_FWD_REF(A2) a2 , BOOST_FWD_REF(A3) a3 , BOOST_FWD_REF(A4) a4 , BOOST_FWD_REF(A5) a5 , BOOST_FWD_REF(A6) a6 , BOOST_FWD_REF(A7) a7 , BOOST_FWD_REF(A8) a8 , BOOST_FWD_REF(A9) a9 , BOOST_FWD_REF(A10) a10) { threads::register_thread(util::bind( util::protect(boost::forward<F>(f)), boost::forward<A0>( a0 ) , boost::forward<A1>( a1 ) , boost::forward<A2>( a2 ) , boost::forward<A3>( a3 ) , boost::forward<A4>( a4 ) , boost::forward<A5>( a5 ) , boost::forward<A6>( a6 ) , boost::forward<A7>( a7 ) , boost::forward<A8>( a8 ) , boost::forward<A9>( a9 ) , boost::forward<A10>( a10 )), "hpx::apply"); return false; } template <typename F, typename A0 , typename A1 , typename A2 , typename A3 , typename A4 , typename A5 , typename A6 , typename A7 , typename A8 , typename A9 , typename A10 , typename A11> typename boost::lazy_enable_if< traits::detail::is_callable_not_action<F , BOOST_FWD_REF(A0) , BOOST_FWD_REF(A1) , BOOST_FWD_REF(A2) , BOOST_FWD_REF(A3) , BOOST_FWD_REF(A4) , BOOST_FWD_REF(A5) , BOOST_FWD_REF(A6) , BOOST_FWD_REF(A7) , BOOST_FWD_REF(A8) , BOOST_FWD_REF(A9) , BOOST_FWD_REF(A10) , BOOST_FWD_REF(A11)> , boost::mpl::identity<bool> >::type apply(threads::executor& sched, BOOST_FWD_REF(F) f, BOOST_FWD_REF(A0) a0 , BOOST_FWD_REF(A1) a1 , BOOST_FWD_REF(A2) a2 , BOOST_FWD_REF(A3) a3 , BOOST_FWD_REF(A4) a4 , BOOST_FWD_REF(A5) a5 , BOOST_FWD_REF(A6) a6 , BOOST_FWD_REF(A7) a7 , BOOST_FWD_REF(A8) a8 , BOOST_FWD_REF(A9) a9 , BOOST_FWD_REF(A10) a10 , BOOST_FWD_REF(A11) a11) { sched.add(util::bind(util::protect(boost::forward<F>(f)), boost::forward<A0>( a0 ) , boost::forward<A1>( a1 ) , boost::forward<A2>( a2 ) , boost::forward<A3>( a3 ) , boost::forward<A4>( a4 ) , boost::forward<A5>( a5 ) , boost::forward<A6>( a6 ) , boost::forward<A7>( a7 ) , boost::forward<A8>( a8 ) , boost::forward<A9>( a9 ) , boost::forward<A10>( a10 ) , boost::forward<A11>( a11 )), "hpx::apply"); return false; } template <typename F, typename A0 , typename A1 , typename A2 , typename A3 , typename A4 , typename A5 , typename A6 , typename A7 , typename A8 , typename A9 , typename A10 , typename A11> typename boost::lazy_enable_if< traits::detail::is_callable_not_action<F , BOOST_FWD_REF(A0) , BOOST_FWD_REF(A1) , BOOST_FWD_REF(A2) , BOOST_FWD_REF(A3) , BOOST_FWD_REF(A4) , BOOST_FWD_REF(A5) , BOOST_FWD_REF(A6) , BOOST_FWD_REF(A7) , BOOST_FWD_REF(A8) , BOOST_FWD_REF(A9) , BOOST_FWD_REF(A10) , BOOST_FWD_REF(A11)> , boost::mpl::identity<bool> >::type apply(BOOST_FWD_REF(F) f, BOOST_FWD_REF(A0) a0 , BOOST_FWD_REF(A1) a1 , BOOST_FWD_REF(A2) a2 , BOOST_FWD_REF(A3) a3 , BOOST_FWD_REF(A4) a4 , BOOST_FWD_REF(A5) a5 , BOOST_FWD_REF(A6) a6 , BOOST_FWD_REF(A7) a7 , BOOST_FWD_REF(A8) a8 , BOOST_FWD_REF(A9) a9 , BOOST_FWD_REF(A10) a10 , BOOST_FWD_REF(A11) a11) { threads::register_thread(util::bind( util::protect(boost::forward<F>(f)), boost::forward<A0>( a0 ) , boost::forward<A1>( a1 ) , boost::forward<A2>( a2 ) , boost::forward<A3>( a3 ) , boost::forward<A4>( a4 ) , boost::forward<A5>( a5 ) , boost::forward<A6>( a6 ) , boost::forward<A7>( a7 ) , boost::forward<A8>( a8 ) , boost::forward<A9>( a9 ) , boost::forward<A10>( a10 ) , boost::forward<A11>( a11 )), "hpx::apply"); return false; }
}
namespace hpx
{
template <
typename Action
, typename T0
>
bool apply(
BOOST_RV_REF(HPX_UTIL_STRIP((
hpx::util::detail::bound_action1<
Action
, T0
>))) bound)
{
return bound.apply();
}
template < typename Action , typename T0 , typename A0 > bool apply( BOOST_RV_REF(HPX_UTIL_STRIP(( hpx::util::detail::bound_action1< Action , T0 >))) bound , BOOST_FWD_REF(A0) a0 ) { return bound.apply(boost::forward<A0>( a0 )); } template < typename Action , typename T0 , typename A0 , typename A1 > bool apply( BOOST_RV_REF(HPX_UTIL_STRIP(( hpx::util::detail::bound_action1< Action , T0 >))) bound , BOOST_FWD_REF(A0) a0 , BOOST_FWD_REF(A1) a1 ) { return bound.apply(boost::forward<A0>( a0 ) , boost::forward<A1>( a1 )); } template < typename Action , typename T0 , typename A0 , typename A1 , typename A2 > bool apply( BOOST_RV_REF(HPX_UTIL_STRIP(( hpx::util::detail::bound_action1< Action , T0 >))) bound , BOOST_FWD_REF(A0) a0 , BOOST_FWD_REF(A1) a1 , BOOST_FWD_REF(A2) a2 ) { return bound.apply(boost::forward<A0>( a0 ) , boost::forward<A1>( a1 ) , boost::forward<A2>( a2 )); } template < typename Action , typename T0 , typename A0 , typename A1 , typename A2 , typename A3 > bool apply( BOOST_RV_REF(HPX_UTIL_STRIP(( hpx::util::detail::bound_action1< Action , T0 >))) bound , BOOST_FWD_REF(A0) a0 , BOOST_FWD_REF(A1) a1 , BOOST_FWD_REF(A2) a2 , BOOST_FWD_REF(A3) a3 ) { return bound.apply(boost::forward<A0>( a0 ) , boost::forward<A1>( a1 ) , boost::forward<A2>( a2 ) , boost::forward<A3>( a3 )); } template < typename Action , typename T0 , typename A0 , typename A1 , typename A2 , typename A3 , typename A4 > bool apply( BOOST_RV_REF(HPX_UTIL_STRIP(( hpx::util::detail::bound_action1< Action , T0 >))) bound , BOOST_FWD_REF(A0) a0 , BOOST_FWD_REF(A1) a1 , BOOST_FWD_REF(A2) a2 , BOOST_FWD_REF(A3) a3 , BOOST_FWD_REF(A4) a4 ) { return bound.apply(boost::forward<A0>( a0 ) , boost::forward<A1>( a1 ) , boost::forward<A2>( a2 ) , boost::forward<A3>( a3 ) , boost::forward<A4>( a4 )); } template < typename Action , typename T0 , typename A0 , typename A1 , typename A2 , typename A3 , typename A4 , typename A5 > bool apply( BOOST_RV_REF(HPX_UTIL_STRIP(( hpx::util::detail::bound_action1< Action , T0 >))) bound , BOOST_FWD_REF(A0) a0 , BOOST_FWD_REF(A1) a1 , BOOST_FWD_REF(A2) a2 , BOOST_FWD_REF(A3) a3 , BOOST_FWD_REF(A4) a4 , BOOST_FWD_REF(A5) a5 ) { return bound.apply(boost::forward<A0>( a0 ) , boost::forward<A1>( a1 ) , boost::forward<A2>( a2 ) , boost::forward<A3>( a3 ) , boost::forward<A4>( a4 ) , boost::forward<A5>( a5 )); } template < typename Action , typename T0 , typename A0 , typename A1 , typename A2 , typename A3 , typename A4 , typename A5 , typename A6 > bool apply( BOOST_RV_REF(HPX_UTIL_STRIP(( hpx::util::detail::bound_action1< Action , T0 >))) bound , BOOST_FWD_REF(A0) a0 , BOOST_FWD_REF(A1) a1 , BOOST_FWD_REF(A2) a2 , BOOST_FWD_REF(A3) a3 , BOOST_FWD_REF(A4) a4 , BOOST_FWD_REF(A5) a5 , BOOST_FWD_REF(A6) a6 ) { return bound.apply(boost::forward<A0>( a0 ) , boost::forward<A1>( a1 ) , boost::forward<A2>( a2 ) , boost::forward<A3>( a3 ) , boost::forward<A4>( a4 ) , boost::forward<A5>( a5 ) , boost::forward<A6>( a6 )); } template < typename Action , typename T0 , typename A0 , typename A1 , typename A2 , typename A3 , typename A4 , typename A5 , typename A6 , typename A7 > bool apply( BOOST_RV_REF(HPX_UTIL_STRIP(( hpx::util::detail::bound_action1< Action , T0 >))) bound , BOOST_FWD_REF(A0) a0 , BOOST_FWD_REF(A1) a1 , BOOST_FWD_REF(A2) a2 , BOOST_FWD_REF(A3) a3 , BOOST_FWD_REF(A4) a4 , BOOST_FWD_REF(A5) a5 , BOOST_FWD_REF(A6) a6 , BOOST_FWD_REF(A7) a7 ) { return bound.apply(boost::forward<A0>( a0 ) , boost::forward<A1>( a1 ) , boost::forward<A2>( a2 ) , boost::forward<A3>( a3 ) , boost::forward<A4>( a4 ) , boost::forward<A5>( a5 ) , boost::forward<A6>( a6 ) , boost::forward<A7>( a7 )); } template < typename Action , typename T0 , typename A0 , typename A1 , typename A2 , typename A3 , typename A4 , typename A5 , typename A6 , typename A7 , typename A8 > bool apply( BOOST_RV_REF(HPX_UTIL_STRIP(( hpx::util::detail::bound_action1< Action , T0 >))) bound , BOOST_FWD_REF(A0) a0 , BOOST_FWD_REF(A1) a1 , BOOST_FWD_REF(A2) a2 , BOOST_FWD_REF(A3) a3 , BOOST_FWD_REF(A4) a4 , BOOST_FWD_REF(A5) a5 , BOOST_FWD_REF(A6) a6 , BOOST_FWD_REF(A7) a7 , BOOST_FWD_REF(A8) a8 ) { return bound.apply(boost::forward<A0>( a0 ) , boost::forward<A1>( a1 ) , boost::forward<A2>( a2 ) , boost::forward<A3>( a3 ) , boost::forward<A4>( a4 ) , boost::forward<A5>( a5 ) , boost::forward<A6>( a6 ) , boost::forward<A7>( a7 ) , boost::forward<A8>( a8 )); } template < typename Action , typename T0 , typename A0 , typename A1 , typename A2 , typename A3 , typename A4 , typename A5 , typename A6 , typename A7 , typename A8 , typename A9 > bool apply( BOOST_RV_REF(HPX_UTIL_STRIP(( hpx::util::detail::bound_action1< Action , T0 >))) bound , BOOST_FWD_REF(A0) a0 , BOOST_FWD_REF(A1) a1 , BOOST_FWD_REF(A2) a2 , BOOST_FWD_REF(A3) a3 , BOOST_FWD_REF(A4) a4 , BOOST_FWD_REF(A5) a5 , BOOST_FWD_REF(A6) a6 , BOOST_FWD_REF(A7) a7 , BOOST_FWD_REF(A8) a8 , BOOST_FWD_REF(A9) a9 ) { return bound.apply(boost::forward<A0>( a0 ) , boost::forward<A1>( a1 ) , boost::forward<A2>( a2 ) , boost::forward<A3>( a3 ) , boost::forward<A4>( a4 ) , boost::forward<A5>( a5 ) , boost::forward<A6>( a6 ) , boost::forward<A7>( a7 ) , boost::forward<A8>( a8 ) , boost::forward<A9>( a9 )); } template < typename Action , typename T0 , typename A0 , typename A1 , typename A2 , typename A3 , typename A4 , typename A5 , typename A6 , typename A7 , typename A8 , typename A9 , typename A10 > bool apply( BOOST_RV_REF(HPX_UTIL_STRIP(( hpx::util::detail::bound_action1< Action , T0 >))) bound , BOOST_FWD_REF(A0) a0 , BOOST_FWD_REF(A1) a1 , BOOST_FWD_REF(A2) a2 , BOOST_FWD_REF(A3) a3 , BOOST_FWD_REF(A4) a4 , BOOST_FWD_REF(A5) a5 , BOOST_FWD_REF(A6) a6 , BOOST_FWD_REF(A7) a7 , BOOST_FWD_REF(A8) a8 , BOOST_FWD_REF(A9) a9 , BOOST_FWD_REF(A10) a10 ) { return bound.apply(boost::forward<A0>( a0 ) , boost::forward<A1>( a1 ) , boost::forward<A2>( a2 ) , boost::forward<A3>( a3 ) , boost::forward<A4>( a4 ) , boost::forward<A5>( a5 ) , boost::forward<A6>( a6 ) , boost::forward<A7>( a7 ) , boost::forward<A8>( a8 ) , boost::forward<A9>( a9 ) , boost::forward<A10>( a10 )); } template < typename Action , typename T0 , typename A0 , typename A1 , typename A2 , typename A3 , typename A4 , typename A5 , typename A6 , typename A7 , typename A8 , typename A9 , typename A10 , typename A11 > bool apply( BOOST_RV_REF(HPX_UTIL_STRIP(( hpx::util::detail::bound_action1< Action , T0 >))) bound , BOOST_FWD_REF(A0) a0 , BOOST_FWD_REF(A1) a1 , BOOST_FWD_REF(A2) a2 , BOOST_FWD_REF(A3) a3 , BOOST_FWD_REF(A4) a4 , BOOST_FWD_REF(A5) a5 , BOOST_FWD_REF(A6) a6 , BOOST_FWD_REF(A7) a7 , BOOST_FWD_REF(A8) a8 , BOOST_FWD_REF(A9) a9 , BOOST_FWD_REF(A10) a10 , BOOST_FWD_REF(A11) a11 ) { return bound.apply(boost::forward<A0>( a0 ) , boost::forward<A1>( a1 ) , boost::forward<A2>( a2 ) , boost::forward<A3>( a3 ) , boost::forward<A4>( a4 ) , boost::forward<A5>( a5 ) , boost::forward<A6>( a6 ) , boost::forward<A7>( a7 ) , boost::forward<A8>( a8 ) , boost::forward<A9>( a9 ) , boost::forward<A10>( a10 ) , boost::forward<A11>( a11 )); }
}
namespace hpx
{
template <
typename Action
, typename T0 , typename T1
>
bool apply(
BOOST_RV_REF(HPX_UTIL_STRIP((
hpx::util::detail::bound_action2<
Action
, T0 , T1
>))) bound)
{
return bound.apply();
}
template < typename Action , typename T0 , typename T1 , typename A0 > bool apply( BOOST_RV_REF(HPX_UTIL_STRIP(( hpx::util::detail::bound_action2< Action , T0 , T1 >))) bound , BOOST_FWD_REF(A0) a0 ) { return bound.apply(boost::forward<A0>( a0 )); } template < typename Action , typename T0 , typename T1 , typename A0 , typename A1 > bool apply( BOOST_RV_REF(HPX_UTIL_STRIP(( hpx::util::detail::bound_action2< Action , T0 , T1 >))) bound , BOOST_FWD_REF(A0) a0 , BOOST_FWD_REF(A1) a1 ) { return bound.apply(boost::forward<A0>( a0 ) , boost::forward<A1>( a1 )); } template < typename Action , typename T0 , typename T1 , typename A0 , typename A1 , typename A2 > bool apply( BOOST_RV_REF(HPX_UTIL_STRIP(( hpx::util::detail::bound_action2< Action , T0 , T1 >))) bound , BOOST_FWD_REF(A0) a0 , BOOST_FWD_REF(A1) a1 , BOOST_FWD_REF(A2) a2 ) { return bound.apply(boost::forward<A0>( a0 ) , boost::forward<A1>( a1 ) , boost::forward<A2>( a2 )); } template < typename Action , typename T0 , typename T1 , typename A0 , typename A1 , typename A2 , typename A3 > bool apply( BOOST_RV_REF(HPX_UTIL_STRIP(( hpx::util::detail::bound_action2< Action , T0 , T1 >))) bound , BOOST_FWD_REF(A0) a0 , BOOST_FWD_REF(A1) a1 , BOOST_FWD_REF(A2) a2 , BOOST_FWD_REF(A3) a3 ) { return bound.apply(boost::forward<A0>( a0 ) , boost::forward<A1>( a1 ) , boost::forward<A2>( a2 ) , boost::forward<A3>( a3 )); } template < typename Action , typename T0 , typename T1 , typename A0 , typename A1 , typename A2 , typename A3 , typename A4 > bool apply( BOOST_RV_REF(HPX_UTIL_STRIP(( hpx::util::detail::bound_action2< Action , T0 , T1 >))) bound , BOOST_FWD_REF(A0) a0 , BOOST_FWD_REF(A1) a1 , BOOST_FWD_REF(A2) a2 , BOOST_FWD_REF(A3) a3 , BOOST_FWD_REF(A4) a4 ) { return bound.apply(boost::forward<A0>( a0 ) , boost::forward<A1>( a1 ) , boost::forward<A2>( a2 ) , boost::forward<A3>( a3 ) , boost::forward<A4>( a4 )); } template < typename Action , typename T0 , typename T1 , typename A0 , typename A1 , typename A2 , typename A3 , typename A4 , typename A5 > bool apply( BOOST_RV_REF(HPX_UTIL_STRIP(( hpx::util::detail::bound_action2< Action , T0 , T1 >))) bound , BOOST_FWD_REF(A0) a0 , BOOST_FWD_REF(A1) a1 , BOOST_FWD_REF(A2) a2 , BOOST_FWD_REF(A3) a3 , BOOST_FWD_REF(A4) a4 , BOOST_FWD_REF(A5) a5 ) { return bound.apply(boost::forward<A0>( a0 ) , boost::forward<A1>( a1 ) , boost::forward<A2>( a2 ) , boost::forward<A3>( a3 ) , boost::forward<A4>( a4 ) , boost::forward<A5>( a5 )); } template < typename Action , typename T0 , typename T1 , typename A0 , typename A1 , typename A2 , typename A3 , typename A4 , typename A5 , typename A6 > bool apply( BOOST_RV_REF(HPX_UTIL_STRIP(( hpx::util::detail::bound_action2< Action , T0 , T1 >))) bound , BOOST_FWD_REF(A0) a0 , BOOST_FWD_REF(A1) a1 , BOOST_FWD_REF(A2) a2 , BOOST_FWD_REF(A3) a3 , BOOST_FWD_REF(A4) a4 , BOOST_FWD_REF(A5) a5 , BOOST_FWD_REF(A6) a6 ) { return bound.apply(boost::forward<A0>( a0 ) , boost::forward<A1>( a1 ) , boost::forward<A2>( a2 ) , boost::forward<A3>( a3 ) , boost::forward<A4>( a4 ) , boost::forward<A5>( a5 ) , boost::forward<A6>( a6 )); } template < typename Action , typename T0 , typename T1 , typename A0 , typename A1 , typename A2 , typename A3 , typename A4 , typename A5 , typename A6 , typename A7 > bool apply( BOOST_RV_REF(HPX_UTIL_STRIP(( hpx::util::detail::bound_action2< Action , T0 , T1 >))) bound , BOOST_FWD_REF(A0) a0 , BOOST_FWD_REF(A1) a1 , BOOST_FWD_REF(A2) a2 , BOOST_FWD_REF(A3) a3 , BOOST_FWD_REF(A4) a4 , BOOST_FWD_REF(A5) a5 , BOOST_FWD_REF(A6) a6 , BOOST_FWD_REF(A7) a7 ) { return bound.apply(boost::forward<A0>( a0 ) , boost::forward<A1>( a1 ) , boost::forward<A2>( a2 ) , boost::forward<A3>( a3 ) , boost::forward<A4>( a4 ) , boost::forward<A5>( a5 ) , boost::forward<A6>( a6 ) , boost::forward<A7>( a7 )); } template < typename Action , typename T0 , typename T1 , typename A0 , typename A1 , typename A2 , typename A3 , typename A4 , typename A5 , typename A6 , typename A7 , typename A8 > bool apply( BOOST_RV_REF(HPX_UTIL_STRIP(( hpx::util::detail::bound_action2< Action , T0 , T1 >))) bound , BOOST_FWD_REF(A0) a0 , BOOST_FWD_REF(A1) a1 , BOOST_FWD_REF(A2) a2 , BOOST_FWD_REF(A3) a3 , BOOST_FWD_REF(A4) a4 , BOOST_FWD_REF(A5) a5 , BOOST_FWD_REF(A6) a6 , BOOST_FWD_REF(A7) a7 , BOOST_FWD_REF(A8) a8 ) { return bound.apply(boost::forward<A0>( a0 ) , boost::forward<A1>( a1 ) , boost::forward<A2>( a2 ) , boost::forward<A3>( a3 ) , boost::forward<A4>( a4 ) , boost::forward<A5>( a5 ) , boost::forward<A6>( a6 ) , boost::forward<A7>( a7 ) , boost::forward<A8>( a8 )); } template < typename Action , typename T0 , typename T1 , typename A0 , typename A1 , typename A2 , typename A3 , typename A4 , typename A5 , typename A6 , typename A7 , typename A8 , typename A9 > bool apply( BOOST_RV_REF(HPX_UTIL_STRIP(( hpx::util::detail::bound_action2< Action , T0 , T1 >))) bound , BOOST_FWD_REF(A0) a0 , BOOST_FWD_REF(A1) a1 , BOOST_FWD_REF(A2) a2 , BOOST_FWD_REF(A3) a3 , BOOST_FWD_REF(A4) a4 , BOOST_FWD_REF(A5) a5 , BOOST_FWD_REF(A6) a6 , BOOST_FWD_REF(A7) a7 , BOOST_FWD_REF(A8) a8 , BOOST_FWD_REF(A9) a9 ) { return bound.apply(boost::forward<A0>( a0 ) , boost::forward<A1>( a1 ) , boost::forward<A2>( a2 ) , boost::forward<A3>( a3 ) , boost::forward<A4>( a4 ) , boost::forward<A5>( a5 ) , boost::forward<A6>( a6 ) , boost::forward<A7>( a7 ) , boost::forward<A8>( a8 ) , boost::forward<A9>( a9 )); } template < typename Action , typename T0 , typename T1 , typename A0 , typename A1 , typename A2 , typename A3 , typename A4 , typename A5 , typename A6 , typename A7 , typename A8 , typename A9 , typename A10 > bool apply( BOOST_RV_REF(HPX_UTIL_STRIP(( hpx::util::detail::bound_action2< Action , T0 , T1 >))) bound , BOOST_FWD_REF(A0) a0 , BOOST_FWD_REF(A1) a1 , BOOST_FWD_REF(A2) a2 , BOOST_FWD_REF(A3) a3 , BOOST_FWD_REF(A4) a4 , BOOST_FWD_REF(A5) a5 , BOOST_FWD_REF(A6) a6 , BOOST_FWD_REF(A7) a7 , BOOST_FWD_REF(A8) a8 , BOOST_FWD_REF(A9) a9 , BOOST_FWD_REF(A10) a10 ) { return bound.apply(boost::forward<A0>( a0 ) , boost::forward<A1>( a1 ) , boost::forward<A2>( a2 ) , boost::forward<A3>( a3 ) , boost::forward<A4>( a4 ) , boost::forward<A5>( a5 ) , boost::forward<A6>( a6 ) , boost::forward<A7>( a7 ) , boost::forward<A8>( a8 ) , boost::forward<A9>( a9 ) , boost::forward<A10>( a10 )); } template < typename Action , typename T0 , typename T1 , typename A0 , typename A1 , typename A2 , typename A3 , typename A4 , typename A5 , typename A6 , typename A7 , typename A8 , typename A9 , typename A10 , typename A11 > bool apply( BOOST_RV_REF(HPX_UTIL_STRIP(( hpx::util::detail::bound_action2< Action , T0 , T1 >))) bound , BOOST_FWD_REF(A0) a0 , BOOST_FWD_REF(A1) a1 , BOOST_FWD_REF(A2) a2 , BOOST_FWD_REF(A3) a3 , BOOST_FWD_REF(A4) a4 , BOOST_FWD_REF(A5) a5 , BOOST_FWD_REF(A6) a6 , BOOST_FWD_REF(A7) a7 , BOOST_FWD_REF(A8) a8 , BOOST_FWD_REF(A9) a9 , BOOST_FWD_REF(A10) a10 , BOOST_FWD_REF(A11) a11 ) { return bound.apply(boost::forward<A0>( a0 ) , boost::forward<A1>( a1 ) , boost::forward<A2>( a2 ) , boost::forward<A3>( a3 ) , boost::forward<A4>( a4 ) , boost::forward<A5>( a5 ) , boost::forward<A6>( a6 ) , boost::forward<A7>( a7 ) , boost::forward<A8>( a8 ) , boost::forward<A9>( a9 ) , boost::forward<A10>( a10 ) , boost::forward<A11>( a11 )); }
}
namespace hpx
{
template <
typename Action
, typename T0 , typename T1 , typename T2
>
bool apply(
BOOST_RV_REF(HPX_UTIL_STRIP((
hpx::util::detail::bound_action3<
Action
, T0 , T1 , T2
>))) bound)
{
return bound.apply();
}
template < typename Action , typename T0 , typename T1 , typename T2 , typename A0 > bool apply( BOOST_RV_REF(HPX_UTIL_STRIP(( hpx::util::detail::bound_action3< Action , T0 , T1 , T2 >))) bound , BOOST_FWD_REF(A0) a0 ) { return bound.apply(boost::forward<A0>( a0 )); } template < typename Action , typename T0 , typename T1 , typename T2 , typename A0 , typename A1 > bool apply( BOOST_RV_REF(HPX_UTIL_STRIP(( hpx::util::detail::bound_action3< Action , T0 , T1 , T2 >))) bound , BOOST_FWD_REF(A0) a0 , BOOST_FWD_REF(A1) a1 ) { return bound.apply(boost::forward<A0>( a0 ) , boost::forward<A1>( a1 )); } template < typename Action , typename T0 , typename T1 , typename T2 , typename A0 , typename A1 , typename A2 > bool apply( BOOST_RV_REF(HPX_UTIL_STRIP(( hpx::util::detail::bound_action3< Action , T0 , T1 , T2 >))) bound , BOOST_FWD_REF(A0) a0 , BOOST_FWD_REF(A1) a1 , BOOST_FWD_REF(A2) a2 ) { return bound.apply(boost::forward<A0>( a0 ) , boost::forward<A1>( a1 ) , boost::forward<A2>( a2 )); } template < typename Action , typename T0 , typename T1 , typename T2 , typename A0 , typename A1 , typename A2 , typename A3 > bool apply( BOOST_RV_REF(HPX_UTIL_STRIP(( hpx::util::detail::bound_action3< Action , T0 , T1 , T2 >))) bound , BOOST_FWD_REF(A0) a0 , BOOST_FWD_REF(A1) a1 , BOOST_FWD_REF(A2) a2 , BOOST_FWD_REF(A3) a3 ) { return bound.apply(boost::forward<A0>( a0 ) , boost::forward<A1>( a1 ) , boost::forward<A2>( a2 ) , boost::forward<A3>( a3 )); } template < typename Action , typename T0 , typename T1 , typename T2 , typename A0 , typename A1 , typename A2 , typename A3 , typename A4 > bool apply( BOOST_RV_REF(HPX_UTIL_STRIP(( hpx::util::detail::bound_action3< Action , T0 , T1 , T2 >))) bound , BOOST_FWD_REF(A0) a0 , BOOST_FWD_REF(A1) a1 , BOOST_FWD_REF(A2) a2 , BOOST_FWD_REF(A3) a3 , BOOST_FWD_REF(A4) a4 ) { return bound.apply(boost::forward<A0>( a0 ) , boost::forward<A1>( a1 ) , boost::forward<A2>( a2 ) , boost::forward<A3>( a3 ) , boost::forward<A4>( a4 )); } template < typename Action , typename T0 , typename T1 , typename T2 , typename A0 , typename A1 , typename A2 , typename A3 , typename A4 , typename A5 > bool apply( BOOST_RV_REF(HPX_UTIL_STRIP(( hpx::util::detail::bound_action3< Action , T0 , T1 , T2 >))) bound , BOOST_FWD_REF(A0) a0 , BOOST_FWD_REF(A1) a1 , BOOST_FWD_REF(A2) a2 , BOOST_FWD_REF(A3) a3 , BOOST_FWD_REF(A4) a4 , BOOST_FWD_REF(A5) a5 ) { return bound.apply(boost::forward<A0>( a0 ) , boost::forward<A1>( a1 ) , boost::forward<A2>( a2 ) , boost::forward<A3>( a3 ) , boost::forward<A4>( a4 ) , boost::forward<A5>( a5 )); } template < typename Action , typename T0 , typename T1 , typename T2 , typename A0 , typename A1 , typename A2 , typename A3 , typename A4 , typename A5 , typename A6 > bool apply( BOOST_RV_REF(HPX_UTIL_STRIP(( hpx::util::detail::bound_action3< Action , T0 , T1 , T2 >))) bound , BOOST_FWD_REF(A0) a0 , BOOST_FWD_REF(A1) a1 , BOOST_FWD_REF(A2) a2 , BOOST_FWD_REF(A3) a3 , BOOST_FWD_REF(A4) a4 , BOOST_FWD_REF(A5) a5 , BOOST_FWD_REF(A6) a6 ) { return bound.apply(boost::forward<A0>( a0 ) , boost::forward<A1>( a1 ) , boost::forward<A2>( a2 ) , boost::forward<A3>( a3 ) , boost::forward<A4>( a4 ) , boost::forward<A5>( a5 ) , boost::forward<A6>( a6 )); } template < typename Action , typename T0 , typename T1 , typename T2 , typename A0 , typename A1 , typename A2 , typename A3 , typename A4 , typename A5 , typename A6 , typename A7 > bool apply( BOOST_RV_REF(HPX_UTIL_STRIP(( hpx::util::detail::bound_action3< Action , T0 , T1 , T2 >))) bound , BOOST_FWD_REF(A0) a0 , BOOST_FWD_REF(A1) a1 , BOOST_FWD_REF(A2) a2 , BOOST_FWD_REF(A3) a3 , BOOST_FWD_REF(A4) a4 , BOOST_FWD_REF(A5) a5 , BOOST_FWD_REF(A6) a6 , BOOST_FWD_REF(A7) a7 ) { return bound.apply(boost::forward<A0>( a0 ) , boost::forward<A1>( a1 ) , boost::forward<A2>( a2 ) , boost::forward<A3>( a3 ) , boost::forward<A4>( a4 ) , boost::forward<A5>( a5 ) , boost::forward<A6>( a6 ) , boost::forward<A7>( a7 )); } template < typename Action , typename T0 , typename T1 , typename T2 , typename A0 , typename A1 , typename A2 , typename A3 , typename A4 , typename A5 , typename A6 , typename A7 , typename A8 > bool apply( BOOST_RV_REF(HPX_UTIL_STRIP(( hpx::util::detail::bound_action3< Action , T0 , T1 , T2 >))) bound , BOOST_FWD_REF(A0) a0 , BOOST_FWD_REF(A1) a1 , BOOST_FWD_REF(A2) a2 , BOOST_FWD_REF(A3) a3 , BOOST_FWD_REF(A4) a4 , BOOST_FWD_REF(A5) a5 , BOOST_FWD_REF(A6) a6 , BOOST_FWD_REF(A7) a7 , BOOST_FWD_REF(A8) a8 ) { return bound.apply(boost::forward<A0>( a0 ) , boost::forward<A1>( a1 ) , boost::forward<A2>( a2 ) , boost::forward<A3>( a3 ) , boost::forward<A4>( a4 ) , boost::forward<A5>( a5 ) , boost::forward<A6>( a6 ) , boost::forward<A7>( a7 ) , boost::forward<A8>( a8 )); } template < typename Action , typename T0 , typename T1 , typename T2 , typename A0 , typename A1 , typename A2 , typename A3 , typename A4 , typename A5 , typename A6 , typename A7 , typename A8 , typename A9 > bool apply( BOOST_RV_REF(HPX_UTIL_STRIP(( hpx::util::detail::bound_action3< Action , T0 , T1 , T2 >))) bound , BOOST_FWD_REF(A0) a0 , BOOST_FWD_REF(A1) a1 , BOOST_FWD_REF(A2) a2 , BOOST_FWD_REF(A3) a3 , BOOST_FWD_REF(A4) a4 , BOOST_FWD_REF(A5) a5 , BOOST_FWD_REF(A6) a6 , BOOST_FWD_REF(A7) a7 , BOOST_FWD_REF(A8) a8 , BOOST_FWD_REF(A9) a9 ) { return bound.apply(boost::forward<A0>( a0 ) , boost::forward<A1>( a1 ) , boost::forward<A2>( a2 ) , boost::forward<A3>( a3 ) , boost::forward<A4>( a4 ) , boost::forward<A5>( a5 ) , boost::forward<A6>( a6 ) , boost::forward<A7>( a7 ) , boost::forward<A8>( a8 ) , boost::forward<A9>( a9 )); } template < typename Action , typename T0 , typename T1 , typename T2 , typename A0 , typename A1 , typename A2 , typename A3 , typename A4 , typename A5 , typename A6 , typename A7 , typename A8 , typename A9 , typename A10 > bool apply( BOOST_RV_REF(HPX_UTIL_STRIP(( hpx::util::detail::bound_action3< Action , T0 , T1 , T2 >))) bound , BOOST_FWD_REF(A0) a0 , BOOST_FWD_REF(A1) a1 , BOOST_FWD_REF(A2) a2 , BOOST_FWD_REF(A3) a3 , BOOST_FWD_REF(A4) a4 , BOOST_FWD_REF(A5) a5 , BOOST_FWD_REF(A6) a6 , BOOST_FWD_REF(A7) a7 , BOOST_FWD_REF(A8) a8 , BOOST_FWD_REF(A9) a9 , BOOST_FWD_REF(A10) a10 ) { return bound.apply(boost::forward<A0>( a0 ) , boost::forward<A1>( a1 ) , boost::forward<A2>( a2 ) , boost::forward<A3>( a3 ) , boost::forward<A4>( a4 ) , boost::forward<A5>( a5 ) , boost::forward<A6>( a6 ) , boost::forward<A7>( a7 ) , boost::forward<A8>( a8 ) , boost::forward<A9>( a9 ) , boost::forward<A10>( a10 )); } template < typename Action , typename T0 , typename T1 , typename T2 , typename A0 , typename A1 , typename A2 , typename A3 , typename A4 , typename A5 , typename A6 , typename A7 , typename A8 , typename A9 , typename A10 , typename A11 > bool apply( BOOST_RV_REF(HPX_UTIL_STRIP(( hpx::util::detail::bound_action3< Action , T0 , T1 , T2 >))) bound , BOOST_FWD_REF(A0) a0 , BOOST_FWD_REF(A1) a1 , BOOST_FWD_REF(A2) a2 , BOOST_FWD_REF(A3) a3 , BOOST_FWD_REF(A4) a4 , BOOST_FWD_REF(A5) a5 , BOOST_FWD_REF(A6) a6 , BOOST_FWD_REF(A7) a7 , BOOST_FWD_REF(A8) a8 , BOOST_FWD_REF(A9) a9 , BOOST_FWD_REF(A10) a10 , BOOST_FWD_REF(A11) a11 ) { return bound.apply(boost::forward<A0>( a0 ) , boost::forward<A1>( a1 ) , boost::forward<A2>( a2 ) , boost::forward<A3>( a3 ) , boost::forward<A4>( a4 ) , boost::forward<A5>( a5 ) , boost::forward<A6>( a6 ) , boost::forward<A7>( a7 ) , boost::forward<A8>( a8 ) , boost::forward<A9>( a9 ) , boost::forward<A10>( a10 ) , boost::forward<A11>( a11 )); }
}
namespace hpx
{
template <
typename Action
, typename T0 , typename T1 , typename T2 , typename T3
>
bool apply(
BOOST_RV_REF(HPX_UTIL_STRIP((
hpx::util::detail::bound_action4<
Action
, T0 , T1 , T2 , T3
>))) bound)
{
return bound.apply();
}
template < typename Action , typename T0 , typename T1 , typename T2 , typename T3 , typename A0 > bool apply( BOOST_RV_REF(HPX_UTIL_STRIP(( hpx::util::detail::bound_action4< Action , T0 , T1 , T2 , T3 >))) bound , BOOST_FWD_REF(A0) a0 ) { return bound.apply(boost::forward<A0>( a0 )); } template < typename Action , typename T0 , typename T1 , typename T2 , typename T3 , typename A0 , typename A1 > bool apply( BOOST_RV_REF(HPX_UTIL_STRIP(( hpx::util::detail::bound_action4< Action , T0 , T1 , T2 , T3 >))) bound , BOOST_FWD_REF(A0) a0 , BOOST_FWD_REF(A1) a1 ) { return bound.apply(boost::forward<A0>( a0 ) , boost::forward<A1>( a1 )); } template < typename Action , typename T0 , typename T1 , typename T2 , typename T3 , typename A0 , typename A1 , typename A2 > bool apply( BOOST_RV_REF(HPX_UTIL_STRIP(( hpx::util::detail::bound_action4< Action , T0 , T1 , T2 , T3 >))) bound , BOOST_FWD_REF(A0) a0 , BOOST_FWD_REF(A1) a1 , BOOST_FWD_REF(A2) a2 ) { return bound.apply(boost::forward<A0>( a0 ) , boost::forward<A1>( a1 ) , boost::forward<A2>( a2 )); } template < typename Action , typename T0 , typename T1 , typename T2 , typename T3 , typename A0 , typename A1 , typename A2 , typename A3 > bool apply( BOOST_RV_REF(HPX_UTIL_STRIP(( hpx::util::detail::bound_action4< Action , T0 , T1 , T2 , T3 >))) bound , BOOST_FWD_REF(A0) a0 , BOOST_FWD_REF(A1) a1 , BOOST_FWD_REF(A2) a2 , BOOST_FWD_REF(A3) a3 ) { return bound.apply(boost::forward<A0>( a0 ) , boost::forward<A1>( a1 ) , boost::forward<A2>( a2 ) , boost::forward<A3>( a3 )); } template < typename Action , typename T0 , typename T1 , typename T2 , typename T3 , typename A0 , typename A1 , typename A2 , typename A3 , typename A4 > bool apply( BOOST_RV_REF(HPX_UTIL_STRIP(( hpx::util::detail::bound_action4< Action , T0 , T1 , T2 , T3 >))) bound , BOOST_FWD_REF(A0) a0 , BOOST_FWD_REF(A1) a1 , BOOST_FWD_REF(A2) a2 , BOOST_FWD_REF(A3) a3 , BOOST_FWD_REF(A4) a4 ) { return bound.apply(boost::forward<A0>( a0 ) , boost::forward<A1>( a1 ) , boost::forward<A2>( a2 ) , boost::forward<A3>( a3 ) , boost::forward<A4>( a4 )); } template < typename Action , typename T0 , typename T1 , typename T2 , typename T3 , typename A0 , typename A1 , typename A2 , typename A3 , typename A4 , typename A5 > bool apply( BOOST_RV_REF(HPX_UTIL_STRIP(( hpx::util::detail::bound_action4< Action , T0 , T1 , T2 , T3 >))) bound , BOOST_FWD_REF(A0) a0 , BOOST_FWD_REF(A1) a1 , BOOST_FWD_REF(A2) a2 , BOOST_FWD_REF(A3) a3 , BOOST_FWD_REF(A4) a4 , BOOST_FWD_REF(A5) a5 ) { return bound.apply(boost::forward<A0>( a0 ) , boost::forward<A1>( a1 ) , boost::forward<A2>( a2 ) , boost::forward<A3>( a3 ) , boost::forward<A4>( a4 ) , boost::forward<A5>( a5 )); } template < typename Action , typename T0 , typename T1 , typename T2 , typename T3 , typename A0 , typename A1 , typename A2 , typename A3 , typename A4 , typename A5 , typename A6 > bool apply( BOOST_RV_REF(HPX_UTIL_STRIP(( hpx::util::detail::bound_action4< Action , T0 , T1 , T2 , T3 >))) bound , BOOST_FWD_REF(A0) a0 , BOOST_FWD_REF(A1) a1 , BOOST_FWD_REF(A2) a2 , BOOST_FWD_REF(A3) a3 , BOOST_FWD_REF(A4) a4 , BOOST_FWD_REF(A5) a5 , BOOST_FWD_REF(A6) a6 ) { return bound.apply(boost::forward<A0>( a0 ) , boost::forward<A1>( a1 ) , boost::forward<A2>( a2 ) , boost::forward<A3>( a3 ) , boost::forward<A4>( a4 ) , boost::forward<A5>( a5 ) , boost::forward<A6>( a6 )); } template < typename Action , typename T0 , typename T1 , typename T2 , typename T3 , typename A0 , typename A1 , typename A2 , typename A3 , typename A4 , typename A5 , typename A6 , typename A7 > bool apply( BOOST_RV_REF(HPX_UTIL_STRIP(( hpx::util::detail::bound_action4< Action , T0 , T1 , T2 , T3 >))) bound , BOOST_FWD_REF(A0) a0 , BOOST_FWD_REF(A1) a1 , BOOST_FWD_REF(A2) a2 , BOOST_FWD_REF(A3) a3 , BOOST_FWD_REF(A4) a4 , BOOST_FWD_REF(A5) a5 , BOOST_FWD_REF(A6) a6 , BOOST_FWD_REF(A7) a7 ) { return bound.apply(boost::forward<A0>( a0 ) , boost::forward<A1>( a1 ) , boost::forward<A2>( a2 ) , boost::forward<A3>( a3 ) , boost::forward<A4>( a4 ) , boost::forward<A5>( a5 ) , boost::forward<A6>( a6 ) , boost::forward<A7>( a7 )); } template < typename Action , typename T0 , typename T1 , typename T2 , typename T3 , typename A0 , typename A1 , typename A2 , typename A3 , typename A4 , typename A5 , typename A6 , typename A7 , typename A8 > bool apply( BOOST_RV_REF(HPX_UTIL_STRIP(( hpx::util::detail::bound_action4< Action , T0 , T1 , T2 , T3 >))) bound , BOOST_FWD_REF(A0) a0 , BOOST_FWD_REF(A1) a1 , BOOST_FWD_REF(A2) a2 , BOOST_FWD_REF(A3) a3 , BOOST_FWD_REF(A4) a4 , BOOST_FWD_REF(A5) a5 , BOOST_FWD_REF(A6) a6 , BOOST_FWD_REF(A7) a7 , BOOST_FWD_REF(A8) a8 ) { return bound.apply(boost::forward<A0>( a0 ) , boost::forward<A1>( a1 ) , boost::forward<A2>( a2 ) , boost::forward<A3>( a3 ) , boost::forward<A4>( a4 ) , boost::forward<A5>( a5 ) , boost::forward<A6>( a6 ) , boost::forward<A7>( a7 ) , boost::forward<A8>( a8 )); } template < typename Action , typename T0 , typename T1 , typename T2 , typename T3 , typename A0 , typename A1 , typename A2 , typename A3 , typename A4 , typename A5 , typename A6 , typename A7 , typename A8 , typename A9 > bool apply( BOOST_RV_REF(HPX_UTIL_STRIP(( hpx::util::detail::bound_action4< Action , T0 , T1 , T2 , T3 >))) bound , BOOST_FWD_REF(A0) a0 , BOOST_FWD_REF(A1) a1 , BOOST_FWD_REF(A2) a2 , BOOST_FWD_REF(A3) a3 , BOOST_FWD_REF(A4) a4 , BOOST_FWD_REF(A5) a5 , BOOST_FWD_REF(A6) a6 , BOOST_FWD_REF(A7) a7 , BOOST_FWD_REF(A8) a8 , BOOST_FWD_REF(A9) a9 ) { return bound.apply(boost::forward<A0>( a0 ) , boost::forward<A1>( a1 ) , boost::forward<A2>( a2 ) , boost::forward<A3>( a3 ) , boost::forward<A4>( a4 ) , boost::forward<A5>( a5 ) , boost::forward<A6>( a6 ) , boost::forward<A7>( a7 ) , boost::forward<A8>( a8 ) , boost::forward<A9>( a9 )); } template < typename Action , typename T0 , typename T1 , typename T2 , typename T3 , typename A0 , typename A1 , typename A2 , typename A3 , typename A4 , typename A5 , typename A6 , typename A7 , typename A8 , typename A9 , typename A10 > bool apply( BOOST_RV_REF(HPX_UTIL_STRIP(( hpx::util::detail::bound_action4< Action , T0 , T1 , T2 , T3 >))) bound , BOOST_FWD_REF(A0) a0 , BOOST_FWD_REF(A1) a1 , BOOST_FWD_REF(A2) a2 , BOOST_FWD_REF(A3) a3 , BOOST_FWD_REF(A4) a4 , BOOST_FWD_REF(A5) a5 , BOOST_FWD_REF(A6) a6 , BOOST_FWD_REF(A7) a7 , BOOST_FWD_REF(A8) a8 , BOOST_FWD_REF(A9) a9 , BOOST_FWD_REF(A10) a10 ) { return bound.apply(boost::forward<A0>( a0 ) , boost::forward<A1>( a1 ) , boost::forward<A2>( a2 ) , boost::forward<A3>( a3 ) , boost::forward<A4>( a4 ) , boost::forward<A5>( a5 ) , boost::forward<A6>( a6 ) , boost::forward<A7>( a7 ) , boost::forward<A8>( a8 ) , boost::forward<A9>( a9 ) , boost::forward<A10>( a10 )); } template < typename Action , typename T0 , typename T1 , typename T2 , typename T3 , typename A0 , typename A1 , typename A2 , typename A3 , typename A4 , typename A5 , typename A6 , typename A7 , typename A8 , typename A9 , typename A10 , typename A11 > bool apply( BOOST_RV_REF(HPX_UTIL_STRIP(( hpx::util::detail::bound_action4< Action , T0 , T1 , T2 , T3 >))) bound , BOOST_FWD_REF(A0) a0 , BOOST_FWD_REF(A1) a1 , BOOST_FWD_REF(A2) a2 , BOOST_FWD_REF(A3) a3 , BOOST_FWD_REF(A4) a4 , BOOST_FWD_REF(A5) a5 , BOOST_FWD_REF(A6) a6 , BOOST_FWD_REF(A7) a7 , BOOST_FWD_REF(A8) a8 , BOOST_FWD_REF(A9) a9 , BOOST_FWD_REF(A10) a10 , BOOST_FWD_REF(A11) a11 ) { return bound.apply(boost::forward<A0>( a0 ) , boost::forward<A1>( a1 ) , boost::forward<A2>( a2 ) , boost::forward<A3>( a3 ) , boost::forward<A4>( a4 ) , boost::forward<A5>( a5 ) , boost::forward<A6>( a6 ) , boost::forward<A7>( a7 ) , boost::forward<A8>( a8 ) , boost::forward<A9>( a9 ) , boost::forward<A10>( a10 ) , boost::forward<A11>( a11 )); }
}
namespace hpx
{
template <
typename Action
, typename T0 , typename T1 , typename T2 , typename T3 , typename T4
>
bool apply(
BOOST_RV_REF(HPX_UTIL_STRIP((
hpx::util::detail::bound_action5<
Action
, T0 , T1 , T2 , T3 , T4
>))) bound)
{
return bound.apply();
}
template < typename Action , typename T0 , typename T1 , typename T2 , typename T3 , typename T4 , typename A0 > bool apply( BOOST_RV_REF(HPX_UTIL_STRIP(( hpx::util::detail::bound_action5< Action , T0 , T1 , T2 , T3 , T4 >))) bound , BOOST_FWD_REF(A0) a0 ) { return bound.apply(boost::forward<A0>( a0 )); } template < typename Action , typename T0 , typename T1 , typename T2 , typename T3 , typename T4 , typename A0 , typename A1 > bool apply( BOOST_RV_REF(HPX_UTIL_STRIP(( hpx::util::detail::bound_action5< Action , T0 , T1 , T2 , T3 , T4 >))) bound , BOOST_FWD_REF(A0) a0 , BOOST_FWD_REF(A1) a1 ) { return bound.apply(boost::forward<A0>( a0 ) , boost::forward<A1>( a1 )); } template < typename Action , typename T0 , typename T1 , typename T2 , typename T3 , typename T4 , typename A0 , typename A1 , typename A2 > bool apply( BOOST_RV_REF(HPX_UTIL_STRIP(( hpx::util::detail::bound_action5< Action , T0 , T1 , T2 , T3 , T4 >))) bound , BOOST_FWD_REF(A0) a0 , BOOST_FWD_REF(A1) a1 , BOOST_FWD_REF(A2) a2 ) { return bound.apply(boost::forward<A0>( a0 ) , boost::forward<A1>( a1 ) , boost::forward<A2>( a2 )); } template < typename Action , typename T0 , typename T1 , typename T2 , typename T3 , typename T4 , typename A0 , typename A1 , typename A2 , typename A3 > bool apply( BOOST_RV_REF(HPX_UTIL_STRIP(( hpx::util::detail::bound_action5< Action , T0 , T1 , T2 , T3 , T4 >))) bound , BOOST_FWD_REF(A0) a0 , BOOST_FWD_REF(A1) a1 , BOOST_FWD_REF(A2) a2 , BOOST_FWD_REF(A3) a3 ) { return bound.apply(boost::forward<A0>( a0 ) , boost::forward<A1>( a1 ) , boost::forward<A2>( a2 ) , boost::forward<A3>( a3 )); } template < typename Action , typename T0 , typename T1 , typename T2 , typename T3 , typename T4 , typename A0 , typename A1 , typename A2 , typename A3 , typename A4 > bool apply( BOOST_RV_REF(HPX_UTIL_STRIP(( hpx::util::detail::bound_action5< Action , T0 , T1 , T2 , T3 , T4 >))) bound , BOOST_FWD_REF(A0) a0 , BOOST_FWD_REF(A1) a1 , BOOST_FWD_REF(A2) a2 , BOOST_FWD_REF(A3) a3 , BOOST_FWD_REF(A4) a4 ) { return bound.apply(boost::forward<A0>( a0 ) , boost::forward<A1>( a1 ) , boost::forward<A2>( a2 ) , boost::forward<A3>( a3 ) , boost::forward<A4>( a4 )); } template < typename Action , typename T0 , typename T1 , typename T2 , typename T3 , typename T4 , typename A0 , typename A1 , typename A2 , typename A3 , typename A4 , typename A5 > bool apply( BOOST_RV_REF(HPX_UTIL_STRIP(( hpx::util::detail::bound_action5< Action , T0 , T1 , T2 , T3 , T4 >))) bound , BOOST_FWD_REF(A0) a0 , BOOST_FWD_REF(A1) a1 , BOOST_FWD_REF(A2) a2 , BOOST_FWD_REF(A3) a3 , BOOST_FWD_REF(A4) a4 , BOOST_FWD_REF(A5) a5 ) { return bound.apply(boost::forward<A0>( a0 ) , boost::forward<A1>( a1 ) , boost::forward<A2>( a2 ) , boost::forward<A3>( a3 ) , boost::forward<A4>( a4 ) , boost::forward<A5>( a5 )); } template < typename Action , typename T0 , typename T1 , typename T2 , typename T3 , typename T4 , typename A0 , typename A1 , typename A2 , typename A3 , typename A4 , typename A5 , typename A6 > bool apply( BOOST_RV_REF(HPX_UTIL_STRIP(( hpx::util::detail::bound_action5< Action , T0 , T1 , T2 , T3 , T4 >))) bound , BOOST_FWD_REF(A0) a0 , BOOST_FWD_REF(A1) a1 , BOOST_FWD_REF(A2) a2 , BOOST_FWD_REF(A3) a3 , BOOST_FWD_REF(A4) a4 , BOOST_FWD_REF(A5) a5 , BOOST_FWD_REF(A6) a6 ) { return bound.apply(boost::forward<A0>( a0 ) , boost::forward<A1>( a1 ) , boost::forward<A2>( a2 ) , boost::forward<A3>( a3 ) , boost::forward<A4>( a4 ) , boost::forward<A5>( a5 ) , boost::forward<A6>( a6 )); } template < typename Action , typename T0 , typename T1 , typename T2 , typename T3 , typename T4 , typename A0 , typename A1 , typename A2 , typename A3 , typename A4 , typename A5 , typename A6 , typename A7 > bool apply( BOOST_RV_REF(HPX_UTIL_STRIP(( hpx::util::detail::bound_action5< Action , T0 , T1 , T2 , T3 , T4 >))) bound , BOOST_FWD_REF(A0) a0 , BOOST_FWD_REF(A1) a1 , BOOST_FWD_REF(A2) a2 , BOOST_FWD_REF(A3) a3 , BOOST_FWD_REF(A4) a4 , BOOST_FWD_REF(A5) a5 , BOOST_FWD_REF(A6) a6 , BOOST_FWD_REF(A7) a7 ) { return bound.apply(boost::forward<A0>( a0 ) , boost::forward<A1>( a1 ) , boost::forward<A2>( a2 ) , boost::forward<A3>( a3 ) , boost::forward<A4>( a4 ) , boost::forward<A5>( a5 ) , boost::forward<A6>( a6 ) , boost::forward<A7>( a7 )); } template < typename Action , typename T0 , typename T1 , typename T2 , typename T3 , typename T4 , typename A0 , typename A1 , typename A2 , typename A3 , typename A4 , typename A5 , typename A6 , typename A7 , typename A8 > bool apply( BOOST_RV_REF(HPX_UTIL_STRIP(( hpx::util::detail::bound_action5< Action , T0 , T1 , T2 , T3 , T4 >))) bound , BOOST_FWD_REF(A0) a0 , BOOST_FWD_REF(A1) a1 , BOOST_FWD_REF(A2) a2 , BOOST_FWD_REF(A3) a3 , BOOST_FWD_REF(A4) a4 , BOOST_FWD_REF(A5) a5 , BOOST_FWD_REF(A6) a6 , BOOST_FWD_REF(A7) a7 , BOOST_FWD_REF(A8) a8 ) { return bound.apply(boost::forward<A0>( a0 ) , boost::forward<A1>( a1 ) , boost::forward<A2>( a2 ) , boost::forward<A3>( a3 ) , boost::forward<A4>( a4 ) , boost::forward<A5>( a5 ) , boost::forward<A6>( a6 ) , boost::forward<A7>( a7 ) , boost::forward<A8>( a8 )); } template < typename Action , typename T0 , typename T1 , typename T2 , typename T3 , typename T4 , typename A0 , typename A1 , typename A2 , typename A3 , typename A4 , typename A5 , typename A6 , typename A7 , typename A8 , typename A9 > bool apply( BOOST_RV_REF(HPX_UTIL_STRIP(( hpx::util::detail::bound_action5< Action , T0 , T1 , T2 , T3 , T4 >))) bound , BOOST_FWD_REF(A0) a0 , BOOST_FWD_REF(A1) a1 , BOOST_FWD_REF(A2) a2 , BOOST_FWD_REF(A3) a3 , BOOST_FWD_REF(A4) a4 , BOOST_FWD_REF(A5) a5 , BOOST_FWD_REF(A6) a6 , BOOST_FWD_REF(A7) a7 , BOOST_FWD_REF(A8) a8 , BOOST_FWD_REF(A9) a9 ) { return bound.apply(boost::forward<A0>( a0 ) , boost::forward<A1>( a1 ) , boost::forward<A2>( a2 ) , boost::forward<A3>( a3 ) , boost::forward<A4>( a4 ) , boost::forward<A5>( a5 ) , boost::forward<A6>( a6 ) , boost::forward<A7>( a7 ) , boost::forward<A8>( a8 ) , boost::forward<A9>( a9 )); } template < typename Action , typename T0 , typename T1 , typename T2 , typename T3 , typename T4 , typename A0 , typename A1 , typename A2 , typename A3 , typename A4 , typename A5 , typename A6 , typename A7 , typename A8 , typename A9 , typename A10 > bool apply( BOOST_RV_REF(HPX_UTIL_STRIP(( hpx::util::detail::bound_action5< Action , T0 , T1 , T2 , T3 , T4 >))) bound , BOOST_FWD_REF(A0) a0 , BOOST_FWD_REF(A1) a1 , BOOST_FWD_REF(A2) a2 , BOOST_FWD_REF(A3) a3 , BOOST_FWD_REF(A4) a4 , BOOST_FWD_REF(A5) a5 , BOOST_FWD_REF(A6) a6 , BOOST_FWD_REF(A7) a7 , BOOST_FWD_REF(A8) a8 , BOOST_FWD_REF(A9) a9 , BOOST_FWD_REF(A10) a10 ) { return bound.apply(boost::forward<A0>( a0 ) , boost::forward<A1>( a1 ) , boost::forward<A2>( a2 ) , boost::forward<A3>( a3 ) , boost::forward<A4>( a4 ) , boost::forward<A5>( a5 ) , boost::forward<A6>( a6 ) , boost::forward<A7>( a7 ) , boost::forward<A8>( a8 ) , boost::forward<A9>( a9 ) , boost::forward<A10>( a10 )); } template < typename Action , typename T0 , typename T1 , typename T2 , typename T3 , typename T4 , typename A0 , typename A1 , typename A2 , typename A3 , typename A4 , typename A5 , typename A6 , typename A7 , typename A8 , typename A9 , typename A10 , typename A11 > bool apply( BOOST_RV_REF(HPX_UTIL_STRIP(( hpx::util::detail::bound_action5< Action , T0 , T1 , T2 , T3 , T4 >))) bound , BOOST_FWD_REF(A0) a0 , BOOST_FWD_REF(A1) a1 , BOOST_FWD_REF(A2) a2 , BOOST_FWD_REF(A3) a3 , BOOST_FWD_REF(A4) a4 , BOOST_FWD_REF(A5) a5 , BOOST_FWD_REF(A6) a6 , BOOST_FWD_REF(A7) a7 , BOOST_FWD_REF(A8) a8 , BOOST_FWD_REF(A9) a9 , BOOST_FWD_REF(A10) a10 , BOOST_FWD_REF(A11) a11 ) { return bound.apply(boost::forward<A0>( a0 ) , boost::forward<A1>( a1 ) , boost::forward<A2>( a2 ) , boost::forward<A3>( a3 ) , boost::forward<A4>( a4 ) , boost::forward<A5>( a5 ) , boost::forward<A6>( a6 ) , boost::forward<A7>( a7 ) , boost::forward<A8>( a8 ) , boost::forward<A9>( a9 ) , boost::forward<A10>( a10 ) , boost::forward<A11>( a11 )); }
}
namespace hpx
{
template <
typename Action
, typename T0 , typename T1 , typename T2 , typename T3 , typename T4 , typename T5
>
bool apply(
BOOST_RV_REF(HPX_UTIL_STRIP((
hpx::util::detail::bound_action6<
Action
, T0 , T1 , T2 , T3 , T4 , T5
>))) bound)
{
return bound.apply();
}
template < typename Action , typename T0 , typename T1 , typename T2 , typename T3 , typename T4 , typename T5 , typename A0 > bool apply( BOOST_RV_REF(HPX_UTIL_STRIP(( hpx::util::detail::bound_action6< Action , T0 , T1 , T2 , T3 , T4 , T5 >))) bound , BOOST_FWD_REF(A0) a0 ) { return bound.apply(boost::forward<A0>( a0 )); } template < typename Action , typename T0 , typename T1 , typename T2 , typename T3 , typename T4 , typename T5 , typename A0 , typename A1 > bool apply( BOOST_RV_REF(HPX_UTIL_STRIP(( hpx::util::detail::bound_action6< Action , T0 , T1 , T2 , T3 , T4 , T5 >))) bound , BOOST_FWD_REF(A0) a0 , BOOST_FWD_REF(A1) a1 ) { return bound.apply(boost::forward<A0>( a0 ) , boost::forward<A1>( a1 )); } template < typename Action , typename T0 , typename T1 , typename T2 , typename T3 , typename T4 , typename T5 , typename A0 , typename A1 , typename A2 > bool apply( BOOST_RV_REF(HPX_UTIL_STRIP(( hpx::util::detail::bound_action6< Action , T0 , T1 , T2 , T3 , T4 , T5 >))) bound , BOOST_FWD_REF(A0) a0 , BOOST_FWD_REF(A1) a1 , BOOST_FWD_REF(A2) a2 ) { return bound.apply(boost::forward<A0>( a0 ) , boost::forward<A1>( a1 ) , boost::forward<A2>( a2 )); } template < typename Action , typename T0 , typename T1 , typename T2 , typename T3 , typename T4 , typename T5 , typename A0 , typename A1 , typename A2 , typename A3 > bool apply( BOOST_RV_REF(HPX_UTIL_STRIP(( hpx::util::detail::bound_action6< Action , T0 , T1 , T2 , T3 , T4 , T5 >))) bound , BOOST_FWD_REF(A0) a0 , BOOST_FWD_REF(A1) a1 , BOOST_FWD_REF(A2) a2 , BOOST_FWD_REF(A3) a3 ) { return bound.apply(boost::forward<A0>( a0 ) , boost::forward<A1>( a1 ) , boost::forward<A2>( a2 ) , boost::forward<A3>( a3 )); } template < typename Action , typename T0 , typename T1 , typename T2 , typename T3 , typename T4 , typename T5 , typename A0 , typename A1 , typename A2 , typename A3 , typename A4 > bool apply( BOOST_RV_REF(HPX_UTIL_STRIP(( hpx::util::detail::bound_action6< Action , T0 , T1 , T2 , T3 , T4 , T5 >))) bound , BOOST_FWD_REF(A0) a0 , BOOST_FWD_REF(A1) a1 , BOOST_FWD_REF(A2) a2 , BOOST_FWD_REF(A3) a3 , BOOST_FWD_REF(A4) a4 ) { return bound.apply(boost::forward<A0>( a0 ) , boost::forward<A1>( a1 ) , boost::forward<A2>( a2 ) , boost::forward<A3>( a3 ) , boost::forward<A4>( a4 )); } template < typename Action , typename T0 , typename T1 , typename T2 , typename T3 , typename T4 , typename T5 , typename A0 , typename A1 , typename A2 , typename A3 , typename A4 , typename A5 > bool apply( BOOST_RV_REF(HPX_UTIL_STRIP(( hpx::util::detail::bound_action6< Action , T0 , T1 , T2 , T3 , T4 , T5 >))) bound , BOOST_FWD_REF(A0) a0 , BOOST_FWD_REF(A1) a1 , BOOST_FWD_REF(A2) a2 , BOOST_FWD_REF(A3) a3 , BOOST_FWD_REF(A4) a4 , BOOST_FWD_REF(A5) a5 ) { return bound.apply(boost::forward<A0>( a0 ) , boost::forward<A1>( a1 ) , boost::forward<A2>( a2 ) , boost::forward<A3>( a3 ) , boost::forward<A4>( a4 ) , boost::forward<A5>( a5 )); } template < typename Action , typename T0 , typename T1 , typename T2 , typename T3 , typename T4 , typename T5 , typename A0 , typename A1 , typename A2 , typename A3 , typename A4 , typename A5 , typename A6 > bool apply( BOOST_RV_REF(HPX_UTIL_STRIP(( hpx::util::detail::bound_action6< Action , T0 , T1 , T2 , T3 , T4 , T5 >))) bound , BOOST_FWD_REF(A0) a0 , BOOST_FWD_REF(A1) a1 , BOOST_FWD_REF(A2) a2 , BOOST_FWD_REF(A3) a3 , BOOST_FWD_REF(A4) a4 , BOOST_FWD_REF(A5) a5 , BOOST_FWD_REF(A6) a6 ) { return bound.apply(boost::forward<A0>( a0 ) , boost::forward<A1>( a1 ) , boost::forward<A2>( a2 ) , boost::forward<A3>( a3 ) , boost::forward<A4>( a4 ) , boost::forward<A5>( a5 ) , boost::forward<A6>( a6 )); } template < typename Action , typename T0 , typename T1 , typename T2 , typename T3 , typename T4 , typename T5 , typename A0 , typename A1 , typename A2 , typename A3 , typename A4 , typename A5 , typename A6 , typename A7 > bool apply( BOOST_RV_REF(HPX_UTIL_STRIP(( hpx::util::detail::bound_action6< Action , T0 , T1 , T2 , T3 , T4 , T5 >))) bound , BOOST_FWD_REF(A0) a0 , BOOST_FWD_REF(A1) a1 , BOOST_FWD_REF(A2) a2 , BOOST_FWD_REF(A3) a3 , BOOST_FWD_REF(A4) a4 , BOOST_FWD_REF(A5) a5 , BOOST_FWD_REF(A6) a6 , BOOST_FWD_REF(A7) a7 ) { return bound.apply(boost::forward<A0>( a0 ) , boost::forward<A1>( a1 ) , boost::forward<A2>( a2 ) , boost::forward<A3>( a3 ) , boost::forward<A4>( a4 ) , boost::forward<A5>( a5 ) , boost::forward<A6>( a6 ) , boost::forward<A7>( a7 )); } template < typename Action , typename T0 , typename T1 , typename T2 , typename T3 , typename T4 , typename T5 , typename A0 , typename A1 , typename A2 , typename A3 , typename A4 , typename A5 , typename A6 , typename A7 , typename A8 > bool apply( BOOST_RV_REF(HPX_UTIL_STRIP(( hpx::util::detail::bound_action6< Action , T0 , T1 , T2 , T3 , T4 , T5 >))) bound , BOOST_FWD_REF(A0) a0 , BOOST_FWD_REF(A1) a1 , BOOST_FWD_REF(A2) a2 , BOOST_FWD_REF(A3) a3 , BOOST_FWD_REF(A4) a4 , BOOST_FWD_REF(A5) a5 , BOOST_FWD_REF(A6) a6 , BOOST_FWD_REF(A7) a7 , BOOST_FWD_REF(A8) a8 ) { return bound.apply(boost::forward<A0>( a0 ) , boost::forward<A1>( a1 ) , boost::forward<A2>( a2 ) , boost::forward<A3>( a3 ) , boost::forward<A4>( a4 ) , boost::forward<A5>( a5 ) , boost::forward<A6>( a6 ) , boost::forward<A7>( a7 ) , boost::forward<A8>( a8 )); } template < typename Action , typename T0 , typename T1 , typename T2 , typename T3 , typename T4 , typename T5 , typename A0 , typename A1 , typename A2 , typename A3 , typename A4 , typename A5 , typename A6 , typename A7 , typename A8 , typename A9 > bool apply( BOOST_RV_REF(HPX_UTIL_STRIP(( hpx::util::detail::bound_action6< Action , T0 , T1 , T2 , T3 , T4 , T5 >))) bound , BOOST_FWD_REF(A0) a0 , BOOST_FWD_REF(A1) a1 , BOOST_FWD_REF(A2) a2 , BOOST_FWD_REF(A3) a3 , BOOST_FWD_REF(A4) a4 , BOOST_FWD_REF(A5) a5 , BOOST_FWD_REF(A6) a6 , BOOST_FWD_REF(A7) a7 , BOOST_FWD_REF(A8) a8 , BOOST_FWD_REF(A9) a9 ) { return bound.apply(boost::forward<A0>( a0 ) , boost::forward<A1>( a1 ) , boost::forward<A2>( a2 ) , boost::forward<A3>( a3 ) , boost::forward<A4>( a4 ) , boost::forward<A5>( a5 ) , boost::forward<A6>( a6 ) , boost::forward<A7>( a7 ) , boost::forward<A8>( a8 ) , boost::forward<A9>( a9 )); } template < typename Action , typename T0 , typename T1 , typename T2 , typename T3 , typename T4 , typename T5 , typename A0 , typename A1 , typename A2 , typename A3 , typename A4 , typename A5 , typename A6 , typename A7 , typename A8 , typename A9 , typename A10 > bool apply( BOOST_RV_REF(HPX_UTIL_STRIP(( hpx::util::detail::bound_action6< Action , T0 , T1 , T2 , T3 , T4 , T5 >))) bound , BOOST_FWD_REF(A0) a0 , BOOST_FWD_REF(A1) a1 , BOOST_FWD_REF(A2) a2 , BOOST_FWD_REF(A3) a3 , BOOST_FWD_REF(A4) a4 , BOOST_FWD_REF(A5) a5 , BOOST_FWD_REF(A6) a6 , BOOST_FWD_REF(A7) a7 , BOOST_FWD_REF(A8) a8 , BOOST_FWD_REF(A9) a9 , BOOST_FWD_REF(A10) a10 ) { return bound.apply(boost::forward<A0>( a0 ) , boost::forward<A1>( a1 ) , boost::forward<A2>( a2 ) , boost::forward<A3>( a3 ) , boost::forward<A4>( a4 ) , boost::forward<A5>( a5 ) , boost::forward<A6>( a6 ) , boost::forward<A7>( a7 ) , boost::forward<A8>( a8 ) , boost::forward<A9>( a9 ) , boost::forward<A10>( a10 )); } template < typename Action , typename T0 , typename T1 , typename T2 , typename T3 , typename T4 , typename T5 , typename A0 , typename A1 , typename A2 , typename A3 , typename A4 , typename A5 , typename A6 , typename A7 , typename A8 , typename A9 , typename A10 , typename A11 > bool apply( BOOST_RV_REF(HPX_UTIL_STRIP(( hpx::util::detail::bound_action6< Action , T0 , T1 , T2 , T3 , T4 , T5 >))) bound , BOOST_FWD_REF(A0) a0 , BOOST_FWD_REF(A1) a1 , BOOST_FWD_REF(A2) a2 , BOOST_FWD_REF(A3) a3 , BOOST_FWD_REF(A4) a4 , BOOST_FWD_REF(A5) a5 , BOOST_FWD_REF(A6) a6 , BOOST_FWD_REF(A7) a7 , BOOST_FWD_REF(A8) a8 , BOOST_FWD_REF(A9) a9 , BOOST_FWD_REF(A10) a10 , BOOST_FWD_REF(A11) a11 ) { return bound.apply(boost::forward<A0>( a0 ) , boost::forward<A1>( a1 ) , boost::forward<A2>( a2 ) , boost::forward<A3>( a3 ) , boost::forward<A4>( a4 ) , boost::forward<A5>( a5 ) , boost::forward<A6>( a6 ) , boost::forward<A7>( a7 ) , boost::forward<A8>( a8 ) , boost::forward<A9>( a9 ) , boost::forward<A10>( a10 ) , boost::forward<A11>( a11 )); }
}
namespace hpx
{
template <
typename Action
, typename T0 , typename T1 , typename T2 , typename T3 , typename T4 , typename T5 , typename T6
>
bool apply(
BOOST_RV_REF(HPX_UTIL_STRIP((
hpx::util::detail::bound_action7<
Action
, T0 , T1 , T2 , T3 , T4 , T5 , T6
>))) bound)
{
return bound.apply();
}
template < typename Action , typename T0 , typename T1 , typename T2 , typename T3 , typename T4 , typename T5 , typename T6 , typename A0 > bool apply( BOOST_RV_REF(HPX_UTIL_STRIP(( hpx::util::detail::bound_action7< Action , T0 , T1 , T2 , T3 , T4 , T5 , T6 >))) bound , BOOST_FWD_REF(A0) a0 ) { return bound.apply(boost::forward<A0>( a0 )); } template < typename Action , typename T0 , typename T1 , typename T2 , typename T3 , typename T4 , typename T5 , typename T6 , typename A0 , typename A1 > bool apply( BOOST_RV_REF(HPX_UTIL_STRIP(( hpx::util::detail::bound_action7< Action , T0 , T1 , T2 , T3 , T4 , T5 , T6 >))) bound , BOOST_FWD_REF(A0) a0 , BOOST_FWD_REF(A1) a1 ) { return bound.apply(boost::forward<A0>( a0 ) , boost::forward<A1>( a1 )); } template < typename Action , typename T0 , typename T1 , typename T2 , typename T3 , typename T4 , typename T5 , typename T6 , typename A0 , typename A1 , typename A2 > bool apply( BOOST_RV_REF(HPX_UTIL_STRIP(( hpx::util::detail::bound_action7< Action , T0 , T1 , T2 , T3 , T4 , T5 , T6 >))) bound , BOOST_FWD_REF(A0) a0 , BOOST_FWD_REF(A1) a1 , BOOST_FWD_REF(A2) a2 ) { return bound.apply(boost::forward<A0>( a0 ) , boost::forward<A1>( a1 ) , boost::forward<A2>( a2 )); } template < typename Action , typename T0 , typename T1 , typename T2 , typename T3 , typename T4 , typename T5 , typename T6 , typename A0 , typename A1 , typename A2 , typename A3 > bool apply( BOOST_RV_REF(HPX_UTIL_STRIP(( hpx::util::detail::bound_action7< Action , T0 , T1 , T2 , T3 , T4 , T5 , T6 >))) bound , BOOST_FWD_REF(A0) a0 , BOOST_FWD_REF(A1) a1 , BOOST_FWD_REF(A2) a2 , BOOST_FWD_REF(A3) a3 ) { return bound.apply(boost::forward<A0>( a0 ) , boost::forward<A1>( a1 ) , boost::forward<A2>( a2 ) , boost::forward<A3>( a3 )); } template < typename Action , typename T0 , typename T1 , typename T2 , typename T3 , typename T4 , typename T5 , typename T6 , typename A0 , typename A1 , typename A2 , typename A3 , typename A4 > bool apply( BOOST_RV_REF(HPX_UTIL_STRIP(( hpx::util::detail::bound_action7< Action , T0 , T1 , T2 , T3 , T4 , T5 , T6 >))) bound , BOOST_FWD_REF(A0) a0 , BOOST_FWD_REF(A1) a1 , BOOST_FWD_REF(A2) a2 , BOOST_FWD_REF(A3) a3 , BOOST_FWD_REF(A4) a4 ) { return bound.apply(boost::forward<A0>( a0 ) , boost::forward<A1>( a1 ) , boost::forward<A2>( a2 ) , boost::forward<A3>( a3 ) , boost::forward<A4>( a4 )); } template < typename Action , typename T0 , typename T1 , typename T2 , typename T3 , typename T4 , typename T5 , typename T6 , typename A0 , typename A1 , typename A2 , typename A3 , typename A4 , typename A5 > bool apply( BOOST_RV_REF(HPX_UTIL_STRIP(( hpx::util::detail::bound_action7< Action , T0 , T1 , T2 , T3 , T4 , T5 , T6 >))) bound , BOOST_FWD_REF(A0) a0 , BOOST_FWD_REF(A1) a1 , BOOST_FWD_REF(A2) a2 , BOOST_FWD_REF(A3) a3 , BOOST_FWD_REF(A4) a4 , BOOST_FWD_REF(A5) a5 ) { return bound.apply(boost::forward<A0>( a0 ) , boost::forward<A1>( a1 ) , boost::forward<A2>( a2 ) , boost::forward<A3>( a3 ) , boost::forward<A4>( a4 ) , boost::forward<A5>( a5 )); } template < typename Action , typename T0 , typename T1 , typename T2 , typename T3 , typename T4 , typename T5 , typename T6 , typename A0 , typename A1 , typename A2 , typename A3 , typename A4 , typename A5 , typename A6 > bool apply( BOOST_RV_REF(HPX_UTIL_STRIP(( hpx::util::detail::bound_action7< Action , T0 , T1 , T2 , T3 , T4 , T5 , T6 >))) bound , BOOST_FWD_REF(A0) a0 , BOOST_FWD_REF(A1) a1 , BOOST_FWD_REF(A2) a2 , BOOST_FWD_REF(A3) a3 , BOOST_FWD_REF(A4) a4 , BOOST_FWD_REF(A5) a5 , BOOST_FWD_REF(A6) a6 ) { return bound.apply(boost::forward<A0>( a0 ) , boost::forward<A1>( a1 ) , boost::forward<A2>( a2 ) , boost::forward<A3>( a3 ) , boost::forward<A4>( a4 ) , boost::forward<A5>( a5 ) , boost::forward<A6>( a6 )); } template < typename Action , typename T0 , typename T1 , typename T2 , typename T3 , typename T4 , typename T5 , typename T6 , typename A0 , typename A1 , typename A2 , typename A3 , typename A4 , typename A5 , typename A6 , typename A7 > bool apply( BOOST_RV_REF(HPX_UTIL_STRIP(( hpx::util::detail::bound_action7< Action , T0 , T1 , T2 , T3 , T4 , T5 , T6 >))) bound , BOOST_FWD_REF(A0) a0 , BOOST_FWD_REF(A1) a1 , BOOST_FWD_REF(A2) a2 , BOOST_FWD_REF(A3) a3 , BOOST_FWD_REF(A4) a4 , BOOST_FWD_REF(A5) a5 , BOOST_FWD_REF(A6) a6 , BOOST_FWD_REF(A7) a7 ) { return bound.apply(boost::forward<A0>( a0 ) , boost::forward<A1>( a1 ) , boost::forward<A2>( a2 ) , boost::forward<A3>( a3 ) , boost::forward<A4>( a4 ) , boost::forward<A5>( a5 ) , boost::forward<A6>( a6 ) , boost::forward<A7>( a7 )); } template < typename Action , typename T0 , typename T1 , typename T2 , typename T3 , typename T4 , typename T5 , typename T6 , typename A0 , typename A1 , typename A2 , typename A3 , typename A4 , typename A5 , typename A6 , typename A7 , typename A8 > bool apply( BOOST_RV_REF(HPX_UTIL_STRIP(( hpx::util::detail::bound_action7< Action , T0 , T1 , T2 , T3 , T4 , T5 , T6 >))) bound , BOOST_FWD_REF(A0) a0 , BOOST_FWD_REF(A1) a1 , BOOST_FWD_REF(A2) a2 , BOOST_FWD_REF(A3) a3 , BOOST_FWD_REF(A4) a4 , BOOST_FWD_REF(A5) a5 , BOOST_FWD_REF(A6) a6 , BOOST_FWD_REF(A7) a7 , BOOST_FWD_REF(A8) a8 ) { return bound.apply(boost::forward<A0>( a0 ) , boost::forward<A1>( a1 ) , boost::forward<A2>( a2 ) , boost::forward<A3>( a3 ) , boost::forward<A4>( a4 ) , boost::forward<A5>( a5 ) , boost::forward<A6>( a6 ) , boost::forward<A7>( a7 ) , boost::forward<A8>( a8 )); } template < typename Action , typename T0 , typename T1 , typename T2 , typename T3 , typename T4 , typename T5 , typename T6 , typename A0 , typename A1 , typename A2 , typename A3 , typename A4 , typename A5 , typename A6 , typename A7 , typename A8 , typename A9 > bool apply( BOOST_RV_REF(HPX_UTIL_STRIP(( hpx::util::detail::bound_action7< Action , T0 , T1 , T2 , T3 , T4 , T5 , T6 >))) bound , BOOST_FWD_REF(A0) a0 , BOOST_FWD_REF(A1) a1 , BOOST_FWD_REF(A2) a2 , BOOST_FWD_REF(A3) a3 , BOOST_FWD_REF(A4) a4 , BOOST_FWD_REF(A5) a5 , BOOST_FWD_REF(A6) a6 , BOOST_FWD_REF(A7) a7 , BOOST_FWD_REF(A8) a8 , BOOST_FWD_REF(A9) a9 ) { return bound.apply(boost::forward<A0>( a0 ) , boost::forward<A1>( a1 ) , boost::forward<A2>( a2 ) , boost::forward<A3>( a3 ) , boost::forward<A4>( a4 ) , boost::forward<A5>( a5 ) , boost::forward<A6>( a6 ) , boost::forward<A7>( a7 ) , boost::forward<A8>( a8 ) , boost::forward<A9>( a9 )); } template < typename Action , typename T0 , typename T1 , typename T2 , typename T3 , typename T4 , typename T5 , typename T6 , typename A0 , typename A1 , typename A2 , typename A3 , typename A4 , typename A5 , typename A6 , typename A7 , typename A8 , typename A9 , typename A10 > bool apply( BOOST_RV_REF(HPX_UTIL_STRIP(( hpx::util::detail::bound_action7< Action , T0 , T1 , T2 , T3 , T4 , T5 , T6 >))) bound , BOOST_FWD_REF(A0) a0 , BOOST_FWD_REF(A1) a1 , BOOST_FWD_REF(A2) a2 , BOOST_FWD_REF(A3) a3 , BOOST_FWD_REF(A4) a4 , BOOST_FWD_REF(A5) a5 , BOOST_FWD_REF(A6) a6 , BOOST_FWD_REF(A7) a7 , BOOST_FWD_REF(A8) a8 , BOOST_FWD_REF(A9) a9 , BOOST_FWD_REF(A10) a10 ) { return bound.apply(boost::forward<A0>( a0 ) , boost::forward<A1>( a1 ) , boost::forward<A2>( a2 ) , boost::forward<A3>( a3 ) , boost::forward<A4>( a4 ) , boost::forward<A5>( a5 ) , boost::forward<A6>( a6 ) , boost::forward<A7>( a7 ) , boost::forward<A8>( a8 ) , boost::forward<A9>( a9 ) , boost::forward<A10>( a10 )); } template < typename Action , typename T0 , typename T1 , typename T2 , typename T3 , typename T4 , typename T5 , typename T6 , typename A0 , typename A1 , typename A2 , typename A3 , typename A4 , typename A5 , typename A6 , typename A7 , typename A8 , typename A9 , typename A10 , typename A11 > bool apply( BOOST_RV_REF(HPX_UTIL_STRIP(( hpx::util::detail::bound_action7< Action , T0 , T1 , T2 , T3 , T4 , T5 , T6 >))) bound , BOOST_FWD_REF(A0) a0 , BOOST_FWD_REF(A1) a1 , BOOST_FWD_REF(A2) a2 , BOOST_FWD_REF(A3) a3 , BOOST_FWD_REF(A4) a4 , BOOST_FWD_REF(A5) a5 , BOOST_FWD_REF(A6) a6 , BOOST_FWD_REF(A7) a7 , BOOST_FWD_REF(A8) a8 , BOOST_FWD_REF(A9) a9 , BOOST_FWD_REF(A10) a10 , BOOST_FWD_REF(A11) a11 ) { return bound.apply(boost::forward<A0>( a0 ) , boost::forward<A1>( a1 ) , boost::forward<A2>( a2 ) , boost::forward<A3>( a3 ) , boost::forward<A4>( a4 ) , boost::forward<A5>( a5 ) , boost::forward<A6>( a6 ) , boost::forward<A7>( a7 ) , boost::forward<A8>( a8 ) , boost::forward<A9>( a9 ) , boost::forward<A10>( a10 ) , boost::forward<A11>( a11 )); }
}
namespace hpx
{
template <
typename Action
, typename T0 , typename T1 , typename T2 , typename T3 , typename T4 , typename T5 , typename T6 , typename T7
>
bool apply(
BOOST_RV_REF(HPX_UTIL_STRIP((
hpx::util::detail::bound_action8<
Action
, T0 , T1 , T2 , T3 , T4 , T5 , T6 , T7
>))) bound)
{
return bound.apply();
}
template < typename Action , typename T0 , typename T1 , typename T2 , typename T3 , typename T4 , typename T5 , typename T6 , typename T7 , typename A0 > bool apply( BOOST_RV_REF(HPX_UTIL_STRIP(( hpx::util::detail::bound_action8< Action , T0 , T1 , T2 , T3 , T4 , T5 , T6 , T7 >))) bound , BOOST_FWD_REF(A0) a0 ) { return bound.apply(boost::forward<A0>( a0 )); } template < typename Action , typename T0 , typename T1 , typename T2 , typename T3 , typename T4 , typename T5 , typename T6 , typename T7 , typename A0 , typename A1 > bool apply( BOOST_RV_REF(HPX_UTIL_STRIP(( hpx::util::detail::bound_action8< Action , T0 , T1 , T2 , T3 , T4 , T5 , T6 , T7 >))) bound , BOOST_FWD_REF(A0) a0 , BOOST_FWD_REF(A1) a1 ) { return bound.apply(boost::forward<A0>( a0 ) , boost::forward<A1>( a1 )); } template < typename Action , typename T0 , typename T1 , typename T2 , typename T3 , typename T4 , typename T5 , typename T6 , typename T7 , typename A0 , typename A1 , typename A2 > bool apply( BOOST_RV_REF(HPX_UTIL_STRIP(( hpx::util::detail::bound_action8< Action , T0 , T1 , T2 , T3 , T4 , T5 , T6 , T7 >))) bound , BOOST_FWD_REF(A0) a0 , BOOST_FWD_REF(A1) a1 , BOOST_FWD_REF(A2) a2 ) { return bound.apply(boost::forward<A0>( a0 ) , boost::forward<A1>( a1 ) , boost::forward<A2>( a2 )); } template < typename Action , typename T0 , typename T1 , typename T2 , typename T3 , typename T4 , typename T5 , typename T6 , typename T7 , typename A0 , typename A1 , typename A2 , typename A3 > bool apply( BOOST_RV_REF(HPX_UTIL_STRIP(( hpx::util::detail::bound_action8< Action , T0 , T1 , T2 , T3 , T4 , T5 , T6 , T7 >))) bound , BOOST_FWD_REF(A0) a0 , BOOST_FWD_REF(A1) a1 , BOOST_FWD_REF(A2) a2 , BOOST_FWD_REF(A3) a3 ) { return bound.apply(boost::forward<A0>( a0 ) , boost::forward<A1>( a1 ) , boost::forward<A2>( a2 ) , boost::forward<A3>( a3 )); } template < typename Action , typename T0 , typename T1 , typename T2 , typename T3 , typename T4 , typename T5 , typename T6 , typename T7 , typename A0 , typename A1 , typename A2 , typename A3 , typename A4 > bool apply( BOOST_RV_REF(HPX_UTIL_STRIP(( hpx::util::detail::bound_action8< Action , T0 , T1 , T2 , T3 , T4 , T5 , T6 , T7 >))) bound , BOOST_FWD_REF(A0) a0 , BOOST_FWD_REF(A1) a1 , BOOST_FWD_REF(A2) a2 , BOOST_FWD_REF(A3) a3 , BOOST_FWD_REF(A4) a4 ) { return bound.apply(boost::forward<A0>( a0 ) , boost::forward<A1>( a1 ) , boost::forward<A2>( a2 ) , boost::forward<A3>( a3 ) , boost::forward<A4>( a4 )); } template < typename Action , typename T0 , typename T1 , typename T2 , typename T3 , typename T4 , typename T5 , typename T6 , typename T7 , typename A0 , typename A1 , typename A2 , typename A3 , typename A4 , typename A5 > bool apply( BOOST_RV_REF(HPX_UTIL_STRIP(( hpx::util::detail::bound_action8< Action , T0 , T1 , T2 , T3 , T4 , T5 , T6 , T7 >))) bound , BOOST_FWD_REF(A0) a0 , BOOST_FWD_REF(A1) a1 , BOOST_FWD_REF(A2) a2 , BOOST_FWD_REF(A3) a3 , BOOST_FWD_REF(A4) a4 , BOOST_FWD_REF(A5) a5 ) { return bound.apply(boost::forward<A0>( a0 ) , boost::forward<A1>( a1 ) , boost::forward<A2>( a2 ) , boost::forward<A3>( a3 ) , boost::forward<A4>( a4 ) , boost::forward<A5>( a5 )); } template < typename Action , typename T0 , typename T1 , typename T2 , typename T3 , typename T4 , typename T5 , typename T6 , typename T7 , typename A0 , typename A1 , typename A2 , typename A3 , typename A4 , typename A5 , typename A6 > bool apply( BOOST_RV_REF(HPX_UTIL_STRIP(( hpx::util::detail::bound_action8< Action , T0 , T1 , T2 , T3 , T4 , T5 , T6 , T7 >))) bound , BOOST_FWD_REF(A0) a0 , BOOST_FWD_REF(A1) a1 , BOOST_FWD_REF(A2) a2 , BOOST_FWD_REF(A3) a3 , BOOST_FWD_REF(A4) a4 , BOOST_FWD_REF(A5) a5 , BOOST_FWD_REF(A6) a6 ) { return bound.apply(boost::forward<A0>( a0 ) , boost::forward<A1>( a1 ) , boost::forward<A2>( a2 ) , boost::forward<A3>( a3 ) , boost::forward<A4>( a4 ) , boost::forward<A5>( a5 ) , boost::forward<A6>( a6 )); } template < typename Action , typename T0 , typename T1 , typename T2 , typename T3 , typename T4 , typename T5 , typename T6 , typename T7 , typename A0 , typename A1 , typename A2 , typename A3 , typename A4 , typename A5 , typename A6 , typename A7 > bool apply( BOOST_RV_REF(HPX_UTIL_STRIP(( hpx::util::detail::bound_action8< Action , T0 , T1 , T2 , T3 , T4 , T5 , T6 , T7 >))) bound , BOOST_FWD_REF(A0) a0 , BOOST_FWD_REF(A1) a1 , BOOST_FWD_REF(A2) a2 , BOOST_FWD_REF(A3) a3 , BOOST_FWD_REF(A4) a4 , BOOST_FWD_REF(A5) a5 , BOOST_FWD_REF(A6) a6 , BOOST_FWD_REF(A7) a7 ) { return bound.apply(boost::forward<A0>( a0 ) , boost::forward<A1>( a1 ) , boost::forward<A2>( a2 ) , boost::forward<A3>( a3 ) , boost::forward<A4>( a4 ) , boost::forward<A5>( a5 ) , boost::forward<A6>( a6 ) , boost::forward<A7>( a7 )); } template < typename Action , typename T0 , typename T1 , typename T2 , typename T3 , typename T4 , typename T5 , typename T6 , typename T7 , typename A0 , typename A1 , typename A2 , typename A3 , typename A4 , typename A5 , typename A6 , typename A7 , typename A8 > bool apply( BOOST_RV_REF(HPX_UTIL_STRIP(( hpx::util::detail::bound_action8< Action , T0 , T1 , T2 , T3 , T4 , T5 , T6 , T7 >))) bound , BOOST_FWD_REF(A0) a0 , BOOST_FWD_REF(A1) a1 , BOOST_FWD_REF(A2) a2 , BOOST_FWD_REF(A3) a3 , BOOST_FWD_REF(A4) a4 , BOOST_FWD_REF(A5) a5 , BOOST_FWD_REF(A6) a6 , BOOST_FWD_REF(A7) a7 , BOOST_FWD_REF(A8) a8 ) { return bound.apply(boost::forward<A0>( a0 ) , boost::forward<A1>( a1 ) , boost::forward<A2>( a2 ) , boost::forward<A3>( a3 ) , boost::forward<A4>( a4 ) , boost::forward<A5>( a5 ) , boost::forward<A6>( a6 ) , boost::forward<A7>( a7 ) , boost::forward<A8>( a8 )); } template < typename Action , typename T0 , typename T1 , typename T2 , typename T3 , typename T4 , typename T5 , typename T6 , typename T7 , typename A0 , typename A1 , typename A2 , typename A3 , typename A4 , typename A5 , typename A6 , typename A7 , typename A8 , typename A9 > bool apply( BOOST_RV_REF(HPX_UTIL_STRIP(( hpx::util::detail::bound_action8< Action , T0 , T1 , T2 , T3 , T4 , T5 , T6 , T7 >))) bound , BOOST_FWD_REF(A0) a0 , BOOST_FWD_REF(A1) a1 , BOOST_FWD_REF(A2) a2 , BOOST_FWD_REF(A3) a3 , BOOST_FWD_REF(A4) a4 , BOOST_FWD_REF(A5) a5 , BOOST_FWD_REF(A6) a6 , BOOST_FWD_REF(A7) a7 , BOOST_FWD_REF(A8) a8 , BOOST_FWD_REF(A9) a9 ) { return bound.apply(boost::forward<A0>( a0 ) , boost::forward<A1>( a1 ) , boost::forward<A2>( a2 ) , boost::forward<A3>( a3 ) , boost::forward<A4>( a4 ) , boost::forward<A5>( a5 ) , boost::forward<A6>( a6 ) , boost::forward<A7>( a7 ) , boost::forward<A8>( a8 ) , boost::forward<A9>( a9 )); } template < typename Action , typename T0 , typename T1 , typename T2 , typename T3 , typename T4 , typename T5 , typename T6 , typename T7 , typename A0 , typename A1 , typename A2 , typename A3 , typename A4 , typename A5 , typename A6 , typename A7 , typename A8 , typename A9 , typename A10 > bool apply( BOOST_RV_REF(HPX_UTIL_STRIP(( hpx::util::detail::bound_action8< Action , T0 , T1 , T2 , T3 , T4 , T5 , T6 , T7 >))) bound , BOOST_FWD_REF(A0) a0 , BOOST_FWD_REF(A1) a1 , BOOST_FWD_REF(A2) a2 , BOOST_FWD_REF(A3) a3 , BOOST_FWD_REF(A4) a4 , BOOST_FWD_REF(A5) a5 , BOOST_FWD_REF(A6) a6 , BOOST_FWD_REF(A7) a7 , BOOST_FWD_REF(A8) a8 , BOOST_FWD_REF(A9) a9 , BOOST_FWD_REF(A10) a10 ) { return bound.apply(boost::forward<A0>( a0 ) , boost::forward<A1>( a1 ) , boost::forward<A2>( a2 ) , boost::forward<A3>( a3 ) , boost::forward<A4>( a4 ) , boost::forward<A5>( a5 ) , boost::forward<A6>( a6 ) , boost::forward<A7>( a7 ) , boost::forward<A8>( a8 ) , boost::forward<A9>( a9 ) , boost::forward<A10>( a10 )); } template < typename Action , typename T0 , typename T1 , typename T2 , typename T3 , typename T4 , typename T5 , typename T6 , typename T7 , typename A0 , typename A1 , typename A2 , typename A3 , typename A4 , typename A5 , typename A6 , typename A7 , typename A8 , typename A9 , typename A10 , typename A11 > bool apply( BOOST_RV_REF(HPX_UTIL_STRIP(( hpx::util::detail::bound_action8< Action , T0 , T1 , T2 , T3 , T4 , T5 , T6 , T7 >))) bound , BOOST_FWD_REF(A0) a0 , BOOST_FWD_REF(A1) a1 , BOOST_FWD_REF(A2) a2 , BOOST_FWD_REF(A3) a3 , BOOST_FWD_REF(A4) a4 , BOOST_FWD_REF(A5) a5 , BOOST_FWD_REF(A6) a6 , BOOST_FWD_REF(A7) a7 , BOOST_FWD_REF(A8) a8 , BOOST_FWD_REF(A9) a9 , BOOST_FWD_REF(A10) a10 , BOOST_FWD_REF(A11) a11 ) { return bound.apply(boost::forward<A0>( a0 ) , boost::forward<A1>( a1 ) , boost::forward<A2>( a2 ) , boost::forward<A3>( a3 ) , boost::forward<A4>( a4 ) , boost::forward<A5>( a5 ) , boost::forward<A6>( a6 ) , boost::forward<A7>( a7 ) , boost::forward<A8>( a8 ) , boost::forward<A9>( a9 ) , boost::forward<A10>( a10 ) , boost::forward<A11>( a11 )); }
}
namespace hpx
{
template <
typename Action
, typename T0 , typename T1 , typename T2 , typename T3 , typename T4 , typename T5 , typename T6 , typename T7 , typename T8
>
bool apply(
BOOST_RV_REF(HPX_UTIL_STRIP((
hpx::util::detail::bound_action9<
Action
, T0 , T1 , T2 , T3 , T4 , T5 , T6 , T7 , T8
>))) bound)
{
return bound.apply();
}
template < typename Action , typename T0 , typename T1 , typename T2 , typename T3 , typename T4 , typename T5 , typename T6 , typename T7 , typename T8 , typename A0 > bool apply( BOOST_RV_REF(HPX_UTIL_STRIP(( hpx::util::detail::bound_action9< Action , T0 , T1 , T2 , T3 , T4 , T5 , T6 , T7 , T8 >))) bound , BOOST_FWD_REF(A0) a0 ) { return bound.apply(boost::forward<A0>( a0 )); } template < typename Action , typename T0 , typename T1 , typename T2 , typename T3 , typename T4 , typename T5 , typename T6 , typename T7 , typename T8 , typename A0 , typename A1 > bool apply( BOOST_RV_REF(HPX_UTIL_STRIP(( hpx::util::detail::bound_action9< Action , T0 , T1 , T2 , T3 , T4 , T5 , T6 , T7 , T8 >))) bound , BOOST_FWD_REF(A0) a0 , BOOST_FWD_REF(A1) a1 ) { return bound.apply(boost::forward<A0>( a0 ) , boost::forward<A1>( a1 )); } template < typename Action , typename T0 , typename T1 , typename T2 , typename T3 , typename T4 , typename T5 , typename T6 , typename T7 , typename T8 , typename A0 , typename A1 , typename A2 > bool apply( BOOST_RV_REF(HPX_UTIL_STRIP(( hpx::util::detail::bound_action9< Action , T0 , T1 , T2 , T3 , T4 , T5 , T6 , T7 , T8 >))) bound , BOOST_FWD_REF(A0) a0 , BOOST_FWD_REF(A1) a1 , BOOST_FWD_REF(A2) a2 ) { return bound.apply(boost::forward<A0>( a0 ) , boost::forward<A1>( a1 ) , boost::forward<A2>( a2 )); } template < typename Action , typename T0 , typename T1 , typename T2 , typename T3 , typename T4 , typename T5 , typename T6 , typename T7 , typename T8 , typename A0 , typename A1 , typename A2 , typename A3 > bool apply( BOOST_RV_REF(HPX_UTIL_STRIP(( hpx::util::detail::bound_action9< Action , T0 , T1 , T2 , T3 , T4 , T5 , T6 , T7 , T8 >))) bound , BOOST_FWD_REF(A0) a0 , BOOST_FWD_REF(A1) a1 , BOOST_FWD_REF(A2) a2 , BOOST_FWD_REF(A3) a3 ) { return bound.apply(boost::forward<A0>( a0 ) , boost::forward<A1>( a1 ) , boost::forward<A2>( a2 ) , boost::forward<A3>( a3 )); } template < typename Action , typename T0 , typename T1 , typename T2 , typename T3 , typename T4 , typename T5 , typename T6 , typename T7 , typename T8 , typename A0 , typename A1 , typename A2 , typename A3 , typename A4 > bool apply( BOOST_RV_REF(HPX_UTIL_STRIP(( hpx::util::detail::bound_action9< Action , T0 , T1 , T2 , T3 , T4 , T5 , T6 , T7 , T8 >))) bound , BOOST_FWD_REF(A0) a0 , BOOST_FWD_REF(A1) a1 , BOOST_FWD_REF(A2) a2 , BOOST_FWD_REF(A3) a3 , BOOST_FWD_REF(A4) a4 ) { return bound.apply(boost::forward<A0>( a0 ) , boost::forward<A1>( a1 ) , boost::forward<A2>( a2 ) , boost::forward<A3>( a3 ) , boost::forward<A4>( a4 )); } template < typename Action , typename T0 , typename T1 , typename T2 , typename T3 , typename T4 , typename T5 , typename T6 , typename T7 , typename T8 , typename A0 , typename A1 , typename A2 , typename A3 , typename A4 , typename A5 > bool apply( BOOST_RV_REF(HPX_UTIL_STRIP(( hpx::util::detail::bound_action9< Action , T0 , T1 , T2 , T3 , T4 , T5 , T6 , T7 , T8 >))) bound , BOOST_FWD_REF(A0) a0 , BOOST_FWD_REF(A1) a1 , BOOST_FWD_REF(A2) a2 , BOOST_FWD_REF(A3) a3 , BOOST_FWD_REF(A4) a4 , BOOST_FWD_REF(A5) a5 ) { return bound.apply(boost::forward<A0>( a0 ) , boost::forward<A1>( a1 ) , boost::forward<A2>( a2 ) , boost::forward<A3>( a3 ) , boost::forward<A4>( a4 ) , boost::forward<A5>( a5 )); } template < typename Action , typename T0 , typename T1 , typename T2 , typename T3 , typename T4 , typename T5 , typename T6 , typename T7 , typename T8 , typename A0 , typename A1 , typename A2 , typename A3 , typename A4 , typename A5 , typename A6 > bool apply( BOOST_RV_REF(HPX_UTIL_STRIP(( hpx::util::detail::bound_action9< Action , T0 , T1 , T2 , T3 , T4 , T5 , T6 , T7 , T8 >))) bound , BOOST_FWD_REF(A0) a0 , BOOST_FWD_REF(A1) a1 , BOOST_FWD_REF(A2) a2 , BOOST_FWD_REF(A3) a3 , BOOST_FWD_REF(A4) a4 , BOOST_FWD_REF(A5) a5 , BOOST_FWD_REF(A6) a6 ) { return bound.apply(boost::forward<A0>( a0 ) , boost::forward<A1>( a1 ) , boost::forward<A2>( a2 ) , boost::forward<A3>( a3 ) , boost::forward<A4>( a4 ) , boost::forward<A5>( a5 ) , boost::forward<A6>( a6 )); } template < typename Action , typename T0 , typename T1 , typename T2 , typename T3 , typename T4 , typename T5 , typename T6 , typename T7 , typename T8 , typename A0 , typename A1 , typename A2 , typename A3 , typename A4 , typename A5 , typename A6 , typename A7 > bool apply( BOOST_RV_REF(HPX_UTIL_STRIP(( hpx::util::detail::bound_action9< Action , T0 , T1 , T2 , T3 , T4 , T5 , T6 , T7 , T8 >))) bound , BOOST_FWD_REF(A0) a0 , BOOST_FWD_REF(A1) a1 , BOOST_FWD_REF(A2) a2 , BOOST_FWD_REF(A3) a3 , BOOST_FWD_REF(A4) a4 , BOOST_FWD_REF(A5) a5 , BOOST_FWD_REF(A6) a6 , BOOST_FWD_REF(A7) a7 ) { return bound.apply(boost::forward<A0>( a0 ) , boost::forward<A1>( a1 ) , boost::forward<A2>( a2 ) , boost::forward<A3>( a3 ) , boost::forward<A4>( a4 ) , boost::forward<A5>( a5 ) , boost::forward<A6>( a6 ) , boost::forward<A7>( a7 )); } template < typename Action , typename T0 , typename T1 , typename T2 , typename T3 , typename T4 , typename T5 , typename T6 , typename T7 , typename T8 , typename A0 , typename A1 , typename A2 , typename A3 , typename A4 , typename A5 , typename A6 , typename A7 , typename A8 > bool apply( BOOST_RV_REF(HPX_UTIL_STRIP(( hpx::util::detail::bound_action9< Action , T0 , T1 , T2 , T3 , T4 , T5 , T6 , T7 , T8 >))) bound , BOOST_FWD_REF(A0) a0 , BOOST_FWD_REF(A1) a1 , BOOST_FWD_REF(A2) a2 , BOOST_FWD_REF(A3) a3 , BOOST_FWD_REF(A4) a4 , BOOST_FWD_REF(A5) a5 , BOOST_FWD_REF(A6) a6 , BOOST_FWD_REF(A7) a7 , BOOST_FWD_REF(A8) a8 ) { return bound.apply(boost::forward<A0>( a0 ) , boost::forward<A1>( a1 ) , boost::forward<A2>( a2 ) , boost::forward<A3>( a3 ) , boost::forward<A4>( a4 ) , boost::forward<A5>( a5 ) , boost::forward<A6>( a6 ) , boost::forward<A7>( a7 ) , boost::forward<A8>( a8 )); } template < typename Action , typename T0 , typename T1 , typename T2 , typename T3 , typename T4 , typename T5 , typename T6 , typename T7 , typename T8 , typename A0 , typename A1 , typename A2 , typename A3 , typename A4 , typename A5 , typename A6 , typename A7 , typename A8 , typename A9 > bool apply( BOOST_RV_REF(HPX_UTIL_STRIP(( hpx::util::detail::bound_action9< Action , T0 , T1 , T2 , T3 , T4 , T5 , T6 , T7 , T8 >))) bound , BOOST_FWD_REF(A0) a0 , BOOST_FWD_REF(A1) a1 , BOOST_FWD_REF(A2) a2 , BOOST_FWD_REF(A3) a3 , BOOST_FWD_REF(A4) a4 , BOOST_FWD_REF(A5) a5 , BOOST_FWD_REF(A6) a6 , BOOST_FWD_REF(A7) a7 , BOOST_FWD_REF(A8) a8 , BOOST_FWD_REF(A9) a9 ) { return bound.apply(boost::forward<A0>( a0 ) , boost::forward<A1>( a1 ) , boost::forward<A2>( a2 ) , boost::forward<A3>( a3 ) , boost::forward<A4>( a4 ) , boost::forward<A5>( a5 ) , boost::forward<A6>( a6 ) , boost::forward<A7>( a7 ) , boost::forward<A8>( a8 ) , boost::forward<A9>( a9 )); } template < typename Action , typename T0 , typename T1 , typename T2 , typename T3 , typename T4 , typename T5 , typename T6 , typename T7 , typename T8 , typename A0 , typename A1 , typename A2 , typename A3 , typename A4 , typename A5 , typename A6 , typename A7 , typename A8 , typename A9 , typename A10 > bool apply( BOOST_RV_REF(HPX_UTIL_STRIP(( hpx::util::detail::bound_action9< Action , T0 , T1 , T2 , T3 , T4 , T5 , T6 , T7 , T8 >))) bound , BOOST_FWD_REF(A0) a0 , BOOST_FWD_REF(A1) a1 , BOOST_FWD_REF(A2) a2 , BOOST_FWD_REF(A3) a3 , BOOST_FWD_REF(A4) a4 , BOOST_FWD_REF(A5) a5 , BOOST_FWD_REF(A6) a6 , BOOST_FWD_REF(A7) a7 , BOOST_FWD_REF(A8) a8 , BOOST_FWD_REF(A9) a9 , BOOST_FWD_REF(A10) a10 ) { return bound.apply(boost::forward<A0>( a0 ) , boost::forward<A1>( a1 ) , boost::forward<A2>( a2 ) , boost::forward<A3>( a3 ) , boost::forward<A4>( a4 ) , boost::forward<A5>( a5 ) , boost::forward<A6>( a6 ) , boost::forward<A7>( a7 ) , boost::forward<A8>( a8 ) , boost::forward<A9>( a9 ) , boost::forward<A10>( a10 )); } template < typename Action , typename T0 , typename T1 , typename T2 , typename T3 , typename T4 , typename T5 , typename T6 , typename T7 , typename T8 , typename A0 , typename A1 , typename A2 , typename A3 , typename A4 , typename A5 , typename A6 , typename A7 , typename A8 , typename A9 , typename A10 , typename A11 > bool apply( BOOST_RV_REF(HPX_UTIL_STRIP(( hpx::util::detail::bound_action9< Action , T0 , T1 , T2 , T3 , T4 , T5 , T6 , T7 , T8 >))) bound , BOOST_FWD_REF(A0) a0 , BOOST_FWD_REF(A1) a1 , BOOST_FWD_REF(A2) a2 , BOOST_FWD_REF(A3) a3 , BOOST_FWD_REF(A4) a4 , BOOST_FWD_REF(A5) a5 , BOOST_FWD_REF(A6) a6 , BOOST_FWD_REF(A7) a7 , BOOST_FWD_REF(A8) a8 , BOOST_FWD_REF(A9) a9 , BOOST_FWD_REF(A10) a10 , BOOST_FWD_REF(A11) a11 ) { return bound.apply(boost::forward<A0>( a0 ) , boost::forward<A1>( a1 ) , boost::forward<A2>( a2 ) , boost::forward<A3>( a3 ) , boost::forward<A4>( a4 ) , boost::forward<A5>( a5 ) , boost::forward<A6>( a6 ) , boost::forward<A7>( a7 ) , boost::forward<A8>( a8 ) , boost::forward<A9>( a9 ) , boost::forward<A10>( a10 ) , boost::forward<A11>( a11 )); }
}
namespace hpx
{
template <
typename Action
, typename T0 , typename T1 , typename T2 , typename T3 , typename T4 , typename T5 , typename T6 , typename T7 , typename T8 , typename T9
>
bool apply(
BOOST_RV_REF(HPX_UTIL_STRIP((
hpx::util::detail::bound_action10<
Action
, T0 , T1 , T2 , T3 , T4 , T5 , T6 , T7 , T8 , T9
>))) bound)
{
return bound.apply();
}
template < typename Action , typename T0 , typename T1 , typename T2 , typename T3 , typename T4 , typename T5 , typename T6 , typename T7 , typename T8 , typename T9 , typename A0 > bool apply( BOOST_RV_REF(HPX_UTIL_STRIP(( hpx::util::detail::bound_action10< Action , T0 , T1 , T2 , T3 , T4 , T5 , T6 , T7 , T8 , T9 >))) bound , BOOST_FWD_REF(A0) a0 ) { return bound.apply(boost::forward<A0>( a0 )); } template < typename Action , typename T0 , typename T1 , typename T2 , typename T3 , typename T4 , typename T5 , typename T6 , typename T7 , typename T8 , typename T9 , typename A0 , typename A1 > bool apply( BOOST_RV_REF(HPX_UTIL_STRIP(( hpx::util::detail::bound_action10< Action , T0 , T1 , T2 , T3 , T4 , T5 , T6 , T7 , T8 , T9 >))) bound , BOOST_FWD_REF(A0) a0 , BOOST_FWD_REF(A1) a1 ) { return bound.apply(boost::forward<A0>( a0 ) , boost::forward<A1>( a1 )); } template < typename Action , typename T0 , typename T1 , typename T2 , typename T3 , typename T4 , typename T5 , typename T6 , typename T7 , typename T8 , typename T9 , typename A0 , typename A1 , typename A2 > bool apply( BOOST_RV_REF(HPX_UTIL_STRIP(( hpx::util::detail::bound_action10< Action , T0 , T1 , T2 , T3 , T4 , T5 , T6 , T7 , T8 , T9 >))) bound , BOOST_FWD_REF(A0) a0 , BOOST_FWD_REF(A1) a1 , BOOST_FWD_REF(A2) a2 ) { return bound.apply(boost::forward<A0>( a0 ) , boost::forward<A1>( a1 ) , boost::forward<A2>( a2 )); } template < typename Action , typename T0 , typename T1 , typename T2 , typename T3 , typename T4 , typename T5 , typename T6 , typename T7 , typename T8 , typename T9 , typename A0 , typename A1 , typename A2 , typename A3 > bool apply( BOOST_RV_REF(HPX_UTIL_STRIP(( hpx::util::detail::bound_action10< Action , T0 , T1 , T2 , T3 , T4 , T5 , T6 , T7 , T8 , T9 >))) bound , BOOST_FWD_REF(A0) a0 , BOOST_FWD_REF(A1) a1 , BOOST_FWD_REF(A2) a2 , BOOST_FWD_REF(A3) a3 ) { return bound.apply(boost::forward<A0>( a0 ) , boost::forward<A1>( a1 ) , boost::forward<A2>( a2 ) , boost::forward<A3>( a3 )); } template < typename Action , typename T0 , typename T1 , typename T2 , typename T3 , typename T4 , typename T5 , typename T6 , typename T7 , typename T8 , typename T9 , typename A0 , typename A1 , typename A2 , typename A3 , typename A4 > bool apply( BOOST_RV_REF(HPX_UTIL_STRIP(( hpx::util::detail::bound_action10< Action , T0 , T1 , T2 , T3 , T4 , T5 , T6 , T7 , T8 , T9 >))) bound , BOOST_FWD_REF(A0) a0 , BOOST_FWD_REF(A1) a1 , BOOST_FWD_REF(A2) a2 , BOOST_FWD_REF(A3) a3 , BOOST_FWD_REF(A4) a4 ) { return bound.apply(boost::forward<A0>( a0 ) , boost::forward<A1>( a1 ) , boost::forward<A2>( a2 ) , boost::forward<A3>( a3 ) , boost::forward<A4>( a4 )); } template < typename Action , typename T0 , typename T1 , typename T2 , typename T3 , typename T4 , typename T5 , typename T6 , typename T7 , typename T8 , typename T9 , typename A0 , typename A1 , typename A2 , typename A3 , typename A4 , typename A5 > bool apply( BOOST_RV_REF(HPX_UTIL_STRIP(( hpx::util::detail::bound_action10< Action , T0 , T1 , T2 , T3 , T4 , T5 , T6 , T7 , T8 , T9 >))) bound , BOOST_FWD_REF(A0) a0 , BOOST_FWD_REF(A1) a1 , BOOST_FWD_REF(A2) a2 , BOOST_FWD_REF(A3) a3 , BOOST_FWD_REF(A4) a4 , BOOST_FWD_REF(A5) a5 ) { return bound.apply(boost::forward<A0>( a0 ) , boost::forward<A1>( a1 ) , boost::forward<A2>( a2 ) , boost::forward<A3>( a3 ) , boost::forward<A4>( a4 ) , boost::forward<A5>( a5 )); } template < typename Action , typename T0 , typename T1 , typename T2 , typename T3 , typename T4 , typename T5 , typename T6 , typename T7 , typename T8 , typename T9 , typename A0 , typename A1 , typename A2 , typename A3 , typename A4 , typename A5 , typename A6 > bool apply( BOOST_RV_REF(HPX_UTIL_STRIP(( hpx::util::detail::bound_action10< Action , T0 , T1 , T2 , T3 , T4 , T5 , T6 , T7 , T8 , T9 >))) bound , BOOST_FWD_REF(A0) a0 , BOOST_FWD_REF(A1) a1 , BOOST_FWD_REF(A2) a2 , BOOST_FWD_REF(A3) a3 , BOOST_FWD_REF(A4) a4 , BOOST_FWD_REF(A5) a5 , BOOST_FWD_REF(A6) a6 ) { return bound.apply(boost::forward<A0>( a0 ) , boost::forward<A1>( a1 ) , boost::forward<A2>( a2 ) , boost::forward<A3>( a3 ) , boost::forward<A4>( a4 ) , boost::forward<A5>( a5 ) , boost::forward<A6>( a6 )); } template < typename Action , typename T0 , typename T1 , typename T2 , typename T3 , typename T4 , typename T5 , typename T6 , typename T7 , typename T8 , typename T9 , typename A0 , typename A1 , typename A2 , typename A3 , typename A4 , typename A5 , typename A6 , typename A7 > bool apply( BOOST_RV_REF(HPX_UTIL_STRIP(( hpx::util::detail::bound_action10< Action , T0 , T1 , T2 , T3 , T4 , T5 , T6 , T7 , T8 , T9 >))) bound , BOOST_FWD_REF(A0) a0 , BOOST_FWD_REF(A1) a1 , BOOST_FWD_REF(A2) a2 , BOOST_FWD_REF(A3) a3 , BOOST_FWD_REF(A4) a4 , BOOST_FWD_REF(A5) a5 , BOOST_FWD_REF(A6) a6 , BOOST_FWD_REF(A7) a7 ) { return bound.apply(boost::forward<A0>( a0 ) , boost::forward<A1>( a1 ) , boost::forward<A2>( a2 ) , boost::forward<A3>( a3 ) , boost::forward<A4>( a4 ) , boost::forward<A5>( a5 ) , boost::forward<A6>( a6 ) , boost::forward<A7>( a7 )); } template < typename Action , typename T0 , typename T1 , typename T2 , typename T3 , typename T4 , typename T5 , typename T6 , typename T7 , typename T8 , typename T9 , typename A0 , typename A1 , typename A2 , typename A3 , typename A4 , typename A5 , typename A6 , typename A7 , typename A8 > bool apply( BOOST_RV_REF(HPX_UTIL_STRIP(( hpx::util::detail::bound_action10< Action , T0 , T1 , T2 , T3 , T4 , T5 , T6 , T7 , T8 , T9 >))) bound , BOOST_FWD_REF(A0) a0 , BOOST_FWD_REF(A1) a1 , BOOST_FWD_REF(A2) a2 , BOOST_FWD_REF(A3) a3 , BOOST_FWD_REF(A4) a4 , BOOST_FWD_REF(A5) a5 , BOOST_FWD_REF(A6) a6 , BOOST_FWD_REF(A7) a7 , BOOST_FWD_REF(A8) a8 ) { return bound.apply(boost::forward<A0>( a0 ) , boost::forward<A1>( a1 ) , boost::forward<A2>( a2 ) , boost::forward<A3>( a3 ) , boost::forward<A4>( a4 ) , boost::forward<A5>( a5 ) , boost::forward<A6>( a6 ) , boost::forward<A7>( a7 ) , boost::forward<A8>( a8 )); } template < typename Action , typename T0 , typename T1 , typename T2 , typename T3 , typename T4 , typename T5 , typename T6 , typename T7 , typename T8 , typename T9 , typename A0 , typename A1 , typename A2 , typename A3 , typename A4 , typename A5 , typename A6 , typename A7 , typename A8 , typename A9 > bool apply( BOOST_RV_REF(HPX_UTIL_STRIP(( hpx::util::detail::bound_action10< Action , T0 , T1 , T2 , T3 , T4 , T5 , T6 , T7 , T8 , T9 >))) bound , BOOST_FWD_REF(A0) a0 , BOOST_FWD_REF(A1) a1 , BOOST_FWD_REF(A2) a2 , BOOST_FWD_REF(A3) a3 , BOOST_FWD_REF(A4) a4 , BOOST_FWD_REF(A5) a5 , BOOST_FWD_REF(A6) a6 , BOOST_FWD_REF(A7) a7 , BOOST_FWD_REF(A8) a8 , BOOST_FWD_REF(A9) a9 ) { return bound.apply(boost::forward<A0>( a0 ) , boost::forward<A1>( a1 ) , boost::forward<A2>( a2 ) , boost::forward<A3>( a3 ) , boost::forward<A4>( a4 ) , boost::forward<A5>( a5 ) , boost::forward<A6>( a6 ) , boost::forward<A7>( a7 ) , boost::forward<A8>( a8 ) , boost::forward<A9>( a9 )); } template < typename Action , typename T0 , typename T1 , typename T2 , typename T3 , typename T4 , typename T5 , typename T6 , typename T7 , typename T8 , typename T9 , typename A0 , typename A1 , typename A2 , typename A3 , typename A4 , typename A5 , typename A6 , typename A7 , typename A8 , typename A9 , typename A10 > bool apply( BOOST_RV_REF(HPX_UTIL_STRIP(( hpx::util::detail::bound_action10< Action , T0 , T1 , T2 , T3 , T4 , T5 , T6 , T7 , T8 , T9 >))) bound , BOOST_FWD_REF(A0) a0 , BOOST_FWD_REF(A1) a1 , BOOST_FWD_REF(A2) a2 , BOOST_FWD_REF(A3) a3 , BOOST_FWD_REF(A4) a4 , BOOST_FWD_REF(A5) a5 , BOOST_FWD_REF(A6) a6 , BOOST_FWD_REF(A7) a7 , BOOST_FWD_REF(A8) a8 , BOOST_FWD_REF(A9) a9 , BOOST_FWD_REF(A10) a10 ) { return bound.apply(boost::forward<A0>( a0 ) , boost::forward<A1>( a1 ) , boost::forward<A2>( a2 ) , boost::forward<A3>( a3 ) , boost::forward<A4>( a4 ) , boost::forward<A5>( a5 ) , boost::forward<A6>( a6 ) , boost::forward<A7>( a7 ) , boost::forward<A8>( a8 ) , boost::forward<A9>( a9 ) , boost::forward<A10>( a10 )); } template < typename Action , typename T0 , typename T1 , typename T2 , typename T3 , typename T4 , typename T5 , typename T6 , typename T7 , typename T8 , typename T9 , typename A0 , typename A1 , typename A2 , typename A3 , typename A4 , typename A5 , typename A6 , typename A7 , typename A8 , typename A9 , typename A10 , typename A11 > bool apply( BOOST_RV_REF(HPX_UTIL_STRIP(( hpx::util::detail::bound_action10< Action , T0 , T1 , T2 , T3 , T4 , T5 , T6 , T7 , T8 , T9 >))) bound , BOOST_FWD_REF(A0) a0 , BOOST_FWD_REF(A1) a1 , BOOST_FWD_REF(A2) a2 , BOOST_FWD_REF(A3) a3 , BOOST_FWD_REF(A4) a4 , BOOST_FWD_REF(A5) a5 , BOOST_FWD_REF(A6) a6 , BOOST_FWD_REF(A7) a7 , BOOST_FWD_REF(A8) a8 , BOOST_FWD_REF(A9) a9 , BOOST_FWD_REF(A10) a10 , BOOST_FWD_REF(A11) a11 ) { return bound.apply(boost::forward<A0>( a0 ) , boost::forward<A1>( a1 ) , boost::forward<A2>( a2 ) , boost::forward<A3>( a3 ) , boost::forward<A4>( a4 ) , boost::forward<A5>( a5 ) , boost::forward<A6>( a6 ) , boost::forward<A7>( a7 ) , boost::forward<A8>( a8 ) , boost::forward<A9>( a9 ) , boost::forward<A10>( a10 ) , boost::forward<A11>( a11 )); }
}
| 451.137931 | 19,599 | 0.678849 | andreasbuhr |
95589cd23a24a500ce6e8b4060128928696eedb6 | 89,701 | cpp | C++ | RotateIt/exiv2/src/basicio.cpp | Vitalii17/RotateIt | 621089c334e740b99bc7686d5724b79655adfbad | [
"MIT"
] | 1 | 2017-02-10T16:39:32.000Z | 2017-02-10T16:39:32.000Z | RotateIt/exiv2/src/basicio.cpp | vitalii17/RotateIt | 621089c334e740b99bc7686d5724b79655adfbad | [
"MIT"
] | null | null | null | RotateIt/exiv2/src/basicio.cpp | vitalii17/RotateIt | 621089c334e740b99bc7686d5724b79655adfbad | [
"MIT"
] | null | null | null | // ***************************************************************** -*- C++ -*-
/*
* Copyright (C) 2004-2017 Andreas Huggel <[email protected]>
*
* This program is part of the Exiv2 distribution.
*
* 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, 5th Floor, Boston, MA 02110-1301 USA.
*/
/*
File: basicio.cpp
Version: $Rev$
*/
// *****************************************************************************
#include "rcsid_int.hpp"
EXIV2_RCSID("@(#) $Id$")
// included header files
#include "config.h"
#include "datasets.hpp"
#include "basicio.hpp"
#include "futils.hpp"
#include "types.hpp"
#include "error.hpp"
#include "http.hpp"
#include "properties.hpp"
// + standard includes
#include <string>
#include <memory>
#include <iostream>
#include <cstring>
#include <cassert>
#include <cstdio> // for remove, rename
#include <cstdlib> // for alloc, realloc, free
#include <sys/types.h> // for stat, chmod
#include <sys/stat.h> // for stat, chmod
#ifdef EXV_HAVE_SYS_MMAN_H
# include <sys/mman.h> // for mmap and munmap
#endif
#ifdef EXV_HAVE_PROCESS_H
# include <process.h>
#endif
#ifdef EXV_HAVE_UNISTD_H
# include <unistd.h> // for getpid, stat
#endif
#if EXV_USE_CURL == 1
#include <curl/curl.h>
#endif
#if EXV_USE_SSH == 1
#include "ssh.hpp"
#else
#define mode_t unsigned short
#endif
// Platform specific headers for handling extended attributes (xattr)
#if defined(__APPLE__)
# include <sys/xattr.h>
#endif
#if defined(__MINGW__) || (defined(WIN32) && !defined(__CYGWIN))
// Windows doesn't provide nlink_t
typedef short nlink_t;
# include <windows.h>
# include <io.h>
#endif
// *****************************************************************************
// class member definitions
namespace Exiv2 {
BasicIo::~BasicIo()
{
}
//! Internal Pimpl structure of class FileIo.
class FileIo::Impl {
public:
//! Constructor
Impl(const std::string& path);
#ifdef EXV_UNICODE_PATH
//! Constructor accepting a unicode path in an std::wstring
Impl(const std::wstring& wpath);
#endif
// Enumerations
//! Mode of operation
enum OpMode { opRead, opWrite, opSeek };
#ifdef EXV_UNICODE_PATH
//! Used to indicate if the path is stored as a standard or unicode string
enum WpMode { wpStandard, wpUnicode };
#endif
// DATA
std::string path_; //!< (Standard) path
#ifdef EXV_UNICODE_PATH
std::wstring wpath_; //!< Unicode path
WpMode wpMode_; //!< Indicates which path is in use
#endif
std::string openMode_; //!< File open mode
FILE *fp_; //!< File stream pointer
OpMode opMode_; //!< File open mode
#if defined WIN32 && !defined __CYGWIN__
HANDLE hFile_; //!< Duplicated fd
HANDLE hMap_; //!< Handle from CreateFileMapping
#endif
byte* pMappedArea_; //!< Pointer to the memory-mapped area
size_t mappedLength_; //!< Size of the memory-mapped area
bool isMalloced_; //!< Is the mapped area allocated?
bool isWriteable_; //!< Can the mapped area be written to?
// TYPES
//! Simple struct stat wrapper for internal use
struct StructStat {
StructStat() : st_mode(0), st_size(0), st_nlink(0) {}
mode_t st_mode; //!< Permissions
off_t st_size; //!< Size
nlink_t st_nlink; //!< Number of hard links (broken on Windows, see winNumberOfLinks())
};
// #endif
// METHODS
/*!
@brief Switch to a new access mode, reopening the file if needed.
Optimized to only reopen the file when it is really necessary.
@param opMode The mode to switch to.
@return 0 if successful
*/
int switchMode(OpMode opMode);
//! stat wrapper for internal use
int stat(StructStat& buf) const;
//! copy extended attributes (xattr) from another file
void copyXattrFrom(const FileIo& src);
#if defined WIN32 && !defined __CYGWIN__
// Windows function to determine the number of hardlinks (on NTFS)
DWORD winNumberOfLinks() const;
#endif
private:
// NOT IMPLEMENTED
Impl(const Impl& rhs); //!< Copy constructor
Impl& operator=(const Impl& rhs); //!< Assignment
}; // class FileIo::Impl
FileIo::Impl::Impl(const std::string& path)
: path_(path),
#ifdef EXV_UNICODE_PATH
wpMode_(wpStandard),
#endif
fp_(0), opMode_(opSeek),
#if defined WIN32 && !defined __CYGWIN__
hFile_(0), hMap_(0),
#endif
pMappedArea_(0), mappedLength_(0), isMalloced_(false), isWriteable_(false)
{
}
#ifdef EXV_UNICODE_PATH
FileIo::Impl::Impl(const std::wstring& wpath)
: wpath_(wpath),
wpMode_(wpUnicode),
fp_(0), opMode_(opSeek),
#if defined WIN32 && !defined __CYGWIN__
hFile_(0), hMap_(0),
#endif
pMappedArea_(0), mappedLength_(0), isMalloced_(false), isWriteable_(false)
{
}
#endif
int FileIo::Impl::switchMode(OpMode opMode)
{
assert(fp_ != 0);
if (opMode_ == opMode) return 0;
OpMode oldOpMode = opMode_;
opMode_ = opMode;
bool reopen = true;
switch(opMode) {
case opRead:
// Flush if current mode allows reading, else reopen (in mode "r+b"
// as in this case we know that we can write to the file)
if (openMode_[0] == 'r' || openMode_[1] == '+') reopen = false;
break;
case opWrite:
// Flush if current mode allows writing, else reopen
if (openMode_[0] != 'r' || openMode_[1] == '+') reopen = false;
break;
case opSeek:
reopen = false;
break;
}
if (!reopen) {
// Don't do anything when switching _from_ opSeek mode; we
// flush when switching _to_ opSeek.
if (oldOpMode == opSeek) return 0;
// Flush. On msvcrt fflush does not do the job
std::fseek(fp_, 0, SEEK_CUR);
return 0;
}
// Reopen the file
long offset = std::ftell(fp_);
if (offset == -1) return -1;
// 'Manual' open("r+b") to avoid munmap()
if (fp_ != 0) {
std::fclose(fp_);
fp_= 0;
}
openMode_ = "r+b";
opMode_ = opSeek;
#ifdef EXV_UNICODE_PATH
if (wpMode_ == wpUnicode) {
fp_ = ::_wfopen(wpath_.c_str(), s2ws(openMode_).c_str());
}
else
#endif
{
fp_ = std::fopen(path_.c_str(), openMode_.c_str());
}
if (!fp_) return 1;
return std::fseek(fp_, offset, SEEK_SET);
} // FileIo::Impl::switchMode
int FileIo::Impl::stat(StructStat& buf) const
{
int ret = 0;
#ifdef EXV_UNICODE_PATH
#ifdef _WIN64
struct _stat64 st;
ret = ::_wstati64(wpath_.c_str(), &st);
if (0 == ret) {
buf.st_size = st.st_size;
buf.st_mode = st.st_mode;
buf.st_nlink = st.st_nlink;
}
#else
struct _stat st;
ret = ::_wstat(wpath_.c_str(), &st);
if (0 == ret) {
buf.st_size = st.st_size;
buf.st_mode = st.st_mode;
buf.st_nlink = st.st_nlink;
}
#endif
else
#endif
{
struct stat st;
ret = ::stat(path_.c_str(), &st);
if (0 == ret) {
buf.st_size = st.st_size;
buf.st_nlink = st.st_nlink;
buf.st_mode = st.st_mode;
}
}
return ret;
} // FileIo::Impl::stat
#if defined(__APPLE__)
void FileIo::Impl::copyXattrFrom(const FileIo& src)
#else
void FileIo::Impl::copyXattrFrom(const FileIo&)
#endif
{
#if defined(__APPLE__)
# if defined(EXV_UNICODE_PATH)
# error No xattr API for MacOS X with unicode support
# endif
ssize_t namebufSize = ::listxattr(src.p_->path_.c_str(), 0, 0, 0);
if (namebufSize < 0) {
throw Error(2, src.p_->path_, strError(), "listxattr");
}
if (namebufSize == 0) {
// No extended attributes in source file
return;
}
char* namebuf = new char[namebufSize];
if (::listxattr(src.p_->path_.c_str(), namebuf, namebufSize, 0) != namebufSize) {
throw Error(2, src.p_->path_, strError(), "listxattr");
}
for (ssize_t namebufPos = 0; namebufPos < namebufSize;) {
const char *name = namebuf + namebufPos;
namebufPos += strlen(name) + 1;
const ssize_t valueSize = ::getxattr(src.p_->path_.c_str(), name, 0, 0, 0, 0);
if (valueSize < 0) {
throw Error(2, src.p_->path_, strError(), "getxattr");
}
char* value = new char[valueSize];
if (::getxattr(src.p_->path_.c_str(), name, value, valueSize, 0, 0) != valueSize) {
throw Error(2, src.p_->path_, strError(), "getxattr");
}
// #906. Mountain Lion 'sandbox' terminates the app when we call setxattr
#ifndef __APPLE__
#ifdef DEBUG
EXV_DEBUG << "Copying xattr \"" << name << "\" with value size " << valueSize << "\n";
#endif
if (::setxattr(path_.c_str(), name, value, valueSize, 0, 0) != 0) {
throw Error(2, path_, strError(), "setxattr");
}
delete [] value;
#endif
}
delete [] namebuf;
#else
// No xattr support for this platform.
#endif
} // FileIo::Impl::copyXattrFrom
#if defined WIN32 && !defined __CYGWIN__
DWORD FileIo::Impl::winNumberOfLinks() const
{
DWORD nlink = 1;
HANDLE hFd = (HANDLE)_get_osfhandle(fileno(fp_));
if (hFd != INVALID_HANDLE_VALUE) {
typedef BOOL (WINAPI * GetFileInformationByHandle_t)(HANDLE, LPBY_HANDLE_FILE_INFORMATION);
HMODULE hKernel = ::GetModuleHandleA("kernel32.dll");
if (hKernel) {
GetFileInformationByHandle_t pfcn_GetFileInformationByHandle = (GetFileInformationByHandle_t)GetProcAddress(hKernel, "GetFileInformationByHandle");
if (pfcn_GetFileInformationByHandle) {
BY_HANDLE_FILE_INFORMATION fi = {0,0,0,0,0,0,0,0,0,0,0,0,0};
if (pfcn_GetFileInformationByHandle(hFd, &fi)) {
nlink = fi.nNumberOfLinks;
}
#ifdef DEBUG
else EXV_DEBUG << "GetFileInformationByHandle failed\n";
#endif
}
#ifdef DEBUG
else EXV_DEBUG << "GetProcAddress(hKernel, \"GetFileInformationByHandle\") failed\n";
#endif
}
#ifdef DEBUG
else EXV_DEBUG << "GetModuleHandleA(\"kernel32.dll\") failed\n";
#endif
}
#ifdef DEBUG
else EXV_DEBUG << "_get_osfhandle failed: INVALID_HANDLE_VALUE\n";
#endif
return nlink;
} // FileIo::Impl::winNumberOfLinks
#endif // defined WIN32 && !defined __CYGWIN__
FileIo::FileIo(const std::string& path)
: p_(new Impl(path))
{
}
#ifdef EXV_UNICODE_PATH
FileIo::FileIo(const std::wstring& wpath)
: p_(new Impl(wpath))
{
}
#endif
FileIo::~FileIo()
{
close();
delete p_;
}
int FileIo::munmap()
{
int rc = 0;
if (p_->pMappedArea_ != 0) {
#if defined EXV_HAVE_MMAP && defined EXV_HAVE_MUNMAP
if (::munmap(p_->pMappedArea_, p_->mappedLength_) != 0) {
rc = 1;
}
#elif defined WIN32 && !defined __CYGWIN__
UnmapViewOfFile(p_->pMappedArea_);
CloseHandle(p_->hMap_);
p_->hMap_ = 0;
CloseHandle(p_->hFile_);
p_->hFile_ = 0;
#else
if (p_->isWriteable_) {
seek(0, BasicIo::beg);
write(p_->pMappedArea_, p_->mappedLength_);
}
if (p_->isMalloced_) {
delete[] p_->pMappedArea_;
p_->isMalloced_ = false;
}
#endif
}
if (p_->isWriteable_) {
if (p_->fp_ != 0) p_->switchMode(Impl::opRead);
p_->isWriteable_ = false;
}
p_->pMappedArea_ = 0;
p_->mappedLength_ = 0;
return rc;
}
byte* FileIo::mmap(bool isWriteable)
{
assert(p_->fp_ != 0);
if (munmap() != 0) {
#ifdef EXV_UNICODE_PATH
if (p_->wpMode_ == Impl::wpUnicode) {
throw WError(2, wpath(), strError().c_str(), "munmap");
}
else
#endif
{
throw Error(2, path(), strError(), "munmap");
}
}
p_->mappedLength_ = size();
p_->isWriteable_ = isWriteable;
if (p_->isWriteable_ && p_->switchMode(Impl::opWrite) != 0) {
#ifdef EXV_UNICODE_PATH
if (p_->wpMode_ == Impl::wpUnicode) {
throw WError(16, wpath(), strError().c_str());
}
else
#endif
{
throw Error(16, path(), strError());
}
}
#if defined EXV_HAVE_MMAP && defined EXV_HAVE_MUNMAP
int prot = PROT_READ;
if (p_->isWriteable_) {
prot |= PROT_WRITE;
}
void* rc = ::mmap(0, p_->mappedLength_, prot, MAP_SHARED, fileno(p_->fp_), 0);
if (MAP_FAILED == rc) {
#ifdef EXV_UNICODE_PATH
if (p_->wpMode_ == Impl::wpUnicode) {
throw WError(2, wpath(), strError().c_str(), "mmap");
}
else
#endif
{
throw Error(2, path(), strError(), "mmap");
}
}
p_->pMappedArea_ = static_cast<byte*>(rc);
#elif defined WIN32 && !defined __CYGWIN__
// Windows implementation
// TODO: An attempt to map a file with a length of 0 (zero) fails with
// an error code of ERROR_FILE_INVALID.
// Applications should test for files with a length of 0 (zero) and
// reject those files.
DWORD dwAccess = FILE_MAP_READ;
DWORD flProtect = PAGE_READONLY;
if (isWriteable) {
dwAccess = FILE_MAP_WRITE;
flProtect = PAGE_READWRITE;
}
HANDLE hPh = GetCurrentProcess();
HANDLE hFd = (HANDLE)_get_osfhandle(fileno(p_->fp_));
if (hFd == INVALID_HANDLE_VALUE) {
#ifdef EXV_UNICODE_PATH
if (p_->wpMode_ == Impl::wpUnicode) {
throw WError(2, wpath(), "MSG1", "_get_osfhandle");
}
else
#endif
{
throw Error(2, path(), "MSG1", "_get_osfhandle");
}
}
if (!DuplicateHandle(hPh, hFd, hPh, &p_->hFile_, 0, false, DUPLICATE_SAME_ACCESS)) {
#ifdef EXV_UNICODE_PATH
if (p_->wpMode_ == Impl::wpUnicode) {
throw WError(2, wpath(), "MSG2", "DuplicateHandle");
}
else
#endif
{
throw Error(2, path(), "MSG2", "DuplicateHandle");
}
}
p_->hMap_ = CreateFileMapping(p_->hFile_, 0, flProtect, 0, (DWORD) p_->mappedLength_, 0);
if (p_->hMap_ == 0 ) {
#ifdef EXV_UNICODE_PATH
if (p_->wpMode_ == Impl::wpUnicode) {
throw WError(2, wpath(), "MSG3", "CreateFileMapping");
}
else
#endif
{
throw Error(2, path(), "MSG3", "CreateFileMapping");
}
}
void* rc = MapViewOfFile(p_->hMap_, dwAccess, 0, 0, 0);
if (rc == 0) {
#ifdef EXV_UNICODE_PATH
if (p_->wpMode_ == Impl::wpUnicode) {
throw WError(2, wpath(), "MSG4", "CreateFileMapping");
}
else
#endif
{
throw Error(2, path(), "MSG4", "CreateFileMapping");
}
}
p_->pMappedArea_ = static_cast<byte*>(rc);
#else
// Workaround for platforms without mmap: Read the file into memory
DataBuf buf(static_cast<long>(p_->mappedLength_));
if (read(buf.pData_, buf.size_) != buf.size_) {
#ifdef EXV_UNICODE_PATH
if (p_->wpMode_ == Impl::wpUnicode) {
throw WError(2, wpath(), strError().c_str(), "FileIo::read");
}
else
#endif
{
throw Error(2, path(), strError(), "FileIo::read");
}
}
if (error()) {
#ifdef EXV_UNICODE_PATH
if (p_->wpMode_ == Impl::wpUnicode) {
throw WError(2, wpath(), strError().c_str(), "FileIo::mmap");
}
else
#endif
{
throw Error(2, path(), strError(), "FileIo::mmap");
}
}
p_->pMappedArea_ = buf.release().first;
p_->isMalloced_ = true;
#endif
return p_->pMappedArea_;
}
void FileIo::setPath(const std::string& path) {
close();
#ifdef EXV_UNICODE_PATH
if (p_->wpMode_ == Impl::wpUnicode) {
std::wstring wpath;
wpath.assign(path.begin(), path.end());
p_->wpath_ = wpath;
}
p_->path_ = path;
#else
p_->path_ = path;
#endif
}
#ifdef EXV_UNICODE_PATH
void FileIo::setPath(const std::wstring& wpath) {
close();
if (p_->wpMode_ == Impl::wpStandard) {
std::string path;
path.assign(wpath.begin(), wpath.end());
p_->path_ = path;
} else {
p_->wpath_ = wpath;
}
}
#endif
long FileIo::write(const byte* data, long wcount)
{
assert(p_->fp_ != 0);
if (p_->switchMode(Impl::opWrite) != 0) return 0;
return (long)std::fwrite(data, 1, wcount, p_->fp_);
}
long FileIo::write(BasicIo& src)
{
assert(p_->fp_ != 0);
if (static_cast<BasicIo*>(this) == &src) return 0;
if (!src.isopen()) return 0;
if (p_->switchMode(Impl::opWrite) != 0) return 0;
byte buf[4096];
long readCount = 0;
long writeCount = 0;
long writeTotal = 0;
while ((readCount = src.read(buf, sizeof(buf)))) {
writeTotal += writeCount = (long)std::fwrite(buf, 1, readCount, p_->fp_);
if (writeCount != readCount) {
// try to reset back to where write stopped
src.seek(writeCount-readCount, BasicIo::cur);
break;
}
}
return writeTotal;
}
void FileIo::transfer(BasicIo& src)
{
const bool wasOpen = (p_->fp_ != 0);
const std::string lastMode(p_->openMode_);
FileIo *fileIo = dynamic_cast<FileIo*>(&src);
if (fileIo) {
// Optimization if src is another instance of FileIo
fileIo->close();
// Check if the file can be written to, if it already exists
if (open("a+b") != 0) {
// Remove the (temporary) file
#ifdef EXV_UNICODE_PATH
if (fileIo->p_->wpMode_ == Impl::wpUnicode) {
::_wremove(fileIo->wpath().c_str());
}
else
#endif
{
::remove(fileIo->path().c_str());
}
#ifdef EXV_UNICODE_PATH
if (p_->wpMode_ == Impl::wpUnicode) {
throw WError(10, wpath(), "a+b", strError().c_str());
}
else
#endif
{
throw Error(10, path(), "a+b", strError());
}
}
close();
bool statOk = true;
mode_t origStMode = 0;
std::string spf;
char* pf = 0;
#ifdef EXV_UNICODE_PATH
std::wstring wspf;
wchar_t* wpf = 0;
if (p_->wpMode_ == Impl::wpUnicode) {
wspf = wpath();
wpf = const_cast<wchar_t*>(wspf.c_str());
}
else
#endif
{
spf = path();
pf = const_cast<char*>(spf.c_str());
}
// Get the permissions of the file, or linked-to file, on platforms which have lstat
#ifdef EXV_HAVE_LSTAT
# ifdef EXV_UNICODE_PATH
# error EXV_UNICODE_PATH and EXV_HAVE_LSTAT are not compatible. Stop.
# endif
struct stat buf1;
if (::lstat(pf, &buf1) == -1) {
statOk = false;
#ifndef SUPPRESS_WARNINGS
EXV_WARNING << Error(2, pf, strError(), "::lstat") << "\n";
#endif
}
origStMode = buf1.st_mode;
DataBuf lbuf; // So that the allocated memory is freed. Must have same scope as pf
// In case path() is a symlink, get the path of the linked-to file
if (statOk && S_ISLNK(buf1.st_mode)) {
lbuf.alloc(buf1.st_size + 1);
memset(lbuf.pData_, 0x0, lbuf.size_);
pf = reinterpret_cast<char*>(lbuf.pData_);
if (::readlink(path().c_str(), pf, lbuf.size_ - 1) == -1) {
throw Error(2, path(), strError(), "readlink");
}
// We need the permissions of the file, not the symlink
if (::stat(pf, &buf1) == -1) {
statOk = false;
#ifndef SUPPRESS_WARNINGS
EXV_WARNING << Error(2, pf, strError(), "::stat") << "\n";
#endif
}
origStMode = buf1.st_mode;
}
#else // EXV_HAVE_LSTAT
Impl::StructStat buf1;
if (p_->stat(buf1) == -1) {
statOk = false;
}
origStMode = buf1.st_mode;
#endif // !EXV_HAVE_LSTAT
// MSVCRT rename that does not overwrite existing files
#ifdef EXV_UNICODE_PATH
if (p_->wpMode_ == Impl::wpUnicode) {
#if defined(WIN32) && defined(REPLACEFILE_IGNORE_MERGE_ERRORS)
// Windows implementation that deals with the fact that ::rename fails
// if the target filename still exists, which regularly happens when
// that file has been opened with FILE_SHARE_DELETE by another process,
// like a virus scanner or disk indexer
// (see also http://stackoverflow.com/a/11023068)
typedef BOOL (WINAPI * ReplaceFileW_t)(LPCWSTR, LPCWSTR, LPCWSTR, DWORD, LPVOID, LPVOID);
HMODULE hKernel = ::GetModuleHandleA("kernel32.dll");
if (hKernel) {
ReplaceFileW_t pfcn_ReplaceFileW = (ReplaceFileW_t)GetProcAddress(hKernel, "ReplaceFileW");
if (pfcn_ReplaceFileW) {
BOOL ret = pfcn_ReplaceFileW(wpf, fileIo->wpath().c_str(), NULL, REPLACEFILE_IGNORE_MERGE_ERRORS, NULL, NULL);
if (ret == 0) {
if (GetLastError() == ERROR_FILE_NOT_FOUND) {
if (::_wrename(fileIo->wpath().c_str(), wpf) == -1) {
throw WError(17, fileIo->wpath(), wpf, strError().c_str());
}
::_wremove(fileIo->wpath().c_str());
}
else {
throw WError(17, fileIo->wpath(), wpf, strError().c_str());
}
}
}
else {
if (fileExists(wpf) && ::_wremove(wpf) != 0) {
throw WError(2, wpf, strError().c_str(), "::_wremove");
}
if (::_wrename(fileIo->wpath().c_str(), wpf) == -1) {
throw WError(17, fileIo->wpath(), wpf, strError().c_str());
}
::_wremove(fileIo->wpath().c_str());
}
}
#else
if (fileExists(wpf) && ::_wremove(wpf) != 0) {
throw WError(2, wpf, strError().c_str(), "::_wremove");
}
if (::_wrename(fileIo->wpath().c_str(), wpf) == -1) {
throw WError(17, fileIo->wpath(), wpf, strError().c_str());
}
::_wremove(fileIo->wpath().c_str());
#endif
// Check permissions of new file
struct _stat buf2;
if (statOk && ::_wstat(wpf, &buf2) == -1) {
statOk = false;
#ifndef SUPPRESS_WARNINGS
EXV_WARNING << Error(2, wpf, strError(), "::_wstat") << "\n";
#endif
}
if (statOk && origStMode != buf2.st_mode) {
// Set original file permissions
if (::_wchmod(wpf, origStMode) == -1) {
#ifndef SUPPRESS_WARNINGS
EXV_WARNING << Error(2, wpf, strError(), "::_wchmod") << "\n";
#endif
}
}
} // if (p_->wpMode_ == Impl::wpUnicode)
else
#endif // EXV_UNICODE_PATH
{
#if defined(WIN32) && defined(REPLACEFILE_IGNORE_MERGE_ERRORS)
// Windows implementation that deals with the fact that ::rename fails
// if the target filename still exists, which regularly happens when
// that file has been opened with FILE_SHARE_DELETE by another process,
// like a virus scanner or disk indexer
// (see also http://stackoverflow.com/a/11023068)
typedef BOOL (WINAPI * ReplaceFileA_t)(LPCSTR, LPCSTR, LPCSTR, DWORD, LPVOID, LPVOID);
HMODULE hKernel = ::GetModuleHandleA("kernel32.dll");
if (hKernel) {
ReplaceFileA_t pfcn_ReplaceFileA = (ReplaceFileA_t)GetProcAddress(hKernel, "ReplaceFileA");
if (pfcn_ReplaceFileA) {
BOOL ret = pfcn_ReplaceFileA(pf, fileIo->path().c_str(), NULL, REPLACEFILE_IGNORE_MERGE_ERRORS, NULL, NULL);
if (ret == 0) {
if (GetLastError() == ERROR_FILE_NOT_FOUND) {
if (::rename(fileIo->path().c_str(), pf) == -1) {
throw Error(17, fileIo->path(), pf, strError());
}
::remove(fileIo->path().c_str());
}
else {
throw Error(17, fileIo->path(), pf, strError());
}
}
}
else {
if (fileExists(pf) && ::remove(pf) != 0) {
throw Error(2, pf, strError(), "::remove");
}
if (::rename(fileIo->path().c_str(), pf) == -1) {
throw Error(17, fileIo->path(), pf, strError());
}
::remove(fileIo->path().c_str());
}
}
#else
if (fileExists(pf) && ::remove(pf) != 0) {
throw Error(2, pf, strError(), "::remove");
}
if (::rename(fileIo->path().c_str(), pf) == -1) {
throw Error(17, fileIo->path(), pf, strError());
}
::remove(fileIo->path().c_str());
#endif
// Check permissions of new file
struct stat buf2;
if (statOk && ::stat(pf, &buf2) == -1) {
statOk = false;
#ifndef SUPPRESS_WARNINGS
EXV_WARNING << Error(2, pf, strError(), "::stat") << "\n";
#endif
}
if (statOk && origStMode != buf2.st_mode) {
// Set original file permissions
if (::chmod(pf, origStMode) == -1) {
#ifndef SUPPRESS_WARNINGS
EXV_WARNING << Error(2, pf, strError(), "::chmod") << "\n";
#endif
}
}
}
} // if (fileIo)
else {
// Generic handling, reopen both to reset to start
if (open("w+b") != 0) {
#ifdef EXV_UNICODE_PATH
if (p_->wpMode_ == Impl::wpUnicode) {
throw WError(10, wpath(), "w+b", strError().c_str());
}
else
#endif
{
throw Error(10, path(), "w+b", strError());
}
}
if (src.open() != 0) {
#ifdef EXV_UNICODE_PATH
if (p_->wpMode_ == Impl::wpUnicode) {
throw WError(9, src.wpath(), strError().c_str());
}
else
#endif
{
throw Error(9, src.path(), strError());
}
}
write(src);
src.close();
}
if (wasOpen) {
if (open(lastMode) != 0) {
#ifdef EXV_UNICODE_PATH
if (p_->wpMode_ == Impl::wpUnicode) {
throw WError(10, wpath(), lastMode.c_str(), strError().c_str());
}
else
#endif
{
throw Error(10, path(), lastMode, strError());
}
}
}
else close();
if (error() || src.error()) {
#ifdef EXV_UNICODE_PATH
if (p_->wpMode_ == Impl::wpUnicode) {
throw WError(18, wpath(), strError().c_str());
}
else
#endif
{
throw Error(18, path(), strError());
}
}
} // FileIo::transfer
int FileIo::putb(byte data)
{
assert(p_->fp_ != 0);
if (p_->switchMode(Impl::opWrite) != 0) return EOF;
return putc(data, p_->fp_);
}
#if defined(_MSC_VER)
int FileIo::seek( int64_t offset, Position pos )
{
assert(p_->fp_ != 0);
int fileSeek = 0;
switch (pos) {
case BasicIo::cur: fileSeek = SEEK_CUR; break;
case BasicIo::beg: fileSeek = SEEK_SET; break;
case BasicIo::end: fileSeek = SEEK_END; break;
}
if (p_->switchMode(Impl::opSeek) != 0) return 1;
#ifdef _WIN64
return _fseeki64(p_->fp_, offset, fileSeek);
#else
return std::fseek(p_->fp_,static_cast<long>(offset), fileSeek);
#endif
}
#else
int FileIo::seek(long offset, Position pos)
{
assert(p_->fp_ != 0);
int fileSeek = 0;
switch (pos) {
case BasicIo::cur: fileSeek = SEEK_CUR; break;
case BasicIo::beg: fileSeek = SEEK_SET; break;
case BasicIo::end: fileSeek = SEEK_END; break;
}
if (p_->switchMode(Impl::opSeek) != 0) return 1;
return std::fseek(p_->fp_, offset, fileSeek);
}
#endif
long FileIo::tell() const
{
assert(p_->fp_ != 0);
return std::ftell(p_->fp_);
}
size_t FileIo::size() const
{
// Flush and commit only if the file is open for writing
if (p_->fp_ != 0 && (p_->openMode_[0] != 'r' || p_->openMode_[1] == '+')) {
std::fflush(p_->fp_);
#if defined WIN32 && !defined __CYGWIN__
// This is required on msvcrt before stat after writing to a file
_commit(_fileno(p_->fp_));
#endif
}
Impl::StructStat buf;
int ret = p_->stat(buf);
if (ret != 0) return -1;
return buf.st_size;
}
int FileIo::open()
{
// Default open is in read-only binary mode
return open("rb");
}
int FileIo::open(const std::string& mode)
{
close();
p_->openMode_ = mode;
p_->opMode_ = Impl::opSeek;
#ifdef EXV_UNICODE_PATH
if (p_->wpMode_ == Impl::wpUnicode) {
p_->fp_ = ::_wfopen(wpath().c_str(), s2ws(mode).c_str());
}
else
#endif
{
p_->fp_ = ::fopen(path().c_str(), mode.c_str());
}
if (!p_->fp_) return 1;
return 0;
}
bool FileIo::isopen() const
{
return p_->fp_ != 0;
}
int FileIo::close()
{
int rc = 0;
if (munmap() != 0) rc = 2;
if (p_->fp_ != 0) {
if (std::fclose(p_->fp_) != 0) rc |= 1;
p_->fp_= 0;
}
return rc;
}
DataBuf FileIo::read(long rcount)
{
assert(p_->fp_ != 0);
DataBuf buf(rcount);
long readCount = read(buf.pData_, buf.size_);
buf.size_ = readCount;
return buf;
}
long FileIo::read(byte* buf, long rcount)
{
assert(p_->fp_ != 0);
if (p_->switchMode(Impl::opRead) != 0) return 0;
return (long)std::fread(buf, 1, rcount, p_->fp_);
}
int FileIo::getb()
{
assert(p_->fp_ != 0);
if (p_->switchMode(Impl::opRead) != 0) return EOF;
return getc(p_->fp_);
}
int FileIo::error() const
{
return p_->fp_ != 0 ? ferror(p_->fp_) : 0;
}
bool FileIo::eof() const
{
assert(p_->fp_ != 0);
return feof(p_->fp_) != 0 || tell() >= (long) size() ;
}
std::string FileIo::path() const
{
#ifdef EXV_UNICODE_PATH
if (p_->wpMode_ == Impl::wpUnicode) {
return ws2s(p_->wpath_);
}
#endif
return p_->path_;
}
#ifdef EXV_UNICODE_PATH
std::wstring FileIo::wpath() const
{
if (p_->wpMode_ == Impl::wpStandard) {
return s2ws(p_->path_);
}
return p_->wpath_;
}
#endif
void FileIo::populateFakeData() {
}
//! Internal Pimpl structure of class MemIo.
class MemIo::Impl {
public:
Impl(); //!< Default constructor
Impl(const byte* data, long size); //!< Constructor 2
// DATA
byte* data_; //!< Pointer to the start of the memory area
long idx_; //!< Index into the memory area
long size_; //!< Size of the memory area
long sizeAlloced_; //!< Size of the allocated buffer
bool isMalloced_; //!< Was the buffer allocated?
bool eof_; //!< EOF indicator
// METHODS
void reserve(long wcount); //!< Reserve memory
private:
// NOT IMPLEMENTED
Impl(const Impl& rhs); //!< Copy constructor
Impl& operator=(const Impl& rhs); //!< Assignment
}; // class MemIo::Impl
MemIo::Impl::Impl()
: data_(0),
idx_(0),
size_(0),
sizeAlloced_(0),
isMalloced_(false),
eof_(false)
{
}
MemIo::Impl::Impl(const byte* data, long size)
: data_(const_cast<byte*>(data)),
idx_(0),
size_(size),
sizeAlloced_(0),
isMalloced_(false),
eof_(false)
{
}
void MemIo::Impl::reserve(long wcount)
{
long need = wcount + idx_;
if (!isMalloced_) {
// Minimum size for 1st block is 32kB
long size = EXV_MAX(32768 * (1 + need / 32768), size_);
byte* data = (byte*)std::malloc(size);
std::memcpy(data, data_, size_);
data_ = data;
sizeAlloced_ = size;
isMalloced_ = true;
}
if (need > size_) {
if (need > sizeAlloced_) {
// Allocate in blocks of 32kB
long want = 32768 * (1 + need / 32768);
data_ = (byte*)std::realloc(data_, want);
sizeAlloced_ = want;
isMalloced_ = true;
}
size_ = need;
}
}
MemIo::MemIo()
: p_(new Impl())
{
}
MemIo::MemIo(const byte* data, long size)
: p_(new Impl(data, size))
{
}
MemIo::~MemIo()
{
if (p_->isMalloced_) {
std::free(p_->data_);
}
delete p_;
}
long MemIo::write(const byte* data, long wcount)
{
p_->reserve(wcount);
assert(p_->isMalloced_);
std::memcpy(&p_->data_[p_->idx_], data, wcount);
p_->idx_ += wcount;
return wcount;
}
void MemIo::transfer(BasicIo& src)
{
MemIo *memIo = dynamic_cast<MemIo*>(&src);
if (memIo) {
// Optimization if src is another instance of MemIo
if (p_->isMalloced_) {
std::free(p_->data_);
}
p_->idx_ = 0;
p_->data_ = memIo->p_->data_;
p_->size_ = memIo->p_->size_;
p_->isMalloced_ = memIo->p_->isMalloced_;
memIo->p_->idx_ = 0;
memIo->p_->data_ = 0;
memIo->p_->size_ = 0;
memIo->p_->isMalloced_ = false;
}
else {
// Generic reopen to reset position to start
if (src.open() != 0) {
throw Error(9, src.path(), strError());
}
p_->idx_ = 0;
write(src);
src.close();
}
if (error() || src.error()) throw Error(19, strError());
}
long MemIo::write(BasicIo& src)
{
if (static_cast<BasicIo*>(this) == &src) return 0;
if (!src.isopen()) return 0;
byte buf[4096];
long readCount = 0;
long writeTotal = 0;
while ((readCount = src.read(buf, sizeof(buf)))) {
write(buf, readCount);
writeTotal += readCount;
}
return writeTotal;
}
int MemIo::putb(byte data)
{
p_->reserve(1);
assert(p_->isMalloced_);
p_->data_[p_->idx_++] = data;
return data;
}
#if defined(_MSC_VER)
int MemIo::seek( int64_t offset, Position pos )
{
uint64_t newIdx = 0;
switch (pos) {
case BasicIo::cur: newIdx = p_->idx_ + offset; break;
case BasicIo::beg: newIdx = offset; break;
case BasicIo::end: newIdx = p_->size_ + offset; break;
}
p_->idx_ = static_cast<long>(newIdx); //not very sure about this. need more test!! - note by Shawn [email protected] //TODO
p_->eof_ = false;
return 0;
}
#else
int MemIo::seek(long offset, Position pos)
{
long newIdx = 0;
switch (pos) {
case BasicIo::cur: newIdx = p_->idx_ + offset; break;
case BasicIo::beg: newIdx = offset; break;
case BasicIo::end: newIdx = p_->size_ + offset; break;
}
if (newIdx < 0) return 1;
p_->idx_ = newIdx;
p_->eof_ = false;
return 0;
}
#endif
byte* MemIo::mmap(bool /*isWriteable*/)
{
return p_->data_;
}
int MemIo::munmap()
{
return 0;
}
long MemIo::tell() const
{
return p_->idx_;
}
size_t MemIo::size() const
{
return p_->size_;
}
int MemIo::open()
{
p_->idx_ = 0;
p_->eof_ = false;
return 0;
}
bool MemIo::isopen() const
{
return true;
}
int MemIo::close()
{
return 0;
}
DataBuf MemIo::read(long rcount)
{
DataBuf buf(rcount);
long readCount = read(buf.pData_, buf.size_);
buf.size_ = readCount;
return buf;
}
long MemIo::read(byte* buf, long rcount)
{
long avail = EXV_MAX(p_->size_ - p_->idx_, 0);
long allow = EXV_MIN(rcount, avail);
std::memcpy(buf, &p_->data_[p_->idx_], allow);
p_->idx_ += allow;
if (rcount > avail) p_->eof_ = true;
return allow;
}
int MemIo::getb()
{
if (p_->idx_ >= p_->size_) {
p_->eof_ = true;
return EOF;
}
return p_->data_[p_->idx_++];
}
int MemIo::error() const
{
return 0;
}
bool MemIo::eof() const
{
return p_->eof_;
}
std::string MemIo::path() const
{
return "MemIo";
}
#ifdef EXV_UNICODE_PATH
std::wstring MemIo::wpath() const
{
return EXV_WIDEN("MemIo");
}
#endif
void MemIo::populateFakeData() {
}
#if EXV_XPATH_MEMIO
XPathIo::XPathIo(const std::string& path) {
Protocol prot = fileProtocol(path);
if (prot == pStdin) ReadStdin();
else if (prot == pDataUri) ReadDataUri(path);
}
#ifdef EXV_UNICODE_PATH
XPathIo::XPathIo(const std::wstring& wpath) {
std::string path;
path.assign(wpath.begin(), wpath.end());
Protocol prot = fileProtocol(path);
if (prot == pStdin) ReadStdin();
else if (prot == pDataUri) ReadDataUri(path);
}
#endif
void XPathIo::ReadStdin() {
if (isatty(fileno(stdin)))
throw Error(53);
#ifdef _O_BINARY
// convert stdin to binary
if (_setmode(_fileno(stdin), _O_BINARY) == -1)
throw Error(54);
#endif
char readBuf[100*1024];
std::streamsize readBufSize = 0;
do {
std::cin.read(readBuf, sizeof(readBuf));
readBufSize = std::cin.gcount();
if (readBufSize > 0) {
write((byte*)readBuf, (long)readBufSize);
}
} while(readBufSize);
}
void XPathIo::ReadDataUri(const std::string& path) {
size_t base64Pos = path.find("base64,");
if (base64Pos == std::string::npos)
throw Error(1, "No base64 data");
std::string data = path.substr(base64Pos+7);
char* decodeData = new char[data.length()];
long size = base64decode(data.c_str(), decodeData, data.length());
if (size > 0)
write((byte*)decodeData, size);
else
throw Error(1, "Unable to decode base 64.");
delete[] decodeData;
}
#else
const std::string XPathIo::TEMP_FILE_EXT = ".exiv2_temp";
const std::string XPathIo::GEN_FILE_EXT = ".exiv2";
XPathIo::XPathIo(const std::string& orgPath) : FileIo(XPathIo::writeDataToFile(orgPath)) {
isTemp_ = true;
tempFilePath_ = path();
}
#ifdef EXV_UNICODE_PATH
XPathIo::XPathIo(const std::wstring& wOrgPathpath) : FileIo(XPathIo::writeDataToFile(wOrgPathpath)) {
isTemp_ = true;
tempFilePath_ = path();
}
#endif
XPathIo::~XPathIo() {
if (isTemp_ && remove(tempFilePath_.c_str()) != 0) {
// error when removing file
// printf ("Warning: Unable to remove the temp file %s.\n", tempFilePath_.c_str());
}
}
void XPathIo::transfer(BasicIo& src) {
if (isTemp_) {
// replace temp path to gent path.
std::string currentPath = path();
setPath(ReplaceStringInPlace(currentPath, XPathIo::TEMP_FILE_EXT, XPathIo::GEN_FILE_EXT));
// rename the file
tempFilePath_ = path();
if (rename(currentPath.c_str(), tempFilePath_.c_str()) != 0) {
// printf("Warning: Failed to rename the temp file. \n");
}
isTemp_ = false;
// call super class method
FileIo::transfer(src);
}
}
std::string XPathIo::writeDataToFile(const std::string& orgPath) {
Protocol prot = fileProtocol(orgPath);
// generating the name for temp file.
std::time_t timestamp = std::time(NULL);
std::stringstream ss;
ss << timestamp << XPathIo::TEMP_FILE_EXT;
std::string path = ss.str();
std::ofstream fs(path.c_str(), std::ios::out | std::ios::binary | std::ios::trunc);
if (prot == pStdin) {
if (isatty(fileno(stdin)))
throw Error(53);
#if defined(_MSC_VER) || defined(__MINGW__)
// convert stdin to binary
if (_setmode(_fileno(stdin), _O_BINARY) == -1)
throw Error(54);
#endif
// read stdin and write to the temp file.
char readBuf[100*1024];
std::streamsize readBufSize = 0;
do {
std::cin.read(readBuf, sizeof(readBuf));
readBufSize = std::cin.gcount();
if (readBufSize > 0) {
fs.write (readBuf, readBufSize);
}
} while(readBufSize);
} else if (prot == pDataUri) {
// read data uri and write to the temp file.
size_t base64Pos = orgPath.find("base64,");
if (base64Pos == std::string::npos)
throw Error(1, "No base64 data");
std::string data = orgPath.substr(base64Pos+7);
char* decodeData = new char[data.length()];
long size = base64decode(data.c_str(), decodeData, data.length());
if (size > 0)
fs.write(decodeData, size);
else
throw Error(1, "Unable to decode base 64.");
delete[] decodeData;
}
fs.close();
return path;
}
#ifdef EXV_UNICODE_PATH
std::string XPathIo::writeDataToFile(const std::wstring& wOrgPath) {
std::string orgPath;
orgPath.assign(wOrgPath.begin(), wOrgPath.end());
return XPathIo::writeDataToFile(orgPath);
}
#endif
#endif
//! Internal Pimpl abstract structure of class RemoteIo.
class RemoteIo::Impl {
public:
//! Constructor
Impl(const std::string& path, size_t blockSize);
#ifdef EXV_UNICODE_PATH
//! Constructor accepting a unicode path in an std::wstring
Impl(const std::wstring& wpath, size_t blockSize);
#endif
//! Destructor. Releases all managed memory.
virtual ~Impl();
// DATA
std::string path_; //!< (Standard) path
#ifdef EXV_UNICODE_PATH
std::wstring wpath_; //!< Unicode path
#endif
size_t blockSize_; //!< Size of the block memory.
BlockMap* blocksMap_; //!< An array contains all blocksMap
size_t size_; //!< The file size
long idx_; //!< Index into the memory area
bool isMalloced_; //!< Was the blocksMap_ allocated?
bool eof_; //!< EOF indicator
Protocol protocol_; //!< the protocol of url
uint32_t totalRead_; //!< bytes requested from host
// METHODS
/*!
@brief Get the length (in bytes) of the remote file.
@return Return -1 if the size is unknown. Otherwise it returns the length of remote file (in bytes).
@throw Error if the server returns the error code.
*/
virtual long getFileLength() = 0;
/*!
@brief Get the data by range.
@param lowBlock The start block index.
@param highBlock The end block index.
@param response The data from the server.
@throw Error if the server returns the error code.
@note Set lowBlock = -1 and highBlock = -1 to get the whole file content.
*/
virtual void getDataByRange(long lowBlock, long highBlock, std::string& response) = 0;
/*!
@brief Submit the data to the remote machine. The data replace a part of the remote file.
The replaced part of remote file is indicated by from and to parameters.
@param data The data are submitted to the remote machine.
@param size The size of data.
@param from The start position in the remote file where the data replace.
@param to The end position in the remote file where the data replace.
@note The write access is available on some protocols. HTTP and HTTPS require the script file
on the remote machine to handle the data. SSH requires the permission to edit the file.
@throw Error if it fails.
*/
virtual void writeRemote(const byte* data, size_t size, long from, long to) = 0;
/*!
@brief Get the data from the remote machine and write them to the memory blocks.
@param lowBlock The start block index.
@param highBlock The end block index.
@return Number of bytes written to the memory block successfully
@throw Error if it fails.
*/
virtual size_t populateBlocks(size_t lowBlock, size_t highBlock);
}; // class RemoteIo::Impl
RemoteIo::Impl::Impl(const std::string& url, size_t blockSize)
: path_(url), blockSize_(blockSize), blocksMap_(0), size_(0),
idx_(0), isMalloced_(false), eof_(false), protocol_(fileProtocol(url)),totalRead_(0)
{
}
#ifdef EXV_UNICODE_PATH
RemoteIo::Impl::Impl(const std::wstring& wurl, size_t blockSize)
: wpath_(wurl), blockSize_(blockSize), blocksMap_(0), size_(0),
idx_(0), isMalloced_(false), eof_(false), protocol_(fileProtocol(wurl))
{
}
#endif
size_t RemoteIo::Impl::populateBlocks(size_t lowBlock, size_t highBlock)
{
assert(isMalloced_);
// optimize: ignore all true blocks on left & right sides.
while(!blocksMap_[lowBlock].isNone() && lowBlock < highBlock) lowBlock++;
while(!blocksMap_[highBlock].isNone() && highBlock > lowBlock) highBlock--;
size_t rcount = 0;
if (blocksMap_[highBlock].isNone())
{
std::string data;
getDataByRange( (long) lowBlock, (long) highBlock, data);
rcount = (size_t)data.length();
if (rcount == 0) {
throw Error(1, "Data By Range is empty. Please check the permission.");
}
byte* source = (byte*)data.c_str();
size_t remain = rcount, totalRead = 0;
size_t iBlock = (rcount == size_) ? 0 : lowBlock;
while (remain) {
size_t allow = EXV_MIN(remain, blockSize_);
blocksMap_[iBlock].populate(&source[totalRead], allow);
remain -= allow;
totalRead += allow;
iBlock++;
}
}
return rcount;
}
RemoteIo::Impl::~Impl() {
if (blocksMap_) delete[] blocksMap_;
}
RemoteIo::~RemoteIo()
{
if (p_) {
close();
delete p_;
}
}
int RemoteIo::open()
{
close(); // reset the IO position
bigBlock_ = NULL;
if (p_->isMalloced_ == false) {
long length = p_->getFileLength();
if (length < 0) { // unable to get the length of remote file, get the whole file content.
std::string data;
p_->getDataByRange(-1, -1, data);
p_->size_ = (size_t) data.length();
size_t nBlocks = (p_->size_ + p_->blockSize_ - 1) / p_->blockSize_;
p_->blocksMap_ = new BlockMap[nBlocks];
p_->isMalloced_ = true;
byte* source = (byte*)data.c_str();
size_t remain = p_->size_, iBlock = 0, totalRead = 0;
while (remain) {
size_t allow = EXV_MIN(remain, p_->blockSize_);
p_->blocksMap_[iBlock].populate(&source[totalRead], allow);
remain -= allow;
totalRead += allow;
iBlock++;
}
} else if (length == 0) { // file is empty
throw Error(1, "the file length is 0");
} else {
p_->size_ = (size_t) length;
size_t nBlocks = (p_->size_ + p_->blockSize_ - 1) / p_->blockSize_;
p_->blocksMap_ = new BlockMap[nBlocks];
p_->isMalloced_ = true;
}
}
return 0; // means OK
}
int RemoteIo::close()
{
if (p_->isMalloced_) {
p_->eof_ = false;
p_->idx_ = 0;
}
#ifdef DEBUG
std::cerr << "RemoteIo::close totalRead_ = " << p_->totalRead_ << std::endl;
#endif
if ( bigBlock_ ) {
delete [] bigBlock_;
bigBlock_=NULL;
}
return 0;
}
long RemoteIo::write(const byte* /* unused data*/, long /* unused wcount*/)
{
return 0; // means failure
}
long RemoteIo::write(BasicIo& src)
{
assert(p_->isMalloced_);
if (!src.isopen()) return 0;
/*
* The idea is to compare the file content, find the different bytes and submit them to the remote machine.
* To simplify it, it:
* + goes from the left, find the first different position -> $left
* + goes from the right, find the first different position -> $right
* The different bytes are [$left-$right] part.
*/
size_t left = 0;
size_t right = 0;
size_t blockIndex = 0;
size_t i = 0;
size_t readCount = 0;
size_t blockSize = 0;
byte* buf = (byte*) std::malloc(p_->blockSize_);
size_t nBlocks = (p_->size_ + p_->blockSize_ - 1) / p_->blockSize_;
// find $left
src.seek(0, BasicIo::beg);
bool findDiff = false;
while (blockIndex < nBlocks && !src.eof() && !findDiff) {
blockSize = p_->blocksMap_[blockIndex].getSize();
bool isFakeData = p_->blocksMap_[blockIndex].isKnown(); // fake data
readCount = src.read(buf, blockSize);
byte* blockData = p_->blocksMap_[blockIndex].getData();
for (i = 0; (i < readCount) && (i < blockSize) && !findDiff; i++) {
if ((!isFakeData && buf[i] != blockData[i]) || (isFakeData && buf[i] != 0)) {
findDiff = true;
} else {
left++;
}
}
blockIndex++;
}
// find $right
findDiff = false;
blockIndex = nBlocks - 1;
blockSize = p_->blocksMap_[blockIndex].getSize();
while ((blockIndex + 1 > 0) && right < src.size() && !findDiff) {
if(src.seek(-1 * (blockSize + right), BasicIo::end)) {
findDiff = true;
} else {
bool isFakeData = p_->blocksMap_[blockIndex].isKnown(); // fake data
readCount = src.read(buf, blockSize);
byte* blockData = p_->blocksMap_[blockIndex].getData();
for (i = 0; (i < readCount) && (i < blockSize) && !findDiff; i++) {
if ((!isFakeData && buf[readCount - i - 1] != blockData[blockSize - i - 1]) || (isFakeData && buf[readCount - i - 1] != 0)) {
findDiff = true;
} else {
right++;
}
}
}
blockIndex--;
blockSize = (long)p_->blocksMap_[blockIndex].getSize();
}
// free buf
if (buf) std::free(buf);
// submit to the remote machine.
long dataSize = src.size() - left - right;
if (dataSize > 0) {
byte* data = (byte*) std::malloc(dataSize);
src.seek(left, BasicIo::beg);
src.read(data, dataSize);
p_->writeRemote(data, (size_t)dataSize, left, (long) p_->size_ - right);
if (data) std::free(data);
}
return src.size();
}
int RemoteIo::putb(byte /*unused data*/)
{
return 0;
}
DataBuf RemoteIo::read(long rcount)
{
DataBuf buf(rcount);
long readCount = read(buf.pData_, buf.size_);
buf.size_ = readCount;
return buf;
}
long RemoteIo::read(byte* buf, long rcount)
{
assert(p_->isMalloced_);
if (p_->eof_) return 0;
p_->totalRead_ += rcount;
size_t allow = EXV_MIN(rcount, (long)( p_->size_ - p_->idx_));
size_t lowBlock = p_->idx_ /p_->blockSize_;
size_t highBlock = (p_->idx_ + allow)/p_->blockSize_;
// connect to the remote machine & populate the blocks just in time.
p_->populateBlocks(lowBlock, highBlock);
byte* fakeData = (byte*) std::calloc(p_->blockSize_, sizeof(byte));
if (!fakeData) {
throw Error(1, "Unable to allocate data");
}
size_t iBlock = lowBlock;
size_t startPos = p_->idx_ - lowBlock*p_->blockSize_;
size_t totalRead = 0;
do {
byte* data = p_->blocksMap_[iBlock++].getData();
if (data == NULL) data = fakeData;
size_t blockR = EXV_MIN(allow, p_->blockSize_ - startPos);
std::memcpy(&buf[totalRead], &data[startPos], blockR);
totalRead += blockR;
startPos = 0;
allow -= blockR;
} while(allow);
if (fakeData) std::free(fakeData);
p_->idx_ += (long) totalRead;
p_->eof_ = (p_->idx_ == (long) p_->size_);
return (long) totalRead;
}
int RemoteIo::getb()
{
assert(p_->isMalloced_);
if (p_->idx_ == (long)p_->size_) {
p_->eof_ = true;
return EOF;
}
size_t expectedBlock = (p_->idx_ + 1)/p_->blockSize_;
// connect to the remote machine & populate the blocks just in time.
p_->populateBlocks(expectedBlock, expectedBlock);
byte* data = p_->blocksMap_[expectedBlock].getData();
return data[p_->idx_++ - expectedBlock*p_->blockSize_];
}
void RemoteIo::transfer(BasicIo& src)
{
if (src.open() != 0) {
throw Error(1, "unable to open src when transferring");
}
write(src);
src.close();
}
#if defined(_MSC_VER)
int RemoteIo::seek( int64_t offset, Position pos )
{
assert(p_->isMalloced_);
uint64_t newIdx = 0;
switch (pos) {
case BasicIo::cur: newIdx = p_->idx_ + offset; break;
case BasicIo::beg: newIdx = offset; break;
case BasicIo::end: newIdx = p_->size_ + offset; break;
}
if ( /*newIdx < 0 || */ newIdx > static_cast<uint64_t>(p_->size_) ) return 1;
p_->idx_ = static_cast<long>(newIdx); //not very sure about this. need more test!! - note by Shawn [email protected] //TODO
p_->eof_ = false;
return 0;
}
#else
int RemoteIo::seek(long offset, Position pos)
{
assert(p_->isMalloced_);
long newIdx = 0;
switch (pos) {
case BasicIo::cur: newIdx = p_->idx_ + offset; break;
case BasicIo::beg: newIdx = offset; break;
case BasicIo::end: newIdx = p_->size_ + offset; break;
}
// #1198. Don't return 1 when asked to seek past EOF. Stay calm and set eof_
// if (newIdx < 0 || newIdx > (long) p_->size_) return 1;
p_->idx_ = newIdx;
p_->eof_ = newIdx > (long) p_->size_;
if ( p_->idx_ > (long) p_->size_ ) p_->idx_= (long) p_->size_;
return 0;
}
#endif
byte* RemoteIo::mmap(bool /*isWriteable*/)
{
size_t nRealData = 0 ;
if ( !bigBlock_ ) {
size_t blockSize = p_->blockSize_;
size_t blocks = (p_->size_ + blockSize -1)/blockSize ;
bigBlock_ = new byte[blocks*blockSize] ;
for ( size_t block = 0 ; block < blocks ; block ++ ) {
void* p = p_->blocksMap_[block].getData();
if ( p ) {
nRealData += blockSize ;
memcpy(bigBlock_+(block*blockSize),p,blockSize);
}
}
#ifdef DEBUG
std::cerr << "RemoteIo::mmap nRealData = " << nRealData << std::endl;
#endif
}
return bigBlock_;
}
int RemoteIo::munmap()
{
return 0;
}
long RemoteIo::tell() const
{
return p_->idx_;
}
size_t RemoteIo::size() const
{
return (long) p_->size_;
}
bool RemoteIo::isopen() const
{
return p_->isMalloced_;
}
int RemoteIo::error() const
{
return 0;
}
bool RemoteIo::eof() const
{
return p_->eof_;
}
std::string RemoteIo::path() const
{
return p_->path_;
}
#ifdef EXV_UNICODE_PATH
std::wstring RemoteIo::wpath() const
{
return p_->wpath_;
}
#endif
void RemoteIo::populateFakeData()
{
assert(p_->isMalloced_);
size_t nBlocks = (p_->size_ + p_->blockSize_ - 1) / p_->blockSize_;
for (size_t i = 0; i < nBlocks; i++) {
if (p_->blocksMap_[i].isNone())
p_->blocksMap_[i].markKnown(p_->blockSize_);
}
}
//! Internal Pimpl structure of class HttpIo.
class HttpIo::HttpImpl : public Impl {
public:
//! Constructor
HttpImpl(const std::string& path, size_t blockSize);
#ifdef EXV_UNICODE_PATH
//! Constructor accepting a unicode path in an std::wstring
HttpImpl(const std::wstring& wpath, size_t blockSize);
#endif
Exiv2::Uri hostInfo_; //!< the host information extracted from the path
// METHODS
/*!
@brief Get the length (in bytes) of the remote file.
@return Return -1 if the size is unknown. Otherwise it returns the length of remote file (in bytes).
@throw Error if the server returns the error code.
*/
long getFileLength();
/*!
@brief Get the data by range.
@param lowBlock The start block index.
@param highBlock The end block index.
@param response The data from the server.
@throw Error if the server returns the error code.
@note Set lowBlock = -1 and highBlock = -1 to get the whole file content.
*/
void getDataByRange(long lowBlock, long highBlock, std::string& response);
/*!
@brief Submit the data to the remote machine. The data replace a part of the remote file.
The replaced part of remote file is indicated by from and to parameters.
@param data The data are submitted to the remote machine.
@param size The size of data.
@param from The start position in the remote file where the data replace.
@param to The end position in the remote file where the data replace.
@note The data are submitted to the remote machine via POST. This requires the script file
on the remote machine to receive the data and edit the remote file. The server-side
script may be specified with the environment string EXIV2_HTTP_POST. The default value is
"/exiv2.php". More info is available at http://dev.exiv2.org/wiki/exiv2
@throw Error if it fails.
*/
void writeRemote(const byte* data, size_t size, long from, long to);
protected:
// NOT IMPLEMENTED
HttpImpl(const HttpImpl& rhs); //!< Copy constructor
HttpImpl& operator=(const HttpImpl& rhs); //!< Assignment
}; // class HttpIo::HttpImpl
HttpIo::HttpImpl::HttpImpl(const std::string& url, size_t blockSize):Impl(url, blockSize)
{
hostInfo_ = Exiv2::Uri::Parse(url);
Exiv2::Uri::Decode(hostInfo_);
}
#ifdef EXV_UNICODE_PATH
HttpIo::HttpImpl::HttpImpl(const std::wstring& wurl, size_t blockSize):Impl(wurl, blockSize)
{
std::string url;
url.assign(wurl.begin(), wurl.end());
path_ = url;
hostInfo_ = Exiv2::Uri::Parse(url);
Exiv2::Uri::Decode(hostInfo_);
}
#endif
long HttpIo::HttpImpl::getFileLength()
{
Exiv2::Dictionary response;
Exiv2::Dictionary request;
std::string errors;
request["server"] = hostInfo_.Host;
request["page" ] = hostInfo_.Path;
if (hostInfo_.Port != "") request["port"] = hostInfo_.Port;
request["verb"] = "HEAD";
long serverCode = (long)http(request, response, errors);
if (serverCode < 0 || serverCode >= 400 || errors.compare("") != 0) {
throw Error(55, "Server", serverCode);
}
Exiv2::Dictionary_i lengthIter = response.find("Content-Length");
return (lengthIter == response.end()) ? -1 : atol((lengthIter->second).c_str());
}
void HttpIo::HttpImpl::getDataByRange(long lowBlock, long highBlock, std::string& response)
{
Exiv2::Dictionary responseDic;
Exiv2::Dictionary request;
request["server"] = hostInfo_.Host;
request["page" ] = hostInfo_.Path;
if (hostInfo_.Port != "") request["port"] = hostInfo_.Port;
request["verb"] = "GET";
std::string errors;
if (lowBlock > -1 && highBlock > -1) {
std::stringstream ss;
ss << "Range: bytes=" << lowBlock * blockSize_ << "-" << ((highBlock + 1) * blockSize_ - 1) << "\r\n";
request["header"] = ss.str();
}
long serverCode = (long)http(request, responseDic, errors);
if (serverCode < 0 || serverCode >= 400 || errors.compare("") != 0) {
throw Error(55, "Server", serverCode);
}
response = responseDic["body"];
}
void HttpIo::HttpImpl::writeRemote(const byte* data, size_t size, long from, long to)
{
std::string scriptPath(getEnv(envHTTPPOST));
if (scriptPath == "") {
throw Error(1, "Please set the path of the server script to handle http post data to EXIV2_HTTP_POST environmental variable.");
}
// standadize the path without "/" at the beginning.
std::size_t protocolIndex = scriptPath.find("://");
if (protocolIndex == std::string::npos && scriptPath[0] != '/') {
scriptPath = "/" + scriptPath;
}
Exiv2::Dictionary response;
Exiv2::Dictionary request;
std::string errors;
Uri scriptUri = Exiv2::Uri::Parse(scriptPath);
request["server"] = scriptUri.Host == "" ? hostInfo_.Host : scriptUri.Host;
if (scriptUri.Port != "") request["port"] = scriptUri.Port;
request["page"] = scriptUri.Path;
request["verb"] = "POST";
// encode base64
size_t encodeLength = ((size + 2) / 3) * 4 + 1;
char* encodeData = new char[encodeLength];
base64encode(data, size, encodeData, encodeLength);
// url encode
char* urlencodeData = urlencode(encodeData);
delete[] encodeData;
std::stringstream ss;
ss << "path=" << hostInfo_.Path << "&"
<< "from=" << from << "&"
<< "to=" << to << "&"
<< "data=" << urlencodeData;
std::string postData = ss.str();
delete[] urlencodeData;
// create the header
ss.str("");
ss << "Content-Length: " << postData.length() << "\n"
<< "Content-Type: application/x-www-form-urlencoded\n"
<< "\n" << postData << "\r\n";
request["header"] = ss.str();
int serverCode = http(request, response, errors);
if (serverCode < 0 || serverCode >= 400 || errors.compare("") != 0) {
throw Error(55, "Server", serverCode);
}
}
HttpIo::HttpIo(const std::string& url, size_t blockSize)
{
p_ = new HttpImpl(url, blockSize);
}
#ifdef EXV_UNICODE_PATH
HttpIo::HttpIo(const std::wstring& wurl, size_t blockSize)
{
p_ = new HttpImpl(wurl, blockSize);
}
#endif
#if EXV_USE_CURL == 1
//! Internal Pimpl structure of class RemoteIo.
class CurlIo::CurlImpl : public Impl {
public:
//! Constructor
CurlImpl(const std::string& path, size_t blockSize);
#ifdef EXV_UNICODE_PATH
//! Constructor accepting a unicode path in an std::wstring
CurlImpl(const std::wstring& wpath, size_t blockSize);
#endif
//! Destructor. Cleans up the curl pointer and releases all managed memory.
~CurlImpl();
CURL* curl_; //!< libcurl pointer
// METHODS
/*!
@brief Get the length (in bytes) of the remote file.
@return Return -1 if the size is unknown. Otherwise it returns the length of remote file (in bytes).
@throw Error if the server returns the error code.
*/
long getFileLength();
/*!
@brief Get the data by range.
@param lowBlock The start block index.
@param highBlock The end block index.
@param response The data from the server.
@throw Error if the server returns the error code.
@note Set lowBlock = -1 and highBlock = -1 to get the whole file content.
*/
void getDataByRange(long lowBlock, long highBlock, std::string& response);
/*!
@brief Submit the data to the remote machine. The data replace a part of the remote file.
The replaced part of remote file is indicated by from and to parameters.
@param data The data are submitted to the remote machine.
@param size The size of data.
@param from The start position in the remote file where the data replace.
@param to The end position in the remote file where the data replace.
@throw Error if it fails.
@note The write access is only available on HTTP & HTTPS protocols. The data are submitted to server
via POST method. It requires the script file on the remote machine to receive the data
and edit the remote file. The server-side script may be specified with the environment
string EXIV2_HTTP_POST. The default value is "/exiv2.php". More info is available at
http://dev.exiv2.org/wiki/exiv2
*/
void writeRemote(const byte* data, size_t size, long from, long to);
protected:
// NOT IMPLEMENTED
CurlImpl(const CurlImpl& rhs); //!< Copy constructor
CurlImpl& operator=(const CurlImpl& rhs); //!< Assignment
private:
long timeout_; //!< The number of seconds to wait while trying to connect.
}; // class RemoteIo::Impl
CurlIo::CurlImpl::CurlImpl(const std::string& url, size_t blockSize):Impl(url, blockSize)
{
// init curl pointer
curl_ = curl_easy_init();
if(!curl_) {
throw Error(1, "Uable to init libcurl.");
}
// The default block size for FTP is much larger than other protocols
// the reason is that getDataByRange() in FTP always creates the new connection,
// so we need the large block size to reduce the overhead of creating the connection.
if (blockSize_ == 0) {
blockSize_ = protocol_ == pFtp ? 102400 : 1024;
}
std::string timeout = getEnv(envTIMEOUT);
timeout_ = atol(timeout.c_str());
if (timeout_ == 0) {
throw Error(1, "Timeout Environmental Variable must be a positive integer.");
}
}
#ifdef EXV_UNICODE_PATH
CurlIo::CurlImpl::CurlImpl(const std::wstring& wurl, size_t blockSize):Impl(wurl, blockSize)
{
std::string url;
url.assign(wurl.begin(), wurl.end());
path_ = url;
// init curl pointer
curl_ = curl_easy_init();
if(!curl_) {
throw Error(1, "Uable to init libcurl.");
}
// The default block size for FTP is much larger than other protocols
// the reason is that getDataByRange() in FTP always creates the new connection,
// so we need the large block size to reduce the overhead of creating the connection.
if (blockSize_ == 0) {
blockSize_ = protocol_ == pFtp ? 102400 : 1024;
}
}
#endif
long CurlIo::CurlImpl::getFileLength()
{
curl_easy_reset(curl_); // reset all options
std::string response;
curl_easy_setopt(curl_, CURLOPT_URL, path_.c_str());
curl_easy_setopt(curl_, CURLOPT_NOBODY, 1); // HEAD
curl_easy_setopt(curl_, CURLOPT_WRITEFUNCTION, curlWriter);
curl_easy_setopt(curl_, CURLOPT_WRITEDATA, &response);
curl_easy_setopt(curl_, CURLOPT_SSL_VERIFYPEER, 0L);
curl_easy_setopt(curl_, CURLOPT_SSL_VERIFYHOST, 0L);
curl_easy_setopt(curl_, CURLOPT_CONNECTTIMEOUT, timeout_);
//curl_easy_setopt(curl_, CURLOPT_VERBOSE, 1); // debugging mode
/* Perform the request, res will get the return code */
CURLcode res = curl_easy_perform(curl_);
if(res != CURLE_OK) { // error happends
throw Error(1, curl_easy_strerror(res));
}
// get return code
long returnCode;
curl_easy_getinfo (curl_, CURLINFO_RESPONSE_CODE, &returnCode); // get code
if (returnCode >= 400 || returnCode < 0) {
throw Error(55, "Server", returnCode);
}
// get length
double temp;
curl_easy_getinfo(curl_, CURLINFO_CONTENT_LENGTH_DOWNLOAD, &temp); // return -1 if unknown
return (long) temp;
}
void CurlIo::CurlImpl::getDataByRange(long lowBlock, long highBlock, std::string& response)
{
curl_easy_reset(curl_); // reset all options
curl_easy_setopt(curl_, CURLOPT_URL, path_.c_str());
curl_easy_setopt(curl_, CURLOPT_NOPROGRESS, 1L); // no progress meter please
curl_easy_setopt(curl_, CURLOPT_WRITEFUNCTION, curlWriter);
curl_easy_setopt(curl_, CURLOPT_WRITEDATA, &response);
curl_easy_setopt(curl_, CURLOPT_SSL_VERIFYPEER, 0L);
curl_easy_setopt(curl_, CURLOPT_CONNECTTIMEOUT, timeout_);
curl_easy_setopt(curl_, CURLOPT_SSL_VERIFYHOST, 0L);
//curl_easy_setopt(curl_, CURLOPT_VERBOSE, 1); // debugging mode
if (lowBlock > -1 && highBlock> -1) {
std::stringstream ss;
ss << lowBlock * blockSize_ << "-" << ((highBlock + 1) * blockSize_ - 1);
std::string range = ss.str();
curl_easy_setopt(curl_, CURLOPT_RANGE, range.c_str());
}
/* Perform the request, res will get the return code */
CURLcode res = curl_easy_perform(curl_);
if(res != CURLE_OK) {
throw Error(1, curl_easy_strerror(res));
} else {
long serverCode;
curl_easy_getinfo (curl_, CURLINFO_RESPONSE_CODE, &serverCode); // get code
if (serverCode >= 400 || serverCode < 0) {
throw Error(55, "Server", serverCode);
}
}
}
void CurlIo::CurlImpl::writeRemote(const byte* data, size_t size, long from, long to)
{
std::string scriptPath(getEnv(envHTTPPOST));
if (scriptPath == "") {
throw Error(1, "Please set the path of the server script to handle http post data to EXIV2_HTTP_POST environmental variable.");
}
Exiv2::Uri hostInfo = Exiv2::Uri::Parse(path_);
// add the protocol and host to the path
std::size_t protocolIndex = scriptPath.find("://");
if (protocolIndex == std::string::npos) {
if (scriptPath[0] != '/') scriptPath = "/" + scriptPath;
scriptPath = hostInfo.Protocol + "://" + hostInfo.Host + scriptPath;
}
curl_easy_reset(curl_); // reset all options
curl_easy_setopt(curl_, CURLOPT_NOPROGRESS, 1L); // no progress meter please
//curl_easy_setopt(curl_, CURLOPT_VERBOSE, 1); // debugging mode
curl_easy_setopt(curl_, CURLOPT_URL, scriptPath.c_str());
curl_easy_setopt(curl_, CURLOPT_SSL_VERIFYPEER, 0L);
// encode base64
size_t encodeLength = ((size + 2) / 3) * 4 + 1;
char* encodeData = new char[encodeLength];
base64encode(data, size, encodeData, encodeLength);
// url encode
char* urlencodeData = urlencode(encodeData);
delete[] encodeData;
std::stringstream ss;
ss << "path=" << hostInfo.Path << "&"
<< "from=" << from << "&"
<< "to=" << to << "&"
<< "data=" << urlencodeData;
std::string postData = ss.str();
delete[] urlencodeData;
curl_easy_setopt(curl_, CURLOPT_POSTFIELDS, postData.c_str());
// Perform the request, res will get the return code.
CURLcode res = curl_easy_perform(curl_);
if(res != CURLE_OK) {
throw Error(1, curl_easy_strerror(res));
} else {
long serverCode;
curl_easy_getinfo (curl_, CURLINFO_RESPONSE_CODE, &serverCode);
if (serverCode >= 400 || serverCode < 0) {
throw Error(55, "Server", serverCode);
}
}
}
CurlIo::CurlImpl::~CurlImpl() {
curl_easy_cleanup(curl_);
}
long CurlIo::write(const byte* data, long wcount)
{
if (p_->protocol_ == pHttp || p_->protocol_ == pHttps) {
return RemoteIo::write(data, wcount);
} else {
throw Error(1, "doesnt support write for this protocol.");
}
}
long CurlIo::write(BasicIo& src)
{
if (p_->protocol_ == pHttp || p_->protocol_ == pHttps) {
return RemoteIo::write(src);
} else {
throw Error(1, "doesnt support write for this protocol.");
}
}
CurlIo::CurlIo(const std::string& url, size_t blockSize)
{
p_ = new CurlImpl(url, blockSize);
}
#ifdef EXV_UNICODE_PATH
CurlIo::CurlIo(const std::wstring& wurl, size_t blockSize)
{
p_ = new CurlImpl(wurl, blockSize);
}
#endif
#endif
#if EXV_USE_SSH == 1
//! Internal Pimpl structure of class RemoteIo.
class SshIo::SshImpl : public Impl {
public:
//! Constructor
SshImpl(const std::string& path, size_t blockSize);
#ifdef EXV_UNICODE_PATH
//! Constructor accepting a unicode path in an std::wstring
SshImpl(const std::wstring& wpath, size_t blockSize);
#endif
//! Destructor. Closes ssh session and releases all managed memory.
~SshImpl();
Exiv2::Uri hostInfo_; //!< host information extracted from path
SSH* ssh_; //!< SSH pointer
sftp_file fileHandler_; //!< sftp file handler
// METHODS
/*!
@brief Get the length (in bytes) of the remote file.
@return Return -1 if the size is unknown. Otherwise it returns the length of remote file (in bytes).
@throw Error if the server returns the error code.
*/
long getFileLength();
/*!
@brief Get the data by range.
@param lowBlock The start block index.
@param highBlock The end block index.
@param response The data from the server.
@throw Error if the server returns the error code.
@note Set lowBlock = -1 and highBlock = -1 to get the whole file content.
*/
void getDataByRange(long lowBlock, long highBlock, std::string& response);
/*!
@brief Submit the data to the remote machine. The data replace a part of the remote file.
The replaced part of remote file is indicated by from and to parameters.
@param data The data are submitted to the remote machine.
@param size The size of data.
@param from The start position in the remote file where the data replace.
@param to The end position in the remote file where the data replace.
@note The write access is only available on the SSH protocol. It requires the write permission
to edit the remote file.
@throw Error if it fails.
*/
void writeRemote(const byte* data, size_t size, long from, long to);
protected:
// NOT IMPLEMENTED
SshImpl(const SshImpl& rhs); //!< Copy constructor
SshImpl& operator=(const SshImpl& rhs); //!< Assignment
}; // class RemoteIo::Impl
SshIo::SshImpl::SshImpl(const std::string& url, size_t blockSize):Impl(url, blockSize)
{
hostInfo_ = Exiv2::Uri::Parse(url);
Exiv2::Uri::Decode(hostInfo_);
// remove / at the beginning of the path
if (hostInfo_.Path[0] == '/') {
hostInfo_.Path = hostInfo_.Path.substr(1);
}
ssh_ = new SSH(hostInfo_.Host, hostInfo_.Username, hostInfo_.Password, hostInfo_.Port);
if (protocol_ == pSftp) {
ssh_->getFileSftp(hostInfo_.Path, fileHandler_);
if (fileHandler_ == NULL) throw Error(1, "Unable to open the file");
} else {
fileHandler_ = NULL;
}
}
#ifdef EXV_UNICODE_PATH
SshIo::SshImpl::SshImpl(const std::wstring& wurl, size_t blockSize):Impl(wurl, blockSize)
{
std::string url;
url.assign(wurl.begin(), wurl.end());
path_ = url;
hostInfo_ = Exiv2::Uri::Parse(url);
Exiv2::Uri::Decode(hostInfo_);
// remove / at the beginning of the path
if (hostInfo_.Path[0] == '/') {
hostInfo_.Path = hostInfo_.Path.substr(1);
}
ssh_ = new SSH(hostInfo_.Host, hostInfo_.Username, hostInfo_.Password, hostInfo_.Port);
if (protocol_ == pSftp) {
ssh_->getFileSftp(hostInfo_.Path, fileHandler_);
if (fileHandler_ == NULL) throw Error(1, "Unable to open the file");
} else {
fileHandler_ = NULL;
}
}
#endif
long SshIo::SshImpl::getFileLength()
{
long length = 0;
if (protocol_ == pSftp) { // sftp
sftp_attributes attributes = sftp_fstat(fileHandler_);
length = (long)attributes->size;
} else { // ssh
std::string response;
//std::string cmd = "stat -c %s " + hostInfo_.Path;
std::string cmd = "declare -a x=($(ls -alt " + hostInfo_.Path + ")); echo ${x[4]}";
if (ssh_->runCommand(cmd, &response) != 0) {
throw Error(1, "Unable to get file length.");
} else {
length = atol(response.c_str());
if (length == 0) {
throw Error(1, "File is empty or not found.");
}
}
}
return length;
}
void SshIo::SshImpl::getDataByRange(long lowBlock, long highBlock, std::string& response)
{
if (protocol_ == pSftp) {
if (sftp_seek(fileHandler_, (uint32_t) (lowBlock * blockSize_)) < 0) throw Error(1, "SFTP: unable to sftp_seek");
size_t buffSize = (highBlock - lowBlock + 1) * blockSize_;
char* buffer = new char[buffSize];
long nBytes = (long) sftp_read(fileHandler_, buffer, buffSize);
if (nBytes < 0) throw Error(1, "SFTP: unable to sftp_read");
response.assign(buffer, buffSize);
delete[] buffer;
} else {
std::stringstream ss;
if (lowBlock > -1 && highBlock > -1) {
ss << "dd if=" << hostInfo_.Path
<< " ibs=" << blockSize_
<< " skip=" << lowBlock
<< " count=" << (highBlock - lowBlock) + 1<< " 2>/dev/null";
} else {
ss << "dd if=" << hostInfo_.Path
<< " ibs=" << blockSize_
<< " 2>/dev/null";
}
std::string cmd = ss.str();
if (ssh_->runCommand(cmd, &response) != 0) {
throw Error(1, "Unable to get data by range.");
}
}
}
void SshIo::SshImpl::writeRemote(const byte* data, size_t size, long from, long to)
{
if (protocol_ == pSftp) throw Error(1, "not support SFTP write access.");
//printf("ssh update size=%ld from=%ld to=%ld\n", (long)size, from, to);
assert(isMalloced_);
std::string tempFile = hostInfo_.Path + ".exiv2tmp";
std::string response;
std::stringstream ss;
// copy the head (byte 0 to byte fromByte) of original file to filepath.exiv2tmp
ss << "head -c " << from
<< " " << hostInfo_.Path
<< " > " << tempFile;
std::string cmd = ss.str();
if (ssh_->runCommand(cmd, &response) != 0) {
throw Error(1, "SSH: Unable to cope the head of file to temp");
}
// upload the data (the byte ranges which are different between the original
// file and the new file) to filepath.exiv2datatemp
if (ssh_->scp(hostInfo_.Path + ".exiv2datatemp", data, size) != 0) {
throw Error(1, "SSH: Unable to copy file");
}
// concatenate the filepath.exiv2datatemp to filepath.exiv2tmp
cmd = "cat " + hostInfo_.Path + ".exiv2datatemp >> " + tempFile;
if (ssh_->runCommand(cmd, &response) != 0) {
throw Error(1, "SSH: Unable to copy the rest");
}
// copy the tail (from byte toByte to the end of file) of original file to filepath.exiv2tmp
ss.str("");
ss << "tail -c+" << (to + 1)
<< " " << hostInfo_.Path
<< " >> " << tempFile;
cmd = ss.str();
if (ssh_->runCommand(cmd, &response) != 0) {
throw Error(1, "SSH: Unable to copy the rest");
}
// replace the original file with filepath.exiv2tmp
cmd = "mv " + tempFile + " " + hostInfo_.Path;
if (ssh_->runCommand(cmd, &response) != 0) {
throw Error(1, "SSH: Unable to copy the rest");
}
// remove filepath.exiv2datatemp
cmd = "rm " + hostInfo_.Path + ".exiv2datatemp";
if (ssh_->runCommand(cmd, &response) != 0) {
throw Error(1, "SSH: Unable to copy the rest");
}
}
SshIo::SshImpl::~SshImpl() {
if (fileHandler_) sftp_close(fileHandler_);
if (ssh_) delete ssh_;
}
SshIo::SshIo(const std::string& url, size_t blockSize)
{
p_ = new SshImpl(url, blockSize);
}
#ifdef EXV_UNICODE_PATH
SshIo::SshIo(const std::wstring& wurl, size_t blockSize)
{
p_ = new SshImpl(wurl, blockSize);
}
#endif
#endif
// *************************************************************************
// free functions
DataBuf readFile(const std::string& path)
{
FileIo file(path);
if (file.open("rb") != 0) {
throw Error(10, path, "rb", strError());
}
struct stat st;
if (0 != ::stat(path.c_str(), &st)) {
throw Error(2, path, strError(), "::stat");
}
DataBuf buf(st.st_size);
long len = file.read(buf.pData_, buf.size_);
if (len != buf.size_) {
throw Error(2, path, strError(), "FileIo::read");
}
return buf;
}
#ifdef EXV_UNICODE_PATH
DataBuf readFile(const std::wstring& wpath)
{
FileIo file(wpath);
if (file.open("rb") != 0) {
throw WError(10, wpath, "rb", strError().c_str());
}
struct _stat st;
if (0 != ::_wstat(wpath.c_str(), &st)) {
throw WError(2, wpath, strError().c_str(), "::_wstat");
}
DataBuf buf(st.st_size);
long len = file.read(buf.pData_, buf.size_);
if (len != buf.size_) {
throw WError(2, wpath, strError().c_str(), "FileIo::read");
}
return buf;
}
#endif
long writeFile(const DataBuf& buf, const std::string& path)
{
FileIo file(path);
if (file.open("wb") != 0) {
throw Error(10, path, "wb", strError());
}
return file.write(buf.pData_, buf.size_);
}
#ifdef EXV_UNICODE_PATH
long writeFile(const DataBuf& buf, const std::wstring& wpath)
{
FileIo file(wpath);
if (file.open("wb") != 0) {
throw WError(10, wpath, "wb", strError().c_str());
}
return file.write(buf.pData_, buf.size_);
}
#endif
std::string ReplaceStringInPlace(std::string subject, const std::string& search,
const std::string& replace) {
size_t pos = 0;
while((pos = subject.find(search, pos)) != std::string::npos) {
subject.replace(pos, search.length(), replace);
pos += replace.length();
}
return subject;
}
#ifdef EXV_UNICODE_PATH
std::wstring ReplaceStringInPlace(std::wstring subject, const std::wstring& search,
const std::wstring& replace) {
std::wstring::size_type pos = 0;
while((pos = subject.find(search, pos)) != std::wstring::npos) {
subject.replace(pos, search.length(), replace);
pos += replace.length();
}
return subject;
}
#endif
#if EXV_USE_CURL == 1
size_t curlWriter(char* data, size_t size, size_t nmemb,
std::string* writerData)
{
if (writerData == NULL) return 0;
writerData->append(data, size*nmemb);
return size * nmemb;
}
#endif
} // namespace Exiv2
| 33.977652 | 163 | 0.530206 | Vitalii17 |
955e642c5037f566bf8e6c34c4062e4dba681223 | 1,118 | cpp | C++ | algorithms/cpp/Problems 101-200/_132_PalindromicPartitioningII.cpp | shivamacs/LeetCode | f8f8b4e9872c47fbaaf9196c422f7e04986e6c3a | [
"MIT"
] | null | null | null | algorithms/cpp/Problems 101-200/_132_PalindromicPartitioningII.cpp | shivamacs/LeetCode | f8f8b4e9872c47fbaaf9196c422f7e04986e6c3a | [
"MIT"
] | null | null | null | algorithms/cpp/Problems 101-200/_132_PalindromicPartitioningII.cpp | shivamacs/LeetCode | f8f8b4e9872c47fbaaf9196c422f7e04986e6c3a | [
"MIT"
] | null | null | null | /* Source - https://leetcode.com/problems/palindrome-partitioning-ii/
Author - Shivam Arora
*/
#include <bits/stdc++.h>
using namespace std;
int minCut(string s) {
int n = s.length();
bool pre[n][n];
memset(pre, false, sizeof(pre));
for(int k = 0; k < n; k++) {
for(int i = 0, j = k; j < n; i++, j++) {
if(k == 0)
pre[i][j] = true;
else if(k == 1)
pre[i][j] = s[i] == s[j];
else if(s[i] == s[j])
pre[i][j] = pre[i + 1][j - 1];
}
}
if(pre[0][n - 1])
return 0;
int dp[n];
for(int i = 0; i < n; i++) {
if(pre[0][i])
dp[i] = 0;
else {
dp[i] = INT_MAX;
for(int j = i; j > 0; j--) {
if(pre[j][i])
dp[i] = min(dp[i], 1 + dp[j - 1]);
}
}
}
return dp[n - 1];
}
int main()
{
string s;
cout<<"Enter a string: ";
cin>>s;
cout<<"Minimum cuts in the string such that each part is a palindrome: "<<minCut(s)<<endl;
} | 21.5 | 94 | 0.392665 | shivamacs |
9560a707872099649b187238b06465d99aae547e | 5,616 | hpp | C++ | SocketAdapter.hpp | Sologala/socket_cvMat | d3ffa4e68badb29f168f955261671ba316ed586b | [
"BSD-2-Clause"
] | null | null | null | SocketAdapter.hpp | Sologala/socket_cvMat | d3ffa4e68badb29f168f955261671ba316ed586b | [
"BSD-2-Clause"
] | null | null | null | SocketAdapter.hpp | Sologala/socket_cvMat | d3ffa4e68badb29f168f955261671ba316ed586b | [
"BSD-2-Clause"
] | null | null | null | #ifndef SOCKETADAPTER_H
#define SOCKETADAPTER_H
#pragma once
#include <arpa/inet.h>
#include <sys/socket.h>
#include <unistd.h>
#include <cstring>
#include "msg.pb.h"
#define IMG_BUFFER_SIZE 5000 * 5000 * 4 * 3
#define MSG_HEAD_SIZE 8
enum SocketAdapter_Mode { SERVER = 0, CLIENT = 1 };
template <class DATA, class MSG, class WRAPER, class DEWRAPER>
class SocketAdapter {
public:
SocketAdapter(SocketAdapter_Mode _mode, int port = 9999, const char *server_id = NULL);
~SocketAdapter();
bool is_connected() { return connected_; }
void Send(DATA data);
DATA Recv();
protected:
int Create_connection_server();
int Create_connection_client();
protected:
int port_;
SocketAdapter_Mode mode_;
int sock;
struct sockaddr_in serv_addr;
char target_ip[100];
// for server
int opt = 1;
bool connected_ = false;
private:
unsigned char *out_buffer;
unsigned char *in_buffer;
};
template <class DATA, class MSG, class WRAPER, class DEWRAPER>
void SocketAdapter<DATA, MSG, WRAPER, DEWRAPER>::Send(DATA data) {
if (!connected_) {
printf("\n not connected \n");
return;
}
proto_cv::msgHead msg_head;
MSG msg = WRAPER()(data);
msg_head.set_len(msg.ByteSize());
memset(out_buffer, 0, IMG_BUFFER_SIZE);
msg_head.SerializeToArray(out_buffer, msg_head.ByteSize());
while (send(sock, out_buffer, MSG_HEAD_SIZE, 0) != MSG_HEAD_SIZE)
;
// send data
assert(msg.ByteSize() <= IMG_BUFFER_SIZE);
// cout << msg_head.ByteSize() << " " << msg.ByteSize() << endl;
msg.SerializeToArray(out_buffer, msg.ByteSize());
while (send(sock, out_buffer, msg.ByteSize(), 0) != msg.ByteSize())
;
}
template <class DATA, class MSG, class WRAPER, class DEWRAPER>
DATA SocketAdapter<DATA, MSG, WRAPER, DEWRAPER>::Recv() {
if (!connected_) {
printf("\n not connected \n");
return DATA();
}
MSG msg;
msg.Clear();
proto_cv::msgHead msg_head;
// proto_cv::Mat_Head msg_head;
memset(in_buffer, 0, IMG_BUFFER_SIZE);
while (recv(sock, in_buffer, MSG_HEAD_SIZE, MSG_WAITALL) != MSG_HEAD_SIZE)
;
msg_head.ParseFromArray(in_buffer, MSG_HEAD_SIZE);
while (recv(sock, in_buffer, msg_head.len(), MSG_WAITALL) != msg_head.len())
;
msg.ParseFromArray(in_buffer, msg_head.len());
DATA data;
data = DEWRAPER()(msg);
return data;
}
template <class DATA, class MSG, class WRAPER, class DEWRAPER>
int SocketAdapter<DATA, MSG, WRAPER, DEWRAPER>::Create_connection_server() {
int server_fd;
int opt = 1;
int addrlen = sizeof(serv_addr);
// Creating socket file descriptor
if ((server_fd = socket(AF_INET, SOCK_STREAM, 0)) == 0) {
perror("socket failed");
return -1;
}
// Forcefully attaching socket to the port 8080
if (setsockopt(server_fd, SOL_SOCKET, SO_REUSEADDR | SO_REUSEPORT, &opt, sizeof(opt))) {
perror("setsockopt");
return -1;
}
serv_addr.sin_family = AF_INET;
serv_addr.sin_addr.s_addr = INADDR_ANY;
serv_addr.sin_port = htons(port_);
// Forcefully attaching socket to the port 8080
if (bind(server_fd, (struct sockaddr *)&serv_addr, sizeof(serv_addr)) < 0) {
perror("bind failed");
return -1;
}
if (listen(server_fd, 3) < 0) {
perror("listen");
return -1;
}
// server 的 accept 方法会阻塞 函数
printf("wait for client connection\n");
if ((sock = accept(server_fd, (struct sockaddr *)&serv_addr, (socklen_t *)&addrlen)) < 0) {
perror("accept");
return -1;
}
printf("client connected\n");
return 0;
}
template <class DATA, class MSG, class WRAPER, class DEWARPRE>
int SocketAdapter<DATA, MSG, WRAPER, DEWARPRE>::Create_connection_client() {
if ((sock = socket(AF_INET, SOCK_STREAM, 0)) < 0) {
printf("\n Socket creation error \n");
return -1;
}
serv_addr.sin_family = AF_INET;
serv_addr.sin_port = htons(port_);
// Convert IPv4 and IPv6 addresses from text to binary form
assert(strlen(target_ip) != 0);
if (inet_pton(AF_INET, target_ip, &serv_addr.sin_addr) <= 0) {
printf("\nInvalid address/ Address not supported \n");
return -1;
}
int retry_cnt = 1000;
while (retry_cnt) {
if (connect(sock, (struct sockaddr *)&serv_addr, sizeof(serv_addr)) < 0) {
printf("\nConnection Failed \n");
retry_cnt--;
usleep(200000);
} else {
break;
}
}
if (retry_cnt == 0) {
printf("\n retry 100 times without success! exit");
return -1;
}
printf("\n create connection success\n");
return 0;
}
template <class DATA, class MSG, class WRAPER, class DEWRAPER>
SocketAdapter<DATA, MSG, WRAPER, DEWRAPER>::SocketAdapter(SocketAdapter_Mode _mode, int port, const char *server_id)
: port_(port), mode_(_mode) {
bool res = 0;
if (_mode == SocketAdapter_Mode::SERVER) {
res = Create_connection_server();
} else {
memset(target_ip, 0, sizeof(target_ip));
memcpy(target_ip, server_id, strlen(server_id));
res = Create_connection_client();
}
if (res == 0) {
connected_ = true;
} else {
connected_ = false;
}
out_buffer = new unsigned char[IMG_BUFFER_SIZE];
in_buffer = new unsigned char[IMG_BUFFER_SIZE];
}
template <class DATA, class MSG, class WRAPER, class DEWRAPER>
SocketAdapter<DATA, MSG, WRAPER, DEWRAPER>::~SocketAdapter() {
delete[] out_buffer;
delete[] in_buffer;
}
#endif | 28.507614 | 116 | 0.637642 | Sologala |
956142c39f615464d087e03ddc11dda0ce9545ef | 9,468 | cpp | C++ | unittests/http/test_buffered_reader.cpp | paulhuggett/pstore | 067be94d87c87fce524c8d76c6f47c347d8f1853 | [
"Apache-2.0"
] | 11 | 2018-02-02T21:24:49.000Z | 2020-12-11T04:06:03.000Z | unittests/http/test_buffered_reader.cpp | SNSystems/pstore | 74e9dd960245d6bfc125af03ed964d8ad660a62d | [
"Apache-2.0"
] | 63 | 2018-02-05T17:24:59.000Z | 2022-03-22T17:26:28.000Z | unittests/http/test_buffered_reader.cpp | paulhuggett/pstore | 067be94d87c87fce524c8d76c6f47c347d8f1853 | [
"Apache-2.0"
] | 5 | 2020-01-13T22:47:11.000Z | 2021-05-14T09:31:15.000Z | //===- unittests/http/test_buffered_reader.cpp ----------------------------===//
//* _ __ __ _ _ *
//* | |__ _ _ / _|/ _| ___ _ __ ___ __| | _ __ ___ __ _ __| | ___ _ __ *
//* | '_ \| | | | |_| |_ / _ \ '__/ _ \/ _` | | '__/ _ \/ _` |/ _` |/ _ \ '__| *
//* | |_) | |_| | _| _| __/ | | __/ (_| | | | | __/ (_| | (_| | __/ | *
//* |_.__/ \__,_|_| |_| \___|_| \___|\__,_| |_| \___|\__,_|\__,_|\___|_| *
//* *
//===----------------------------------------------------------------------===//
//
// Part of the pstore project, under the Apache License v2.0 with LLVM Exceptions.
// See https://github.com/SNSystems/pstore/blob/master/LICENSE.txt for license
// information.
// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
//
//===----------------------------------------------------------------------===//
#include "pstore/http/buffered_reader.hpp"
// Standard Library includes
#include <algorithm>
#include <cerrno>
#include <cstring>
#include <string>
#include <vector>
// 3rd party includes
#include "gmock/gmock.h"
// Local includes
#include "buffered_reader_mocks.hpp"
using pstore::error_or;
using pstore::error_or_n;
using pstore::in_place;
using pstore::maybe;
using pstore::gsl::span;
using pstore::http::make_buffered_reader;
using testing::_;
using testing::Invoke;
TEST (HttpdBufferedReader, Span) {
using byte_span = pstore::gsl::span<std::uint8_t>;
auto refill = [] (int io, byte_span const & sp) {
std::fill (std::begin (sp), std::end (sp), std::uint8_t{0});
return pstore::error_or_n<int, byte_span::iterator>{pstore::in_place, io, sp.end ()};
};
constexpr auto buffer_size = std::size_t{0};
constexpr auto requested_size = std::size_t{1};
auto br = pstore::http::make_buffered_reader<int> (refill, buffer_size);
std::vector<std::uint8_t> v (requested_size, std::uint8_t{0xFF});
pstore::error_or_n<int, byte_span> res = br.get_span (0, pstore::gsl::make_span (v));
ASSERT_TRUE (res);
auto const & sp = std::get<1> (res);
ASSERT_EQ (sp.size (), 1);
EXPECT_EQ (sp[0], std::uint8_t{0});
}
TEST (HttpdBufferedReader, GetcThenEOF) {
refiller r;
EXPECT_CALL (r, fill (_, _)).WillRepeatedly (Invoke (eof ()));
EXPECT_CALL (r, fill (0, _)).WillOnce (Invoke (yield_string ("a")));
auto io = 0;
auto br = make_buffered_reader<int> (r.refill_function ());
{
getc_result_type const c1 = br.getc (io);
ASSERT_TRUE (static_cast<bool> (c1));
io = std::get<0> (*c1);
maybe<char> const char1 = std::get<1> (*c1);
ASSERT_TRUE (char1.has_value ());
EXPECT_EQ (char1.value (), 'a');
}
{
getc_result_type const c2 = br.getc (io);
ASSERT_TRUE (static_cast<bool> (c2));
// Uncomment the next line if adding further blocks to this test!
// io = std::get<0> (*c2);
maybe<char> const char2 = std::get<1> (*c2);
ASSERT_FALSE (char2.has_value ());
}
}
TEST (HttpdBufferedReader, GetTwoStringsLFThenEOF) {
refiller r;
EXPECT_CALL (r, fill (_, _)).WillRepeatedly (Invoke (eof ()));
EXPECT_CALL (r, fill (0, _)).WillOnce (Invoke (yield_string ("abc\ndef")));
auto io = 0;
auto br = make_buffered_reader<int> (r.refill_function ());
{
gets_result_type const s1 = br.gets (io);
ASSERT_TRUE (static_cast<bool> (s1));
maybe<std::string> str1;
std::tie (io, str1) = *s1;
ASSERT_TRUE (str1.has_value ());
EXPECT_EQ (str1.value (), "abc");
}
{
gets_result_type const s2 = br.gets (io);
ASSERT_TRUE (static_cast<bool> (s2));
maybe<std::string> str2;
std::tie (io, str2) = *s2;
ASSERT_TRUE (str2.has_value ());
EXPECT_EQ (str2.value (), "def");
}
{
gets_result_type const s3 = br.gets (io);
ASSERT_TRUE (static_cast<bool> (s3));
maybe<std::string> str3;
std::tie (io, str3) = *s3;
ASSERT_FALSE (str3.has_value ());
}
}
TEST (HttpdBufferedReader, StringCRLF) {
refiller r;
EXPECT_CALL (r, fill (_, _)).WillRepeatedly (Invoke (eof ()));
EXPECT_CALL (r, fill (0, _)).WillOnce (Invoke (yield_string ("abc\r\ndef")));
auto io = 0;
auto br = make_buffered_reader<int> (r.refill_function ());
{
gets_result_type const s1 = br.gets (io);
ASSERT_TRUE (static_cast<bool> (s1))
<< "There was an unexpected error: " << s1.get_error ();
maybe<std::string> str1;
std::tie (io, str1) = *s1;
ASSERT_TRUE (str1.has_value ());
EXPECT_EQ (str1.value (), "abc");
}
{
gets_result_type const s2 = br.gets (io);
ASSERT_TRUE (static_cast<bool> (s2))
<< "There was an unexpected error: " << s2.get_error ();
maybe<std::string> str2;
std::tie (io, str2) = *s2;
ASSERT_TRUE (str2.has_value ());
EXPECT_EQ (str2.value (), "def");
}
{
gets_result_type const s3 = br.gets (io);
ASSERT_TRUE (static_cast<bool> (s3))
<< "There was an unexpected error: " << s3.get_error ();
maybe<std::string> str3;
std::tie (io, str3) = *s3;
ASSERT_FALSE (str3.has_value ());
}
}
TEST (HttpdBufferedReader, StringCRNoLFThenEOF) {
refiller r;
EXPECT_CALL (r, fill (_, _)).WillRepeatedly (Invoke (eof ()));
EXPECT_CALL (r, fill (0, _)).WillOnce (Invoke (yield_string ("abc\r")));
auto io = 0;
auto br = make_buffered_reader<int> (r.refill_function ());
{
gets_result_type const s1 = br.gets (io);
ASSERT_TRUE (static_cast<bool> (s1))
<< "There was an unexpected error: " << s1.get_error ();
maybe<std::string> str1;
std::tie (io, str1) = *s1;
ASSERT_TRUE (str1.has_value ());
EXPECT_EQ (str1.value (), "abc");
}
{
gets_result_type const s2 = br.gets (io);
ASSERT_TRUE (static_cast<bool> (s2))
<< "There was an unexpected error: " << s2.get_error ();
maybe<std::string> str2;
std::tie (io, str2) = *s2;
ASSERT_FALSE (str2.has_value ());
}
}
TEST (HttpdBufferedReader, StringCRNoLFChars) {
refiller r;
EXPECT_CALL (r, fill (_, _)).WillRepeatedly (Invoke (eof ()));
EXPECT_CALL (r, fill (0, _)).WillOnce (Invoke (yield_string ("abc\rdef")));
auto io = 0;
auto br = make_buffered_reader<int> (r.refill_function ());
{
gets_result_type const s1 = br.gets (io);
ASSERT_TRUE (static_cast<bool> (s1))
<< "There was an unexpected error: " << s1.get_error ();
maybe<std::string> str1;
std::tie (io, str1) = *s1;
ASSERT_TRUE (str1.has_value ());
EXPECT_EQ (str1.value (), "abc");
}
{
gets_result_type const s2 = br.gets (io);
ASSERT_TRUE (static_cast<bool> (s2))
<< "There was an unexpected error: " << s2.get_error ();
maybe<std::string> str2;
std::tie (io, str2) = *s2;
ASSERT_TRUE (str2.has_value ());
EXPECT_EQ (str2.value (), "def");
}
}
TEST (HttpdBufferedReader, SomeCharactersThenAnError) {
refiller r;
EXPECT_CALL (r, fill (0, _)).WillOnce (Invoke (yield_string ("abc\nd")));
EXPECT_CALL (r, fill (1, _)).WillOnce (Invoke ([] (int, span<std::uint8_t> const &) {
return refiller_result_type (std::make_error_code (std::errc::operation_not_permitted));
}));
auto io = 0;
auto br = make_buffered_reader<int> (r.refill_function ());
{
gets_result_type const s1 = br.gets (io);
ASSERT_TRUE (static_cast<bool> (s1)) << "Error: " << s1.get_error ();
maybe<std::string> str1;
std::tie (io, str1) = *s1;
ASSERT_TRUE (str1.has_value ());
EXPECT_EQ (str1.value (), "abc");
}
{
gets_result_type const s2 = br.gets (io);
ASSERT_FALSE (static_cast<bool> (s2)) << "An error was expected";
EXPECT_EQ (s2.get_error (), (std::make_error_code (std::errc::operation_not_permitted)));
}
}
TEST (HttpdBufferedReader, MaxLengthString) {
using pstore::http::max_string_length;
std::string const max_length_string (max_string_length, 'a');
refiller r;
EXPECT_CALL (r, fill (_, _)).WillRepeatedly (Invoke (eof ()));
EXPECT_CALL (r, fill (0, _)).WillOnce (Invoke (yield_string (max_length_string)));
auto io = 0;
auto br = make_buffered_reader<int> (r.refill_function (), max_string_length);
error_or_n<int, maybe<std::string>> const s1 = br.gets (io);
ASSERT_TRUE (static_cast<bool> (s1)) << "Error: " << s1.get_error ();
maybe<std::string> str1;
std::tie (io, str1) = *s1;
ASSERT_TRUE (str1.has_value ());
EXPECT_EQ (str1.value (), max_length_string);
}
TEST (HttpdBufferedReader, StringTooLong) {
using pstore::http::max_string_length;
refiller r;
EXPECT_CALL (r, fill (_, _)).WillRepeatedly (Invoke (eof ()));
EXPECT_CALL (r, fill (0, _))
.WillOnce (Invoke (yield_string (std::string (max_string_length + 1U, 'a'))));
auto io = 0;
auto br = make_buffered_reader<int> (r.refill_function (), max_string_length + 1U);
error_or_n<int, maybe<std::string>> const s2 = br.gets (io);
EXPECT_EQ (s2.get_error (), make_error_code (pstore::http::error_code::string_too_long));
}
| 36.555985 | 97 | 0.575201 | paulhuggett |
956792a122ceac7ce969482efac081aae8ce55b1 | 15,229 | cpp | C++ | windows/subwnd/dclock.cpp | whitehara/NP2kai | 72117d7a5def7e6c735f6780d53322c044e2b1d3 | [
"MIT"
] | 170 | 2017-08-15T17:02:36.000Z | 2022-03-30T20:02:26.000Z | windows/subwnd/dclock.cpp | whitehara/NP2kai | 72117d7a5def7e6c735f6780d53322c044e2b1d3 | [
"MIT"
] | 138 | 2017-07-09T13:18:51.000Z | 2022-03-20T17:53:43.000Z | windows/subwnd/dclock.cpp | whitehara/NP2kai | 72117d7a5def7e6c735f6780d53322c044e2b1d3 | [
"MIT"
] | 53 | 2017-07-17T10:27:42.000Z | 2022-03-15T01:09:05.000Z | /**
* @file dclock.cpp
* @brief 時刻表示クラスの動作の定義を行います
*/
#include <compiler.h>
#include "dclock.h"
#include <common/parts.h>
#include <np2.h>
#include <scrnmng.h>
#include <timemng.h>
#include <vram/scrndraw.h>
#include <vram/palettes.h>
//! 唯一のインスタンスです
DispClock DispClock::sm_instance;
/**
* @brief パターン構造体
*/
struct DispClockPattern
{
UINT8 cWidth; /*!< フォント サイズ */
UINT8 cMask; /*!< マスク */
UINT8 cPosition[6]; /*!< 位置 */
void (*fnInitialize)(UINT8* lpBuffer, UINT8 nDegits); /*!< 初期化関数 */
UINT8 font[11][16]; /*!< フォント */
};
/**
* 初期化-1
* @param[out] lpBuffer バッファ
* @param[in] nDegits 桁数
*/
static void InitializeFont1(UINT8* lpBuffer, UINT8 nDegits)
{
if (nDegits)
{
const UINT32 pat = (nDegits <= 4) ? 0x00008001 : 0x30008001;
*(UINT32 *)(lpBuffer + 1 + ( 4 * DCLOCK_YALIGN)) = pat;
*(UINT32 *)(lpBuffer + 1 + ( 5 * DCLOCK_YALIGN)) = pat;
*(UINT32 *)(lpBuffer + 1 + ( 9 * DCLOCK_YALIGN)) = pat;
*(UINT32 *)(lpBuffer + 1 + (10 * DCLOCK_YALIGN)) = pat;
}
}
/**
* 初期化-2
* @param[out] lpBuffer バッファ
* @param[in] nDegits 桁数
*/
static void InitializeFont2(UINT8* lpBuffer, UINT8 nDegits)
{
if (nDegits)
{
UINT32 pat = (nDegits <= 4) ? 0x00000002 : 0x00020002;
*(UINT32 *)(lpBuffer + 1 + ( 4 * DCLOCK_YALIGN)) = pat;
*(UINT32 *)(lpBuffer + 1 + ( 5 * DCLOCK_YALIGN)) = pat;
pat <<= 1;
*(UINT32 *)(lpBuffer + 1 + ( 9 * DCLOCK_YALIGN)) = pat;
*(UINT32 *)(lpBuffer + 1 + (10 * DCLOCK_YALIGN)) = pat;
}
}
/**
* 初期化-3
* @param[out] lpBuffer バッファ
* @param[in] nDegits 桁数
*/
static void InitializeFont3(UINT8* lpBuffer, UINT8 nDegits)
{
if (nDegits)
{
const UINT32 pat = (nDegits <= 4) ? 0x00000010 : 0x00400010;
*(UINT32 *)(lpBuffer + 1 + ( 4 * DCLOCK_YALIGN)) = pat;
*(UINT32 *)(lpBuffer + 1 + ( 5 * DCLOCK_YALIGN)) = pat;
*(UINT32 *)(lpBuffer + 1 + ( 9 * DCLOCK_YALIGN)) = pat;
*(UINT32 *)(lpBuffer + 1 + (10 * DCLOCK_YALIGN)) = pat;
}
}
/**
* 初期化-4
* @param[out] lpBuffer バッファ
* @param[in] nDegits 桁数
*/
static void InitializeFont4(UINT8* lpBuffer, UINT8 nDegits)
{
if (nDegits)
{
const UINT32 pat = (nDegits <= 4) ? 0x00000004 : 0x00040004;
*(UINT32 *)(lpBuffer + 1 + ( 5 * DCLOCK_YALIGN)) = pat;
*(UINT32 *)(lpBuffer + 1 + ( 6 * DCLOCK_YALIGN)) = pat;
*(UINT32 *)(lpBuffer + 1 + ( 9 * DCLOCK_YALIGN)) = pat;
*(UINT32 *)(lpBuffer + 1 + (10 * DCLOCK_YALIGN)) = pat;
}
}
/**
* 初期化-5
* @param[out] lpBuffer バッファ
* @param[in] nDegits 桁数
*/
static void InitializeFont5(UINT8* lpBuffer, UINT8 nDegits)
{
if (nDegits)
{
const UINT32 pat = (nDegits <= 4) ? 0x00000006 : 0x00030006;
*(UINT32 *)(lpBuffer + 1 + ( 6 * DCLOCK_YALIGN)) = pat;
*(UINT32 *)(lpBuffer + 1 + ( 7 * DCLOCK_YALIGN)) = pat;
*(UINT32 *)(lpBuffer + 1 + ( 9 * DCLOCK_YALIGN)) = pat;
*(UINT32 *)(lpBuffer + 1 + (10 * DCLOCK_YALIGN)) = pat;
}
}
/**
* 初期化-6
* @param[out] lpBuffer バッファ
* @param[in] nDegits 桁数
*/
static void InitializeFont6(UINT8* lpBuffer, UINT8 nDegits)
{
if (nDegits)
{
const UINT32 pat = (nDegits <= 4) ? 0x00000020 : 0x00000220;
*(UINT32 *)(lpBuffer + 1 + ( 8 * DCLOCK_YALIGN)) = pat;
*(UINT32 *)(lpBuffer + 1 + (10 * DCLOCK_YALIGN)) = pat;
}
}
/**
* パターン
*/
static const DispClockPattern s_pattern[6] =
{
// FONT-1
{
6, 0xfc,
{0, 7, 19, 26, 38, 45},
InitializeFont1,
{
{0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,},
{0x78, 0xcc, 0xcc, 0xcc, 0xcc, 0xcc, 0xcc, 0xcc, 0x78,},
{0x30, 0x70, 0x30, 0x30, 0x30, 0x30, 0x30, 0x30, 0x30,},
{0x78, 0xcc, 0xcc, 0x0c, 0x18, 0x30, 0x60, 0xc0, 0xfc,},
{0xfc, 0x18, 0x30, 0x70, 0x18, 0x0c, 0x0c, 0xcc, 0x78,},
{0x18, 0x38, 0x78, 0xd8, 0xd8, 0xfc, 0x18, 0x18, 0x18,},
{0xfc, 0xc0, 0xc0, 0xf8, 0x0c, 0x0c, 0x0c, 0x8c, 0x78,},
{0x38, 0x60, 0xc0, 0xf8, 0xcc, 0xcc, 0xcc, 0xcc, 0x78,},
{0xfc, 0x0c, 0x0c, 0x18, 0x18, 0x18, 0x30, 0x30, 0x30,},
{0x78, 0xcc, 0xcc, 0xcc, 0x78, 0xcc, 0xcc, 0xcc, 0x78,},
{0x78, 0xcc, 0xcc, 0xcc, 0xcc, 0x7c, 0x0c, 0x18, 0x70,}
}
},
// FONT-2
{
6, 0xfc,
{0, 6, 16, 22, 32, 38},
InitializeFont2,
{
{0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,},
{0x00, 0x00, 0x30, 0x48, 0x88, 0x88, 0x88, 0x88, 0x70,},
{0x10, 0x30, 0x10, 0x10, 0x10, 0x20, 0x20, 0x20, 0x20,},
{0x38, 0x44, 0x04, 0x08, 0x10, 0x20, 0x40, 0x80, 0xf8,},
{0x7c, 0x08, 0x10, 0x30, 0x10, 0x08, 0x08, 0x90, 0x60,},
{0x20, 0x40, 0x40, 0x88, 0x88, 0x90, 0x78, 0x10, 0x20,},
{0x3c, 0x20, 0x20, 0x70, 0x08, 0x08, 0x08, 0x90, 0x60,},
{0x10, 0x10, 0x20, 0x70, 0x48, 0x88, 0x88, 0x90, 0x60,},
{0x7c, 0x04, 0x08, 0x08, 0x10, 0x10, 0x20, 0x20, 0x40,},
{0x38, 0x44, 0x44, 0x48, 0x30, 0x48, 0x88, 0x88, 0x70,},
{0x18, 0x24, 0x40, 0x44, 0x48, 0x38, 0x10, 0x20, 0x20,}
}
},
// FONT-3
{
4, 0xf0,
{0, 5, 14, 19, 28, 33},
InitializeFont3,
{
{0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,},
{0x60, 0x90, 0x90, 0x90, 0x90, 0x90, 0x90, 0x90, 0x60,},
{0x20, 0x60, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20,},
{0x60, 0x90, 0x90, 0x10, 0x20, 0x40, 0x40, 0x80, 0xf0,},
{0x60, 0x90, 0x90, 0x10, 0x60, 0x10, 0x90, 0x90, 0x60,},
{0x20, 0x60, 0x60, 0xa0, 0xa0, 0xa0, 0xf0, 0x20, 0x20,},
{0xf0, 0x80, 0x80, 0xe0, 0x90, 0x10, 0x90, 0x90, 0x60,},
{0x60, 0x90, 0x90, 0x80, 0xe0, 0x90, 0x90, 0x90, 0x60,},
{0xf0, 0x10, 0x10, 0x20, 0x20, 0x20, 0x40, 0x40, 0x40,},
{0x60, 0x90, 0x90, 0x90, 0x60, 0x90, 0x90, 0x90, 0x60,},
{0x60, 0x90, 0x90, 0x90, 0x70, 0x10, 0x90, 0x90, 0x60,}
}
},
// FONT-4
{
5, 0xf8,
{0, 6, 16, 22, 32, 38},
InitializeFont4,
{
{0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,},
{0x00, 0x70, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x70,},
{0x00, 0x60, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x70,},
{0x00, 0x70, 0x88, 0x08, 0x08, 0x30, 0x40, 0x88, 0xf8,},
{0x00, 0x70, 0x88, 0x08, 0x30, 0x08, 0x08, 0x08, 0xf0,},
{0x00, 0x10, 0x30, 0x50, 0x50, 0x90, 0xf8, 0x10, 0x10,},
{0x00, 0x38, 0x40, 0x60, 0x10, 0x08, 0x08, 0x08, 0xf0,},
{0x00, 0x18, 0x20, 0x40, 0xb0, 0xc8, 0x88, 0x88, 0x70,},
{0x00, 0x70, 0x88, 0x88, 0x10, 0x10, 0x10, 0x20, 0x20,},
{0x00, 0x70, 0x88, 0x88, 0x70, 0x50, 0x88, 0x88, 0x70,},
{0x00, 0x70, 0x88, 0x88, 0x88, 0x78, 0x10, 0x20, 0xc0,}
}
},
// FONT-5
{
5, 0xf8,
{0, 6, 17, 23, 34, 40},
InitializeFont5,
{
{0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,},
{0x00, 0x00, 0x70, 0x88, 0x88, 0x88, 0x88, 0x88, 0x70,},
{0x00, 0x00, 0x20, 0x60, 0x20, 0x20, 0x20, 0x20, 0x20,},
{0x00, 0x00, 0x70, 0x88, 0x08, 0x10, 0x20, 0x40, 0xf8,},
{0x00, 0x00, 0xf8, 0x10, 0x20, 0x10, 0x08, 0x88, 0x70,},
{0x00, 0x00, 0x30, 0x50, 0x50, 0x90, 0xf8, 0x10, 0x10,},
{0x00, 0x00, 0xf8, 0x80, 0xf0, 0x08, 0x08, 0x88, 0x70,},
{0x00, 0x00, 0x30, 0x40, 0xf0, 0x88, 0x88, 0x88, 0x70,},
{0x00, 0x00, 0xf8, 0x08, 0x10, 0x20, 0x20, 0x40, 0x40,},
{0x00, 0x00, 0x70, 0x88, 0x88, 0x70, 0x88, 0x88, 0x70,},
{0x00, 0x00, 0x70, 0x88, 0x88, 0x88, 0x78, 0x10, 0x60,}
}
},
// FONT-6
{
4, 0xf0,
{0, 5, 12, 17, 24, 29},
InitializeFont6,
{
{0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,},
{0x00, 0x00, 0x00, 0x60, 0x90, 0x90, 0x90, 0x90, 0x60,},
{0x00, 0x00, 0x00, 0x20, 0x60, 0x20, 0x20, 0x20, 0x20,},
{0x00, 0x00, 0x00, 0x60, 0x90, 0x10, 0x20, 0x40, 0xf0,},
{0x00, 0x00, 0x00, 0xf0, 0x20, 0x60, 0x10, 0x90, 0x60,},
{0x00, 0x00, 0x00, 0x40, 0x80, 0xa0, 0xa0, 0xf0, 0x20,},
{0x00, 0x00, 0x00, 0xf0, 0x80, 0x60, 0x10, 0x90, 0x60,},
{0x00, 0x00, 0x00, 0x40, 0x80, 0xe0, 0x90, 0x90, 0x60,},
{0x00, 0x00, 0x00, 0xe0, 0x10, 0x10, 0x20, 0x20, 0x40,},
{0x00, 0x00, 0x00, 0x60, 0x90, 0x60, 0x90, 0x90, 0x60,},
{0x00, 0x00, 0x00, 0x60, 0x90, 0x90, 0x70, 0x20, 0x40,}
}
}
};
/**
* コンストラクタ
*/
DispClock::DispClock()
{
ZeroMemory(this, sizeof(*this));
}
/**
* 初期化
*/
void DispClock::Initialize()
{
::pal_makegrad(m_pal32, 4, np2oscfg.clk_color1, np2oscfg.clk_color2);
}
/**
* パレット設定
* @param[in] bpp 色
*/
void DispClock::SetPalettes(UINT bpp)
{
switch (bpp)
{
case 8:
SetPalette8();
break;
case 16:
SetPalette16();
break;
}
}
/**
* 8bpp パレット設定
*/
void DispClock::SetPalette8()
{
for (UINT i = 0; i < 16; i++)
{
UINT nBits = 0;
for (UINT j = 1; j < 0x10; j <<= 1)
{
nBits <<= 8;
if (i & j)
{
nBits |= 1;
}
}
for (UINT j = 0; j < 4; j++)
{
m_pal8[j][i] = nBits * (START_PALORG + j);
}
}
}
/**
* 16bpp パレット設定
*/
void DispClock::SetPalette16()
{
for (UINT i = 0; i < 4; i++)
{
m_pal16[i] = scrnmng_makepal16(m_pal32[i]);
}
}
/**
* リセット
*/
void DispClock::Reset()
{
if (np2oscfg.clk_x)
{
if (np2oscfg.clk_x <= 4)
{
np2oscfg.clk_x = 4;
}
else if (np2oscfg.clk_x <= 6)
{
np2oscfg.clk_x = 6;
}
else
{
np2oscfg.clk_x = 0;
}
}
if (np2oscfg.clk_fnt >= _countof(s_pattern))
{
np2oscfg.clk_fnt = 0;
}
ZeroMemory(m_cTime, sizeof(m_cTime));
ZeroMemory(m_cLastTime, sizeof(m_cLastTime));
ZeroMemory(m_buffer, sizeof(m_buffer));
m_pPattern = &s_pattern[np2oscfg.clk_fnt];
m_cCharaters = np2oscfg.clk_x;
(*m_pPattern->fnInitialize)(m_buffer, m_cCharaters);
Update();
Redraw();
}
/**
* 更新
*/
void DispClock::Update()
{
if ((scrnmng_isfullscreen()) && (m_cCharaters))
{
_SYSTIME st;
timemng_gettime(&st);
UINT8 buf[6];
buf[0] = (st.hour / 10) + 1;
buf[1] = (st.hour % 10) + 1;
buf[2] = (st.minute / 10) + 1;
buf[3] = (st.minute % 10) + 1;
if (m_cCharaters > 4)
{
buf[4] = (st.second / 10) + 1;
buf[5] = (st.second % 10) + 1;
}
UINT8 count = 13;
for (int i = m_cCharaters; i--; )
{
if (m_cTime[i] != buf[i])
{
m_cTime[i] = buf[i];
m_nCounter.b[i] = count;
m_cDirty |= (1 << i);
count += 4;
}
}
}
}
/**
* 再描画
*/
void DispClock::Redraw()
{
m_cDirty = 0x3f;
}
/**
* 描画が必要?
* @retval true 描画中
* @retval false 非描画
*/
bool DispClock::IsDisplayed() const
{
return ((m_cDirty != 0) || (m_nCounter.q != 0));
}
//! オフセット テーブル
static const UINT8 s_dclocky[13] = {0, 1, 1, 2, 2, 2, 2, 3, 3, 3, 3, 3, 3};
/**
* 位置計算
* @param[in] nCount カウント値
* @return オフセット
*/
UINT8 DispClock::CountPos(UINT nCount)
{
if (nCount < _countof(s_dclocky))
{
return s_dclocky[nCount];
}
else
{
return 255;
}
}
/**
* カウントダウン処理
* @param[in] nFrames フレーム数
*/
void DispClock::CountDown(UINT nFrames)
{
if ((m_cCharaters == 0) || (m_nCounter.q == 0))
{
return;
}
if (nFrames == 0)
{
nFrames = 1;
}
for (UINT i = 0; i < m_cCharaters; i++)
{
UINT nRemain = m_nCounter.b[i];
if (nRemain == 0)
{
continue;
}
const UINT8 y = CountPos(nRemain);
if (nFrames < nRemain)
{
nRemain -= nFrames;
}
else
{
nRemain = 0;
}
if (y != CountPos(nRemain))
{
m_cDirty |= (1 << i);
}
m_nCounter.b[i] = nRemain;
}
}
/**
* バッファに描画
* @retval true 更新あり
* @retval false 更新なし
*/
bool DispClock::Make()
{
if ((m_cCharaters == 0) || (m_cDirty == 0))
{
return false;
}
for (UINT i = 0; i < m_cCharaters; i++)
{
if ((m_cDirty & (1 << i)) == 0)
{
continue;
}
UINT nNumber = m_cTime[i];
UINT nPadding = 3;
const UINT nRemain = m_nCounter.b[i];
if (nRemain == 0)
{
m_cLastTime[i] = nNumber;
}
else if (nRemain < _countof(s_dclocky))
{
nPadding -= s_dclocky[nRemain];
}
else
{
nNumber = this->m_cLastTime[i];
}
UINT8* q = m_buffer + (m_pPattern->cPosition[i] >> 3);
const UINT8 cShifter = m_pPattern->cPosition[i] & 7;
const UINT8 cMask0 = ~(m_pPattern->cMask >> cShifter);
const UINT8 cMask1 = ~(m_pPattern->cMask << (8 - cShifter));
for (UINT y = 0; y < nPadding; y++)
{
q[0] = (q[0] & cMask0);
q[1] = (q[1] & cMask1);
q += DCLOCK_YALIGN;
}
const UINT8* p = m_pPattern->font[nNumber];
for (UINT y = 0; y < 9; y++)
{
q[0] = (q[0] & cMask0) | (p[y] >> cShifter);
q[1] = (q[1] & cMask1) | (p[y] << (8 - cShifter));
q += DCLOCK_YALIGN;
}
}
m_cDirty = 0;
return true;
}
/**
* 描画
* @param[in] nBpp 色数
* @param[out] lpBuffer 描画ポインタ
* @param[in] nYAlign アライメント
*/
void DispClock::Draw(UINT nBpp, void* lpBuffer, int nYAlign) const
{
switch (nBpp)
{
case 8:
Draw8(lpBuffer, nYAlign);
break;
case 16:
Draw16(lpBuffer, nYAlign);
break;
case 24:
Draw24(lpBuffer, nYAlign);
break;
case 32:
Draw32(lpBuffer, nYAlign);
break;
}
}
/**
* 描画(8bpp)
* @param[out] lpBuffer 描画ポインタ
* @param[in] nYAlign アライメント
*/
void DispClock::Draw8(void* lpBuffer, int nYAlign) const
{
const UINT8* p = m_buffer;
for (UINT i = 0; i < 4; i++)
{
const UINT32* pPattern = m_pal8[i];
for (UINT j = 0; j < 3; j++)
{
for (UINT x = 0; x < DCLOCK_YALIGN; x++)
{
(static_cast<UINT32*>(lpBuffer))[x * 2 + 0] = pPattern[p[x] >> 4];
(static_cast<UINT32*>(lpBuffer))[x * 2 + 1] = pPattern[p[x] & 15];
}
p += DCLOCK_YALIGN;
lpBuffer = reinterpret_cast<void*>(reinterpret_cast<INTPTR>(lpBuffer) + nYAlign);
}
}
}
/**
* 描画(16bpp)
* @param[out] lpBuffer 描画ポインタ
* @param[in] nYAlign アライメント
*/
void DispClock::Draw16(void* lpBuffer, int nYAlign) const
{
const UINT8* p = m_buffer;
for (UINT i = 0; i < 4; i++)
{
const RGB16 pal = m_pal16[i];
for (UINT j = 0; j < 3; j++)
{
for (UINT x = 0; x < (8 * DCLOCK_YALIGN); x++)
{
(static_cast<UINT16*>(lpBuffer))[x] = (p[x >> 3] & (0x80 >> (x & 7))) ? pal : 0;
}
p += DCLOCK_YALIGN;
lpBuffer = reinterpret_cast<void*>(reinterpret_cast<INTPTR>(lpBuffer) + nYAlign);
}
}
}
/**
* 描画(24bpp)
* @param[out] lpBuffer 描画ポインタ
* @param[in] nYAlign アライメント
*/
void DispClock::Draw24(void* lpBuffer, int nYAlign) const
{
const UINT8* p = m_buffer;
UINT8* q = static_cast<UINT8*>(lpBuffer);
for (UINT i = 0; i < 4; i++)
{
const RGB32 pal = m_pal32[i];
for (UINT j = 0; j < 3; j++)
{
for (UINT x = 0; x < (8 * DCLOCK_YALIGN); x++)
{
if (p[x >> 3] & (0x80 >> (x & 7)))
{
q[0] = pal.p.b;
q[1] = pal.p.g;
q[2] = pal.p.g;
}
else
{
q[0] = 0;
q[1] = 1;
q[2] = 2;
}
q += 3;
}
p += DCLOCK_YALIGN;
q += nYAlign - (8 * DCLOCK_YALIGN) * 3;
}
}
}
/**
* 描画(32bpp)
* @param[out] lpBuffer 描画ポインタ
* @param[in] nYAlign アライメント
*/
void DispClock::Draw32(void* lpBuffer, int nYAlign) const
{
const UINT8* p = m_buffer;
for (UINT i = 0; i < 4; i++)
{
const UINT32 pal = m_pal32[i].d;
for (UINT j = 0; j < 3; j++)
{
for (UINT x = 0; x < (8 * DCLOCK_YALIGN); x++)
{
(static_cast<UINT32*>(lpBuffer))[x] = (p[x >> 3] & (0x80 >> (x & 7))) ? pal : 0;
}
p += DCLOCK_YALIGN;
lpBuffer = reinterpret_cast<void*>(reinterpret_cast<INTPTR>(lpBuffer) + nYAlign);
}
}
}
| 22.729851 | 85 | 0.547836 | whitehara |
956d4445e1b746e5786fb41996266325e3d939d4 | 6,930 | cpp | C++ | recipes-cbc/cbc/cbc/examples/link.cpp | Justin790126/meta-coinor | 0180187c583b3a6fd0a8dac7c85ac1bd89bf8cc9 | [
"MIT"
] | null | null | null | recipes-cbc/cbc/cbc/examples/link.cpp | Justin790126/meta-coinor | 0180187c583b3a6fd0a8dac7c85ac1bd89bf8cc9 | [
"MIT"
] | null | null | null | recipes-cbc/cbc/cbc/examples/link.cpp | Justin790126/meta-coinor | 0180187c583b3a6fd0a8dac7c85ac1bd89bf8cc9 | [
"MIT"
] | null | null | null | // Copyright (C) 2005, International Business Machines
// Corporation and others. All Rights Reserved.
// This code is licensed under the terms of the Eclipse Public License (EPL).
#include <cassert>
#include <iomanip>
#include "CoinPragma.hpp"
// For Branch and bound
#include "OsiSolverInterface.hpp"
#include "CbcModel.hpp"
#include "CoinModel.hpp"
// For Linked Ordered Sets
#include "CbcBranchLink.hpp"
#include "OsiClpSolverInterface.hpp"
#include "CoinTime.hpp"
/************************************************************************
This shows how we can define a new branching method to solve problems with
nonlinearities and discontinuities.
We are going to solve the problem
minimize 10.0*x + y + z - w
where x, y are continuous between 1 and 10, z can take the values 0, 0.1, 0.2 up to 1.0
and w can take the values 0 or 1. There is one constraint
w <= x*z**2 + y*sqrt(z)
One could try to use logarithms to make the problem separable but that is a very
weak formulation as we want to branch on z directly. The answer is the concept of linked
special ordered sets. The generalization with column generation can be even more powerful
but here we are limiting z to discrete values to avoid column generation.
The idea is simple:
A linear variable is a convex combination of its lower bound and upper bound!
If x must lie between 2 and 10 then we can substitute for x as x == 2.0*xl + 10.0*xu where
xl + xu == 1.0. At first this looks cumbersome but if we have xl0, xl1, ... xl10 and corresponding
xu and yl and yu then we can write:
x == sum 2.0*xl[i] + 10.0* xu[i] where sum xl[i] + xu[i] == 1.0
and
x*z**2 == 0.02*xl1 + 0.1*xu1 + 0.08*xl2 + 0.4*xu2 .... + 2.0*xl10 + 10.0*xu10
with similar substitutions for y and y*sqrt(z)
And now the problem is satisfied if w is 0 or 1 and xl[i], xu[i], yl[i] and yu[i] are only
nonzero for one i.
So this is just like a special ordered set of type 1 but on four sets simultaneously.
Also note that convexity requirements for any non-linear functions are not needed.
So we need a new branching method to do that - see CbcBranchLink.?pp
We are going to need a CbcBranchLink method to see whether we are satisfied etc and also to
create another branching object which knows how to fix variables. We might be able to use an
existing method for the latter but let us create two methods CbcLink and
CbcLinkBranchingObject.
For CbcLink we will need the following methods:
Constructot/Destructor
infeasibility - returns 0.0 if feasible otherwise some measure of infeasibility
feasibleRegion - sets bounds to contain current solution
createBranch - creates a CbcLinkBranchingObject
For CbcLinkBranchingObject we need:
Constructor/Destructor
branch - does actual fixing
print - optional for debug purposes.
The easiest way to do this is to cut and paste from CbcBranchActual to get current
SOS stuff and then modify that.
************************************************************************/
int main(int argc, const char *argv[])
{
OsiClpSolverInterface solver1;
// Create model
CoinModel build;
// Keep x,y and z for reporting purposes in rows 0,1,2
// Do these
double value = 1.0;
int row = -1;
// x
row = 0;
build.addColumn(1, &row, &value, 1.0, 10.0, 10.0);
// y
row = 1;
build.addColumn(1, &row, &value, 1.0, 10.0, 1.0);
// z
row = 2;
build.addColumn(1, &row, &value, 0.0, 1.0, 1.0);
// w
row = 3;
build.addColumn(1, &row, &value, 0.0, 1.0, -1.0);
build.setInteger(3);
// Do columns so we know where each is
int i;
for (i = 4; i < 4 + 44; i++)
build.setColumnBounds(i, 0.0, 1.0);
// Now do rows
// x
build.setRowBounds(0, 0.0, 0.0);
for (i = 0; i < 11; i++) {
// xl
build.setElement(0, 4 + 4 * i, -1.0);
// xu
build.setElement(0, 4 + 4 * i + 1, -10.0);
}
// y
build.setRowBounds(1, 0.0, 0.0);
for (i = 0; i < 11; i++) {
// yl
build.setElement(1, 4 + 4 * i + 2, -1.0);
// yu
build.setElement(1, 4 + 4 * i + 3, -10.0);
}
// z - just use x part
build.setRowBounds(2, 0.0, 0.0);
for (i = 0; i < 11; i++) {
// xl
build.setElement(2, 4 + 4 * i, -0.1 * i);
// xu
build.setElement(2, 4 + 4 * i + 1, -0.1 * i);
}
// w <= x*z**2 + y* sqrt(z)
build.setRowBounds(3, -COIN_DBL_MAX, 0.0);
for (i = 0; i < 11; i++) {
double value = 0.1 * i;
// xl * z**2
build.setElement(3, 4 + 4 * i, -1.0 * value * value);
// xu * z**2
build.setElement(3, 4 + 4 * i + 1, -10.0 * value * value);
// yl * sqrt(z)
build.setElement(3, 4 + 4 * i + 2, -1.0 * sqrt(value));
// yu * sqrt(z)
build.setElement(3, 4 + 4 * i + 3, -10.0 * sqrt(value));
}
// and convexity for x and y
// x
build.setRowBounds(4, 1.0, 1.0);
for (i = 0; i < 11; i++) {
// xl
build.setElement(4, 4 + 4 * i, 1.0);
// xu
build.setElement(4, 4 + 4 * i + 1, 1.0);
}
// y
build.setRowBounds(5, 1.0, 1.0);
for (i = 0; i < 11; i++) {
// yl
build.setElement(5, 4 + 4 * i + 2, 1.0);
// yu
build.setElement(5, 4 + 4 * i + 3, 1.0);
}
solver1.loadFromCoinModel(build);
// To make CbcBranchLink simpler assume that all variables with same i are consecutive
double time1 = CoinCpuTime();
solver1.initialSolve();
solver1.writeMps("bad");
CbcModel model(solver1);
model.solver()->setHintParam(OsiDoReducePrint, true, OsiHintTry);
// Although just one set - code as if more
CbcObject **objects = new CbcObject *[1];
/* Format is number in sets, number in each link, first variable in matrix)
and then a weight for each in set to say where to branch.
Finally a set number as ID.
*/
double where[] = { 0.0, 0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9, 1.0 };
objects[0] = new CbcLink(&model, 11, 4, 4, where, 0);
model.addObjects(1, objects);
delete objects[0];
delete[] objects;
// Do complete search
model.branchAndBound();
std::cout << "took " << CoinCpuTime() - time1 << " seconds, "
<< model.getNodeCount() << " nodes with objective "
<< model.getObjValue()
<< (!model.status() ? " Finished" : " Not finished")
<< std::endl;
if (model.getMinimizationObjValue() < 1.0e50) {
const double *solution = model.bestSolution();
// check correct
int which = -1;
for (int i = 0; i < 11; i++) {
for (int j = 4 + 4 * i; j < 4 + 4 * i + 4; j++) {
double value = solution[j];
if (fabs(value) > 1.0e-7) {
if (which == -1)
which = i;
else
assert(which == i);
}
}
}
double x = solution[0];
double y = solution[1];
double z = solution[2];
double w = solution[3];
// check z
assert(fabs(z - 0.1 * ((double)which)) < 1.0e-7);
printf("Optimal solution when x is %g, y %g, z %g and w %g\n",
x, y, z, w);
printf("solution should be %g\n", 10.0 * x + y + z - w);
}
return 0;
}
| 31.5 | 99 | 0.607504 | Justin790126 |
956e8b30e37e2abf5f9820a5a43f4be46f879c76 | 1,641 | cpp | C++ | HW1/Problem 2/main.cpp | alakh125/csci2270 | 84c5f34721f67604c5ddc9ac6028d42f9ee1813f | [
"MIT"
] | null | null | null | HW1/Problem 2/main.cpp | alakh125/csci2270 | 84c5f34721f67604c5ddc9ac6028d42f9ee1813f | [
"MIT"
] | null | null | null | HW1/Problem 2/main.cpp | alakh125/csci2270 | 84c5f34721f67604c5ddc9ac6028d42f9ee1813f | [
"MIT"
] | null | null | null | #include <iostream>
#include <fstream>
#include <string>
#include <sstream>
struct Park{
std::string parkname;
std::string state;
int area;
};
void addPark (Park parks[], std::string parkname, std::string state, int area, int length);
void printList(const Park parks[], int length);
using namespace std;
int main(int argc, char** argv){
string iFileName = argv[0];
string oFileName = argv[1];
int lowerBound = stoi(argv[2]);
int upperBound = stoi(argv[3]);
Park parks[100];
ifstream iFile;
iFile.open(iFileName);
string line,parkname,state,areaTemp;
int area;
int i = 0;
while(getline(iFile,line)){
istringstream s(line);
getline(s,parkname,',');
getline(s,state,',');
getline(s,areaTemp,',');
area = stoi(areaTemp);
addPark(parks,parkname,state,area,i);
i++;
}
printList(parks, i);
ofstream oFile;
oFile.open(oFileName);
for(int j = 0; j < i; j++){
Park a = parks[j];
if(a.area >= lowerBound && a.area <= upperBound){
oFile << a.parkname << ',' << a.state << ',' << a.area << endl;
}
}
}
void addPark(Park parks[], string parkname, string state, int area, int length){
Park a;
a.parkname = parkname;
a.state = state;
a.area = area;
parks[length] = a;
}
using namespace std;
void printList(const Park parks[], int length){
for(int i = 0; i < length; i++){
Park a = parks[i];
cout << a.parkname << " [" << a.state << "] area: " << a.area << endl;
}
}
| 26.047619 | 92 | 0.550274 | alakh125 |
9571c7f718f9d07933026224b6f5dd33639490cb | 13,042 | cpp | C++ | DFNs/BundleAdjustment/SvdDecomposition.cpp | H2020-InFuse/cdff | e55fd48f9a909d0c274c3dfa4fe2704bc5071542 | [
"BSD-2-Clause"
] | 7 | 2019-02-26T15:09:50.000Z | 2021-09-30T07:39:01.000Z | DFNs/BundleAdjustment/SvdDecomposition.cpp | H2020-InFuse/cdff | e55fd48f9a909d0c274c3dfa4fe2704bc5071542 | [
"BSD-2-Clause"
] | null | null | null | DFNs/BundleAdjustment/SvdDecomposition.cpp | H2020-InFuse/cdff | e55fd48f9a909d0c274c3dfa4fe2704bc5071542 | [
"BSD-2-Clause"
] | 1 | 2020-12-06T12:09:05.000Z | 2020-12-06T12:09:05.000Z | /**
* @author Alessandro Bianco
*/
/**
* @addtogroup DFNs
* @{
*/
#include "SvdDecomposition.hpp"
#include <Converters/FrameToMatConverter.hpp>
#include <Macros/YamlcppMacros.hpp>
#include <Errors/Assert.hpp>
#include <stdlib.h>
#include <fstream>
using namespace Helpers;
using namespace Converters;
using namespace CorrespondenceMap2DWrapper;
using namespace PoseWrapper;
using namespace BaseTypesWrapper;
namespace CDFF
{
namespace DFN
{
namespace BundleAdjustment
{
SvdDecomposition::SvdDecomposition()
{
parameters = DEFAULT_PARAMETERS;
parametersHelper.AddParameter<float>("LeftCameraMatrix", "FocalLengthX", parameters.leftCameraMatrix.focalLengthX, DEFAULT_PARAMETERS.leftCameraMatrix.focalLengthX);
parametersHelper.AddParameter<float>("LeftCameraMatrix", "FocalLengthY", parameters.leftCameraMatrix.focalLengthY, DEFAULT_PARAMETERS.leftCameraMatrix.focalLengthY);
parametersHelper.AddParameter<float>("LeftCameraMatrix", "PrincipalPointX", parameters.leftCameraMatrix.principalPointX, DEFAULT_PARAMETERS.leftCameraMatrix.principalPointX);
parametersHelper.AddParameter<float>("LeftCameraMatrix", "PrincipalPointY", parameters.leftCameraMatrix.principalPointY, DEFAULT_PARAMETERS.leftCameraMatrix.principalPointY);
parametersHelper.AddParameter<float>("RightCameraMatrix", "FocalLengthX", parameters.rightCameraMatrix.focalLengthX, DEFAULT_PARAMETERS.rightCameraMatrix.focalLengthX);
parametersHelper.AddParameter<float>("RightCameraMatrix", "FocalLengthY", parameters.rightCameraMatrix.focalLengthY, DEFAULT_PARAMETERS.rightCameraMatrix.focalLengthY);
parametersHelper.AddParameter<float>("RightCameraMatrix", "PrincipalPointX", parameters.rightCameraMatrix.principalPointX, DEFAULT_PARAMETERS.rightCameraMatrix.principalPointX);
parametersHelper.AddParameter<float>("RightCameraMatrix", "PrincipalPointY", parameters.rightCameraMatrix.principalPointY, DEFAULT_PARAMETERS.rightCameraMatrix.principalPointY);
parametersHelper.AddParameter<float>("GeneralParameters", "Baseline", parameters.baseline, DEFAULT_PARAMETERS.baseline);
configurationFilePath = "";
}
SvdDecomposition::~SvdDecomposition()
{
}
void SvdDecomposition::configure()
{
parametersHelper.ReadFile(configurationFilePath);
ValidateParameters();
leftCameraMatrix = CameraMatrixToCvMatrix(parameters.leftCameraMatrix);
rightCameraMatrix = CameraMatrixToCvMatrix(parameters.rightCameraMatrix);
leftCameraMatrixInverse = leftCameraMatrix.inv();
rightCameraMatrixInverse = rightCameraMatrix.inv();
leftAbsoluteConicImage = leftCameraMatrix.t() * leftCameraMatrixInverse;
rightAbsoluteConicImage = rightCameraMatrix.t() * rightCameraMatrixInverse;
}
void SvdDecomposition::process()
{
cv::Mat measurementMatrix = correspondencesSequenceConverter.Convert(&inCorrespondenceMapsSequence);
if (measurementMatrix.cols < 4) //Not enough points available.
{
outSuccess = false;
return;
}
cv::Mat centroidMatrix = ComputeMeasuresCentroid(measurementMatrix);
cv::Mat translationMatrix = ComputeTranslationMatrix(centroidMatrix);
CentreMeasurementMatrix(centroidMatrix, measurementMatrix);
cv::Mat compatibleRotationMatrix, compatiblePositionMatrix;
DecomposeMeasurementMatrix(measurementMatrix, compatibleRotationMatrix, compatiblePositionMatrix);
ConvertRotationTranslationMatricesToPosesSequence(translationMatrix, compatibleRotationMatrix, outPosesSequence);
outError = -1;
outSuccess = true;
}
const SvdDecomposition::SvdDecompositionOptionsSet SvdDecomposition::DEFAULT_PARAMETERS =
{
//.leftCameraMatrix =
{
/*.focalLengthX =*/ 1,
/*.focalLengthY =*/ 1,
/*.principalPointX =*/ 0,
/*.principalPointY =*/ 0,
},
//.rightCameraMatrix =
{
/*.focalLengthX =*/ 1,
/*.focalLengthY =*/ 1,
/*.principalPointX =*/ 0,
/*.principalPointY =*/ 0,
},
/*.baseline =*/ 1.0
};
cv::Mat SvdDecomposition::CameraMatrixToCvMatrix(const CameraMatrix& cameraMatrix)
{
cv::Mat cvCameraMatrix(3, 3, CV_32FC1, cv::Scalar(0));
cvCameraMatrix.at<float>(0,0) = cameraMatrix.focalLengthX;
cvCameraMatrix.at<float>(1,1) = cameraMatrix.focalLengthY;
cvCameraMatrix.at<float>(2,0) = cameraMatrix.principalPointX;
cvCameraMatrix.at<float>(2,1) = cameraMatrix.principalPointY;
cvCameraMatrix.at<float>(2,2) = 1.0;
return cvCameraMatrix;
}
void SvdDecomposition::ConvertRotationTranslationMatricesToPosesSequence(cv::Mat translationMatrix, cv::Mat rotationMatrix, PoseWrapper::Poses3DSequence& posesSequence)
{
ASSERT( translationMatrix.rows == rotationMatrix.rows/2, "Translation Matrix and rotation Matrix sizes do not match");
// the rotation matrix is an affine rotation matrix, it needs to be multipled on the right by an appropriate 3x3 matrix.
// ComputeMetricRotationMatrix finds the matrix according to section 10.4.2 of "Multiple View Geometry in Computer Vision" by Richard Hartley, and Andrew Zisserman.
cv::Mat finalRotationMatrix, firstMetricRotationMatrix;
{
// x = M X + t for the first camera matrix, M is given by the first two row of the rotation matrix and t is given by the first centroid;
// The rotation matrix of the projective 3x4 transformation matrix P = [M'|m]. M' is given by the first two columns of M concatenated with t, concatenated with a final row (0, 0, 1).
int firstPoseIndex = 0;
cv::Mat firstProjectionMatrixColumns[4];
firstProjectionMatrixColumns[0] = (cv::Mat_<float>(3, 1, CV_32FC1) << rotationMatrix.at<float>(2*firstPoseIndex, 0), rotationMatrix.at<float>(2*firstPoseIndex+1, 0), 0);
firstProjectionMatrixColumns[1] = (cv::Mat_<float>(3, 1, CV_32FC1) << rotationMatrix.at<float>(2*firstPoseIndex, 1), rotationMatrix.at<float>(2*firstPoseIndex+1, 1), 0);
firstProjectionMatrixColumns[2] = (cv::Mat_<float>(3, 1, CV_32FC1) << translationMatrix.at<float>(firstPoseIndex, 0), translationMatrix.at<float>(firstPoseIndex, 1), 1);
firstProjectionMatrixColumns[3] = (cv::Mat_<float>(3, 1, CV_32FC1) << rotationMatrix.at<float>(2*firstPoseIndex, 2), rotationMatrix.at<float>(2*firstPoseIndex+1, 2), 0);
cv::Mat firstProjectionMatrix;
cv::hconcat(firstProjectionMatrixColumns, 4, firstProjectionMatrix);
firstMetricRotationMatrix = ComputeMetricRotationMatrix(firstProjectionMatrix(cv::Rect(0, 0, 3, 3)), firstPoseIndex);
finalRotationMatrix = rotationMatrix * firstMetricRotationMatrix;
}
AffineTransform inverseOfFirstCameraTransform;
for(int poseIndex = 0; poseIndex < translationMatrix.rows; poseIndex++)
{
Eigen::Matrix3f eigenRotationMatrix;
eigenRotationMatrix << finalRotationMatrix.at<float>(2*poseIndex, 0), finalRotationMatrix.at<float>(2*poseIndex, 1), finalRotationMatrix.at<float>(2*poseIndex, 2),
finalRotationMatrix.at<float>(2*poseIndex+1, 0), finalRotationMatrix.at<float>(2*poseIndex+1, 1), finalRotationMatrix.at<float>(2*poseIndex+1, 2),
0, 0, 0;
Eigen::Quaternion<float> eigenRotation(eigenRotationMatrix);
eigenRotation.normalize();
Eigen::Translation<float, 3> translation(translationMatrix.at<float>(poseIndex,0), translationMatrix.at<float>(poseIndex,1), translationMatrix.at<float>(poseIndex, 2));
AffineTransform affineTransform = translation * eigenRotation;
// We put the transforms in the reference frame of the first camera.
if (poseIndex == 0)
{
inverseOfFirstCameraTransform = affineTransform.inverse();
}
affineTransform = affineTransform * inverseOfFirstCameraTransform;
AffineTransform cameraTransform = affineTransform.inverse();
Pose3D newPose;
SetPosition(newPose, cameraTransform.translation()(0), cameraTransform.translation()(1), cameraTransform.translation()(2));
Eigen::Quaternion<float> outputQuaternion( cameraTransform.rotation() );
SetOrientation(newPose, outputQuaternion.x(), outputQuaternion.y(), outputQuaternion.z(), outputQuaternion.w());
PRINT_TO_LOG("newPose", ToString(newPose));
AddPose(posesSequence, newPose);
}
}
void SvdDecomposition::DecomposeMeasurementMatrix(cv::Mat measurementMatrix, cv::Mat& compatibleRotationMatrix, cv::Mat& compatiblePositionMatrix)
{
//This is the algorithm of Tomasi and Kanade as describe in page 437 of "Multiple View Geometry in Computer Vision" by Richard Hartley, and Andrew Zisserman.
cv::Mat leftSingularVectorsMatrix, singularValuesMatrix, rightSingularVectorsMatrix;
cv::SVD::compute(measurementMatrix, singularValuesMatrix, leftSingularVectorsMatrix, rightSingularVectorsMatrix);
ASSERT(singularValuesMatrix.cols == 1 && singularValuesMatrix.rows == measurementMatrix.cols && singularValuesMatrix.type() == CV_32FC1, "Something went wrong in the svd decomposition");
ASSERT(leftSingularVectorsMatrix.rows == measurementMatrix.rows, "Unexpected result in svd decomposition");
cv::Mat rotationMatrixColumnsList[3];
for(int columnIndex = 0; columnIndex < 3; columnIndex++)
{
rotationMatrixColumnsList[columnIndex] = leftSingularVectorsMatrix(cv::Rect(columnIndex, 0, 1, leftSingularVectorsMatrix.rows)) * singularValuesMatrix.at<float>(columnIndex, 0);
}
cv::hconcat(rotationMatrixColumnsList, 3, compatibleRotationMatrix);
compatiblePositionMatrix = rightSingularVectorsMatrix( cv::Rect(0, 0, rightSingularVectorsMatrix.cols, 3) );
}
cv::Mat SvdDecomposition::ComputeTranslationMatrix(cv::Mat centroidMatrix)
{
//the centroid matrix contains the translation direction vectors. In order to find the vector expressed in meters we use the measure of the baseline provided as an input parameter.
float estimatedBaselineX = centroidMatrix.at<float>(0, 0) - centroidMatrix.at<float>(1, 0);
float estimatedBaselineY = centroidMatrix.at<float>(0, 1) - centroidMatrix.at<float>(1, 1);
float estimatedBaseline = std::sqrt( estimatedBaselineX*estimatedBaselineX + estimatedBaselineY*estimatedBaselineY);
float metricCoefficient = parameters.baseline / estimatedBaseline;
cv::Mat temporaryImagesList[2] = {centroidMatrix, cv::Mat::ones(centroidMatrix.rows, 1, CV_32FC1)};
cv::Mat translationMatrix;
cv::hconcat(temporaryImagesList, 2, translationMatrix);
translationMatrix = translationMatrix * metricCoefficient;
return translationMatrix;
}
cv::Mat SvdDecomposition::ComputeMeasuresCentroid(cv::Mat measurementMatrix)
{
cv::Mat centroidMatrix(measurementMatrix.rows/2, 2, CV_32FC1);
for(int imageIndex = 0; imageIndex < centroidMatrix.rows; imageIndex++)
{
float centroidX = 0;
float centroidY = 0;
for(int measureIndex = 0; measureIndex < measurementMatrix.cols; measureIndex++)
{
centroidX += measurementMatrix.at<float>(2*imageIndex, measureIndex);
centroidY += measurementMatrix.at<float>(2*imageIndex+1, measureIndex);
}
centroidX /= (float)measurementMatrix.cols;
centroidY /= (float)measurementMatrix.cols;
centroidMatrix.at<float>(imageIndex, 0) = centroidX;
centroidMatrix.at<float>(imageIndex, 1) = centroidY;
}
return centroidMatrix;
}
void SvdDecomposition::CentreMeasurementMatrix(cv::Mat centroidMatrix, cv::Mat& measurementMatrix)
{
ASSERT( centroidMatrix.rows == measurementMatrix.rows/2, "Centroid Matrix and measurement Matrix sizes do not match");
for(int imageIndex = 0; imageIndex < centroidMatrix.rows; imageIndex++)
{
float centroidX = centroidMatrix.at<float>(imageIndex, 0);
float centroidY = centroidMatrix.at<float>(imageIndex, 1);
for(int measureIndex = 0; measureIndex < measurementMatrix.cols; measureIndex++)
{
measurementMatrix.at<float>(2*imageIndex, measureIndex) -= centroidX;
measurementMatrix.at<float>(2*imageIndex+1, measureIndex) -= centroidY;
}
}
}
cv::Mat SvdDecomposition::ComputeMetricRotationMatrix(cv::Mat rotationMatrix, int poseIndex)
{
// computation of the metric matrix according to section 10.4.2 of "Multiple View Geometry in Computer Vision" by Richard Hartley, and Andrew Zisserman.
ASSERT(rotationMatrix.cols == 3 && rotationMatrix.rows == 3 && rotationMatrix.type() == CV_32FC1, "unexpected rotation matrix format");
cv::Mat matrixToDecompose;
if (poseIndex % 2 == 0)
{
matrixToDecompose = ( rotationMatrix.t() * leftAbsoluteConicImage * rotationMatrix).inv();
}
else
{
matrixToDecompose = ( rotationMatrix.t() * rightAbsoluteConicImage * rotationMatrix).inv();
}
cv::Cholesky((float*)matrixToDecompose.ptr(), matrixToDecompose.cols*sizeof(float), 3, NULL, 0, 0);
return matrixToDecompose;
}
void SvdDecomposition::ValidateParameters()
{
ASSERT(parameters.leftCameraMatrix.focalLengthX > 0 && parameters.leftCameraMatrix.focalLengthY > 0, "SvdDecomposition Configuration error: left focal length has to be positive");
ASSERT(parameters.rightCameraMatrix.focalLengthX > 0 && parameters.rightCameraMatrix.focalLengthY > 0, "SvdDecomposition Configuration error: right focal length has to be positive");
ASSERT(parameters.baseline > 0, "SvdDecomposition Configuration error: stereo camera baseline has to be positive");
}
void SvdDecomposition::ValidateInputs()
{
int n = GetNumberOfCorrespondenceMaps(inCorrespondenceMapsSequence);
ASSERT( n == 6 || n == 15 || n == 28, "SvdDecomposition Error: you should provide correspondence maps for either 2, 3 or 4 pairs of stereo camera images");
}
}
}
}
/** @} */
| 46.74552 | 187 | 0.783392 | H2020-InFuse |
9576856d827def72924012e2ecb87a8ab7648b67 | 13,033 | cpp | C++ | libs/fnd/type_traits/test/src/unit_test_fnd_type_traits_arithmetic_promote.cpp | myoukaku/bksge | 0f8b60e475a3f1709723906e4796b5e60decf06e | [
"MIT"
] | 4 | 2018-06-10T13:35:32.000Z | 2021-06-03T14:27:41.000Z | libs/fnd/type_traits/test/src/unit_test_fnd_type_traits_arithmetic_promote.cpp | myoukaku/bksge | 0f8b60e475a3f1709723906e4796b5e60decf06e | [
"MIT"
] | 566 | 2017-01-31T05:36:09.000Z | 2022-02-09T05:04:37.000Z | libs/fnd/type_traits/test/src/unit_test_fnd_type_traits_arithmetic_promote.cpp | myoukaku/bksge | 0f8b60e475a3f1709723906e4796b5e60decf06e | [
"MIT"
] | 1 | 2018-07-05T04:40:53.000Z | 2018-07-05T04:40:53.000Z | /**
* @file unit_test_fnd_type_traits_arithmetic_promote.cpp
*
* @brief arithmetic_promote のテスト
*
* @author myoukaku
*/
#include <bksge/fnd/type_traits/arithmetic_promote.hpp>
#include <bksge/fnd/type_traits/is_same.hpp>
#include <gtest/gtest.h>
#define BKSGE_ARITHMETIC_PROMOTE_TEST(T, ...) \
static_assert(bksge::is_same<T, bksge::arithmetic_promote<__VA_ARGS__>::type>::value, ""); \
static_assert(bksge::is_same<T, bksge::arithmetic_promote_t<__VA_ARGS__>>::value, "")
BKSGE_ARITHMETIC_PROMOTE_TEST(float, float);
BKSGE_ARITHMETIC_PROMOTE_TEST(double, double);
BKSGE_ARITHMETIC_PROMOTE_TEST(long double, long double);
BKSGE_ARITHMETIC_PROMOTE_TEST(int, int);
BKSGE_ARITHMETIC_PROMOTE_TEST(char, char);
BKSGE_ARITHMETIC_PROMOTE_TEST(short, short);
BKSGE_ARITHMETIC_PROMOTE_TEST(long, long);
BKSGE_ARITHMETIC_PROMOTE_TEST(long long, long long);
BKSGE_ARITHMETIC_PROMOTE_TEST(unsigned int, unsigned int);
BKSGE_ARITHMETIC_PROMOTE_TEST(unsigned char, unsigned char);
BKSGE_ARITHMETIC_PROMOTE_TEST(unsigned short, unsigned short);
BKSGE_ARITHMETIC_PROMOTE_TEST(unsigned long, unsigned long);
BKSGE_ARITHMETIC_PROMOTE_TEST(unsigned long long, unsigned long long);
BKSGE_ARITHMETIC_PROMOTE_TEST(float, float, float);
BKSGE_ARITHMETIC_PROMOTE_TEST(double, float, double);
BKSGE_ARITHMETIC_PROMOTE_TEST(long double, float, long double);
BKSGE_ARITHMETIC_PROMOTE_TEST(float, float, int);
BKSGE_ARITHMETIC_PROMOTE_TEST(float, float, char);
BKSGE_ARITHMETIC_PROMOTE_TEST(float, float, unsigned int);
BKSGE_ARITHMETIC_PROMOTE_TEST(float, float, unsigned char);
BKSGE_ARITHMETIC_PROMOTE_TEST(double, double, float);
BKSGE_ARITHMETIC_PROMOTE_TEST(double, double, double);
BKSGE_ARITHMETIC_PROMOTE_TEST(long double, double, long double);
BKSGE_ARITHMETIC_PROMOTE_TEST(double, double, int);
BKSGE_ARITHMETIC_PROMOTE_TEST(double, double, char);
BKSGE_ARITHMETIC_PROMOTE_TEST(double, double, unsigned int);
BKSGE_ARITHMETIC_PROMOTE_TEST(double, double, unsigned char);
BKSGE_ARITHMETIC_PROMOTE_TEST(long double, long double, float);
BKSGE_ARITHMETIC_PROMOTE_TEST(long double, long double, double);
BKSGE_ARITHMETIC_PROMOTE_TEST(long double, long double, long double);
BKSGE_ARITHMETIC_PROMOTE_TEST(long double, long double, int);
BKSGE_ARITHMETIC_PROMOTE_TEST(long double, long double, char);
BKSGE_ARITHMETIC_PROMOTE_TEST(long double, long double, unsigned int);
BKSGE_ARITHMETIC_PROMOTE_TEST(long double, long double, unsigned char);
BKSGE_ARITHMETIC_PROMOTE_TEST(float, int, float);
BKSGE_ARITHMETIC_PROMOTE_TEST(double, int, double);
BKSGE_ARITHMETIC_PROMOTE_TEST(long double, int, long double);
BKSGE_ARITHMETIC_PROMOTE_TEST(int, int, int);
BKSGE_ARITHMETIC_PROMOTE_TEST(int, int, char);
BKSGE_ARITHMETIC_PROMOTE_TEST(unsigned int, int, unsigned int);
BKSGE_ARITHMETIC_PROMOTE_TEST(int, int, unsigned char);
BKSGE_ARITHMETIC_PROMOTE_TEST(float, char, float);
BKSGE_ARITHMETIC_PROMOTE_TEST(double, char, double);
BKSGE_ARITHMETIC_PROMOTE_TEST(long double, char, long double);
BKSGE_ARITHMETIC_PROMOTE_TEST(int, char, int);
BKSGE_ARITHMETIC_PROMOTE_TEST(int, char, char);
BKSGE_ARITHMETIC_PROMOTE_TEST(unsigned int, char, unsigned int);
BKSGE_ARITHMETIC_PROMOTE_TEST(int, char, unsigned char);
BKSGE_ARITHMETIC_PROMOTE_TEST(float, unsigned int, float);
BKSGE_ARITHMETIC_PROMOTE_TEST(double, unsigned int, double);
BKSGE_ARITHMETIC_PROMOTE_TEST(long double, unsigned int, long double);
BKSGE_ARITHMETIC_PROMOTE_TEST(unsigned int, unsigned int, int);
BKSGE_ARITHMETIC_PROMOTE_TEST(unsigned int, unsigned int, char);
BKSGE_ARITHMETIC_PROMOTE_TEST(unsigned int, unsigned int, unsigned int);
BKSGE_ARITHMETIC_PROMOTE_TEST(unsigned int, unsigned int, unsigned char);
BKSGE_ARITHMETIC_PROMOTE_TEST(float, unsigned char, float);
BKSGE_ARITHMETIC_PROMOTE_TEST(double, unsigned char, double);
BKSGE_ARITHMETIC_PROMOTE_TEST(long double, unsigned char, long double);
BKSGE_ARITHMETIC_PROMOTE_TEST(int, unsigned char, int);
BKSGE_ARITHMETIC_PROMOTE_TEST(int, unsigned char, char);
BKSGE_ARITHMETIC_PROMOTE_TEST(unsigned int, unsigned char, unsigned int);
BKSGE_ARITHMETIC_PROMOTE_TEST(int, unsigned char, unsigned char);
BKSGE_ARITHMETIC_PROMOTE_TEST(float, float, float, float);
BKSGE_ARITHMETIC_PROMOTE_TEST(double, float, float, double);
BKSGE_ARITHMETIC_PROMOTE_TEST(long double, float, float, long double);
BKSGE_ARITHMETIC_PROMOTE_TEST(float, float, float, int);
BKSGE_ARITHMETIC_PROMOTE_TEST(float, float, float, char);
BKSGE_ARITHMETIC_PROMOTE_TEST(double, float, double, float);
BKSGE_ARITHMETIC_PROMOTE_TEST(double, float, double, double);
BKSGE_ARITHMETIC_PROMOTE_TEST(long double, float, double, long double);
BKSGE_ARITHMETIC_PROMOTE_TEST(double, float, double, int);
BKSGE_ARITHMETIC_PROMOTE_TEST(double, float, double, char);
BKSGE_ARITHMETIC_PROMOTE_TEST(long double, float, long double, float);
BKSGE_ARITHMETIC_PROMOTE_TEST(long double, float, long double, double);
BKSGE_ARITHMETIC_PROMOTE_TEST(long double, float, long double, long double);
BKSGE_ARITHMETIC_PROMOTE_TEST(long double, float, long double, int);
BKSGE_ARITHMETIC_PROMOTE_TEST(long double, float, long double, char);
BKSGE_ARITHMETIC_PROMOTE_TEST(float, float, int, float);
BKSGE_ARITHMETIC_PROMOTE_TEST(double, float, int, double);
BKSGE_ARITHMETIC_PROMOTE_TEST(long double, float, int, long double);
BKSGE_ARITHMETIC_PROMOTE_TEST(float, float, int, int);
BKSGE_ARITHMETIC_PROMOTE_TEST(float, float, int, char);
BKSGE_ARITHMETIC_PROMOTE_TEST(float, float, char, float);
BKSGE_ARITHMETIC_PROMOTE_TEST(double, float, char, double);
BKSGE_ARITHMETIC_PROMOTE_TEST(long double, float, char, long double);
BKSGE_ARITHMETIC_PROMOTE_TEST(float, float, char, int);
BKSGE_ARITHMETIC_PROMOTE_TEST(float, float, char, char);
BKSGE_ARITHMETIC_PROMOTE_TEST(double, double, float, float);
BKSGE_ARITHMETIC_PROMOTE_TEST(double, double, float, double);
BKSGE_ARITHMETIC_PROMOTE_TEST(long double, double, float, long double);
BKSGE_ARITHMETIC_PROMOTE_TEST(double, double, float, int);
BKSGE_ARITHMETIC_PROMOTE_TEST(double, double, float, char);
BKSGE_ARITHMETIC_PROMOTE_TEST(double, double, double, float);
BKSGE_ARITHMETIC_PROMOTE_TEST(double, double, double, double);
BKSGE_ARITHMETIC_PROMOTE_TEST(long double, double, double, long double);
BKSGE_ARITHMETIC_PROMOTE_TEST(double, double, double, int);
BKSGE_ARITHMETIC_PROMOTE_TEST(double, double, double, char);
BKSGE_ARITHMETIC_PROMOTE_TEST(long double, double, long double, float);
BKSGE_ARITHMETIC_PROMOTE_TEST(long double, double, long double, double);
BKSGE_ARITHMETIC_PROMOTE_TEST(long double, double, long double, long double);
BKSGE_ARITHMETIC_PROMOTE_TEST(long double, double, long double, int);
BKSGE_ARITHMETIC_PROMOTE_TEST(long double, double, long double, char);
BKSGE_ARITHMETIC_PROMOTE_TEST(double, double, int, float);
BKSGE_ARITHMETIC_PROMOTE_TEST(double, double, int, double);
BKSGE_ARITHMETIC_PROMOTE_TEST(long double, double, int, long double);
BKSGE_ARITHMETIC_PROMOTE_TEST(double, double, int, int);
BKSGE_ARITHMETIC_PROMOTE_TEST(double, double, int, char);
BKSGE_ARITHMETIC_PROMOTE_TEST(double, double, char, float);
BKSGE_ARITHMETIC_PROMOTE_TEST(double, double, char, double);
BKSGE_ARITHMETIC_PROMOTE_TEST(long double, double, char, long double);
BKSGE_ARITHMETIC_PROMOTE_TEST(double, double, char, int);
BKSGE_ARITHMETIC_PROMOTE_TEST(double, double, char, char);
BKSGE_ARITHMETIC_PROMOTE_TEST(long double, long double, float, float);
BKSGE_ARITHMETIC_PROMOTE_TEST(long double, long double, float, double);
BKSGE_ARITHMETIC_PROMOTE_TEST(long double, long double, float, long double);
BKSGE_ARITHMETIC_PROMOTE_TEST(long double, long double, float, int);
BKSGE_ARITHMETIC_PROMOTE_TEST(long double, long double, float, char);
BKSGE_ARITHMETIC_PROMOTE_TEST(long double, long double, double, float);
BKSGE_ARITHMETIC_PROMOTE_TEST(long double, long double, double, double);
BKSGE_ARITHMETIC_PROMOTE_TEST(long double, long double, double, long double);
BKSGE_ARITHMETIC_PROMOTE_TEST(long double, long double, double, int);
BKSGE_ARITHMETIC_PROMOTE_TEST(long double, long double, double, char);
BKSGE_ARITHMETIC_PROMOTE_TEST(long double, long double, long double, float);
BKSGE_ARITHMETIC_PROMOTE_TEST(long double, long double, long double, double);
BKSGE_ARITHMETIC_PROMOTE_TEST(long double, long double, long double, long double);
BKSGE_ARITHMETIC_PROMOTE_TEST(long double, long double, long double, int);
BKSGE_ARITHMETIC_PROMOTE_TEST(long double, long double, long double, char);
BKSGE_ARITHMETIC_PROMOTE_TEST(long double, long double, int, float);
BKSGE_ARITHMETIC_PROMOTE_TEST(long double, long double, int, double);
BKSGE_ARITHMETIC_PROMOTE_TEST(long double, long double, int, long double);
BKSGE_ARITHMETIC_PROMOTE_TEST(long double, long double, int, int);
BKSGE_ARITHMETIC_PROMOTE_TEST(long double, long double, int, char);
BKSGE_ARITHMETIC_PROMOTE_TEST(long double, long double, char, float);
BKSGE_ARITHMETIC_PROMOTE_TEST(long double, long double, char, double);
BKSGE_ARITHMETIC_PROMOTE_TEST(long double, long double, char, long double);
BKSGE_ARITHMETIC_PROMOTE_TEST(long double, long double, char, int);
BKSGE_ARITHMETIC_PROMOTE_TEST(long double, long double, char, char);
BKSGE_ARITHMETIC_PROMOTE_TEST(float, int, float, float);
BKSGE_ARITHMETIC_PROMOTE_TEST(double, int, float, double);
BKSGE_ARITHMETIC_PROMOTE_TEST(long double, int, float, long double);
BKSGE_ARITHMETIC_PROMOTE_TEST(float, int, float, int);
BKSGE_ARITHMETIC_PROMOTE_TEST(float, int, float, char);
BKSGE_ARITHMETIC_PROMOTE_TEST(double, int, double, float);
BKSGE_ARITHMETIC_PROMOTE_TEST(double, int, double, double);
BKSGE_ARITHMETIC_PROMOTE_TEST(long double, int, double, long double);
BKSGE_ARITHMETIC_PROMOTE_TEST(double, int, double, int);
BKSGE_ARITHMETIC_PROMOTE_TEST(double, int, double, char);
BKSGE_ARITHMETIC_PROMOTE_TEST(long double, int, long double, float);
BKSGE_ARITHMETIC_PROMOTE_TEST(long double, int, long double, double);
BKSGE_ARITHMETIC_PROMOTE_TEST(long double, int, long double, long double);
BKSGE_ARITHMETIC_PROMOTE_TEST(long double, int, long double, int);
BKSGE_ARITHMETIC_PROMOTE_TEST(long double, int, long double, char);
BKSGE_ARITHMETIC_PROMOTE_TEST(float, int, int, float);
BKSGE_ARITHMETIC_PROMOTE_TEST(double, int, int, double);
BKSGE_ARITHMETIC_PROMOTE_TEST(long double, int, int, long double);
BKSGE_ARITHMETIC_PROMOTE_TEST(int, int, int, int);
BKSGE_ARITHMETIC_PROMOTE_TEST(int, int, int, char);
BKSGE_ARITHMETIC_PROMOTE_TEST(float, int, char, float);
BKSGE_ARITHMETIC_PROMOTE_TEST(double, int, char, double);
BKSGE_ARITHMETIC_PROMOTE_TEST(long double, int, char, long double);
BKSGE_ARITHMETIC_PROMOTE_TEST(int, int, char, int);
BKSGE_ARITHMETIC_PROMOTE_TEST(int, int, char, char);
BKSGE_ARITHMETIC_PROMOTE_TEST(float, char, float, float);
BKSGE_ARITHMETIC_PROMOTE_TEST(double, char, float, double);
BKSGE_ARITHMETIC_PROMOTE_TEST(long double, char, float, long double);
BKSGE_ARITHMETIC_PROMOTE_TEST(float, char, float, int);
BKSGE_ARITHMETIC_PROMOTE_TEST(float, char, float, char);
BKSGE_ARITHMETIC_PROMOTE_TEST(double, char, double, float);
BKSGE_ARITHMETIC_PROMOTE_TEST(double, char, double, double);
BKSGE_ARITHMETIC_PROMOTE_TEST(long double, char, double, long double);
BKSGE_ARITHMETIC_PROMOTE_TEST(double, char, double, int);
BKSGE_ARITHMETIC_PROMOTE_TEST(double, char, double, char);
BKSGE_ARITHMETIC_PROMOTE_TEST(long double, char, long double, float);
BKSGE_ARITHMETIC_PROMOTE_TEST(long double, char, long double, double);
BKSGE_ARITHMETIC_PROMOTE_TEST(long double, char, long double, long double);
BKSGE_ARITHMETIC_PROMOTE_TEST(long double, char, long double, int);
BKSGE_ARITHMETIC_PROMOTE_TEST(long double, char, long double, char);
BKSGE_ARITHMETIC_PROMOTE_TEST(float, char, int, float);
BKSGE_ARITHMETIC_PROMOTE_TEST(double, char, int, double);
BKSGE_ARITHMETIC_PROMOTE_TEST(long double, char, int, long double);
BKSGE_ARITHMETIC_PROMOTE_TEST(int, char, int, int);
BKSGE_ARITHMETIC_PROMOTE_TEST(int, char, int, char);
BKSGE_ARITHMETIC_PROMOTE_TEST(float, char, char, float);
BKSGE_ARITHMETIC_PROMOTE_TEST(double, char, char, double);
BKSGE_ARITHMETIC_PROMOTE_TEST(long double, char, char, long double);
BKSGE_ARITHMETIC_PROMOTE_TEST(int, char, char, int);
BKSGE_ARITHMETIC_PROMOTE_TEST(int, char, char, char);
#undef BKSGE_ARITHMETIC_PROMOTE_TEST
| 59.784404 | 94 | 0.778792 | myoukaku |
958b2f5869c8acdc23c1f098b29acb1eb98cda0c | 1,972 | cpp | C++ | test/core/utility/UnicodeTest.cpp | mark-online/sne | 92190c78a1710778acf16dd3a83af064db5c269b | [
"MIT"
] | null | null | null | test/core/utility/UnicodeTest.cpp | mark-online/sne | 92190c78a1710778acf16dd3a83af064db5c269b | [
"MIT"
] | null | null | null | test/core/utility/UnicodeTest.cpp | mark-online/sne | 92190c78a1710778acf16dd3a83af064db5c269b | [
"MIT"
] | null | null | null | #include "CoreTestPCH.h"
#include <sne/core/utility/Unicode.h>
using namespace sne;
using namespace sne::core;
// Visual Studio에서 한글 문자열이 포함된 코드를 실행하기 위해서
// "UTF-8 with BOM"으로 저장해야 함
/**
* @class UnicodeTest
*
* Unicode Test
*/
class UnicodeTest : public testing::Test
{
private:
void testEnglish();
void testKorean();
void testInvalidUtf8();
};
TEST_F(UnicodeTest, testEnglish)
{
{
const std::string expected("You aren't gonna need it!");
ASSERT_EQ(expected, toUtf8(L"You aren't gonna need it!")) <<
"UCS to UTF-8";
}
{
const std::wstring expected(L"You aren't gonna need it!");
ASSERT_TRUE(wcscmp(expected.c_str(),
fromUtf8("You aren't gonna need it!").c_str()) == 0) <<
"UTF-8 to UCS";
}
}
TEST_F(UnicodeTest, testKorean)
{
#ifdef _MSC_VER
#pragma warning(push)
#pragma warning(disable: 4566)
{
const std::string expected("\xEC\x95\x84\xED\x96\x8F\xED\x96\x8F");
ASSERT_EQ(expected, toUtf8(L"아햏햏")) << "UCS to UTF-8";
}
{
const std::wstring expected(L"아햏햏");
ASSERT_EQ(expected, fromUtf8("\xEC\x95\x84\xED\x96\x8F\xED\x96\x8F")) <<
"UTF-8 to UCS";
}
#pragma warning(pop)
#else
// GCC의 경우 유니코드 문자열을 바로 입력할 경우 컴파일러가 제대로
// 파싱하지 못하는 문제가 발생한다.
{
const std::string expected("\xEC\x95\x84\xED\x96\x8F\xED\x96\x8F");
ASSERT_EQ(expected, toUtf8(fromUtf8(expected))) <<
"utf-8 -> ucs -> utf-8";
}
#endif
}
TEST_F(UnicodeTest, testInvalidUtf8)
{
const std::wstring str(L"1234567890ABCDEFGHIZKLMNOPQRSTUVWXYZ");
const std::string utf8(toUtf8(str));
const size_t strLen = 10;
std::string invalidUtf8;
for (std::string::size_type i = 0; i < strLen; ++i) {
invalidUtf8.push_back(utf8[i]);
}
const std::wstring converted(fromUtf8(invalidUtf8));
ASSERT_TRUE(wcscmp(L"1234567890", converted.c_str()) == 0) <<
"converting";
}
| 24.04878 | 80 | 0.615619 | mark-online |
958cc3d74bfa6a54c74c93d8a43a04993317516b | 114 | cpp | C++ | src/entrypoint.cpp | juha-hovi/Jam3D | 71b7d10c9cfccb7a376ae9d1753277e0ed45f853 | [
"MIT"
] | null | null | null | src/entrypoint.cpp | juha-hovi/Jam3D | 71b7d10c9cfccb7a376ae9d1753277e0ed45f853 | [
"MIT"
] | null | null | null | src/entrypoint.cpp | juha-hovi/Jam3D | 71b7d10c9cfccb7a376ae9d1753277e0ed45f853 | [
"MIT"
] | null | null | null | #include "application.h"
int main()
{
Jam3D::Application application;
application.Run();
return 0;
} | 14.25 | 35 | 0.649123 | juha-hovi |
958f6d03a90c76bf3f35058237e52e1e13e0ad42 | 309 | cpp | C++ | Ejercicios/Ejercicio19-do-while/do-while.cpp | Nelson-Chacon/cpp | 21332e2ecaa815acc116eead80dd5b05cc35b710 | [
"MIT"
] | null | null | null | Ejercicios/Ejercicio19-do-while/do-while.cpp | Nelson-Chacon/cpp | 21332e2ecaa815acc116eead80dd5b05cc35b710 | [
"MIT"
] | null | null | null | Ejercicios/Ejercicio19-do-while/do-while.cpp | Nelson-Chacon/cpp | 21332e2ecaa815acc116eead80dd5b05cc35b710 | [
"MIT"
] | null | null | null | #include<iostream>
using namespace std;
int main(int argc, char const *argv[])
{
int a = 2;
int b =1;
while (a>b)
{
cout<<"(while) A > B"<< endl;
break;
}
do{
cout<<"(do while) A > B"<< endl;
break;
}while (a>b);
return 0;
}
| 14.045455 | 40 | 0.433657 | Nelson-Chacon |
d2e51d6e4bb90c5a9b5f20ee1c8125b5adc19760 | 5,246 | hpp | C++ | nRF24L01+/nrf24L01.hpp | Jordieboyz/nRF24L01 | 18db91377c1b48418b64e4ce1d1f947109220267 | [
"BSL-1.0"
] | null | null | null | nRF24L01+/nrf24L01.hpp | Jordieboyz/nRF24L01 | 18db91377c1b48418b64e4ce1d1f947109220267 | [
"BSL-1.0"
] | null | null | null | nRF24L01+/nrf24L01.hpp | Jordieboyz/nRF24L01 | 18db91377c1b48418b64e4ce1d1f947109220267 | [
"BSL-1.0"
] | null | null | null | #ifndef NRF24_HPP
#define NRF24_HPP
#include "hwlib.hpp"
#include "registers.hpp"
enum pipeInfo : uint8_t {
ERX_P0 = 0, ERX_P1, ERX_P2, ERX_P3, ERX_P4, ERX_P5,
RX_ADDR_P0 = 0x0A, RX_ADDR_P1, RX_ADDR_P2, RX_ADDR_P3, RX_ADDR_P4, RX_ADDR_P5,
RX_PW_P0 = 0x11, RX_PW_P1, RX_PW_P2, RX_PW_P3, RX_PW_P4, RX_PW_P5
};
enum dataRate : uint8_t {
dBm_18 = 0,
dBm_12,
dBm_6,
dBm_0
};
/// @file
/// \brief
/// nRF24L01+ driver
/// \details
/// This driver is a driver for the nRF24L01+
/// It's a fairly easy library using the most significant functions
/// of the nRF24L01+
class NRF24 {
private:
hwlib::spi_bus & spi;
hwlib::pin_out & ce;
hwlib::pin_out & csn;
uint8_t data_size;
const uint8_t pipeEnable[6] = { ERX_P0, ERX_P1, ERX_P2, ERX_P3, ERX_P4, ERX_P5 };
const uint8_t pipeAdress[6] = { RX_ADDR_P0, RX_ADDR_P1, RX_ADDR_P2, RX_ADDR_P3, RX_ADDR_P4, RX_ADDR_P5 };
const uint8_t pipeWidth[6] = { RX_PW_P0, RX_PW_P1, RX_PW_P2, RX_PW_P3, RX_PW_P4, RX_PW_P5 };
protected:
/// \brief
/// Read from a regsiter
/// \details
/// This funtion reads one byte from the given register
uint8_t read_register(uint8_t reg);
/// \brief
/// Write to a regsiter
/// \details
/// This funtion writes one byte to the given register
void write_register(uint8_t reg, uint8_t byte);
/// \brief
/// Reads multiple bytes from a single register
/// \details
/// This function reads the an x amount of incoming bytes (from the MISO pin)
void read_register(uint8_t reg, std::array<uint8_t, 5> & bytes);
/// \brief
/// Writes multiple bytes to a register
/// \details
/// This function writes n bytes to one of the registers of the nRF24L01+
void write_register(uint8_t reg, std::array<uint8_t, 5> & bytes);
/// \brief
/// Read incoming data
/// \details
/// This function reads the data from the RX_PLD (arrived data on the RX FIFO)
/// and saves it in the given array for further use
void read_payload(std::array<uint8_t, 32> & payload);
/// \brief
/// Write data to payload
/// \details
/// This function writes the given payload to the payload queque
void write_payload(std::array<uint8_t, 32> & payload);
/// \brief
/// Flush RX
/// \details
/// This function flushes the RX queue
void flush_RX();
/// \brief
/// Flush TX
/// \details
/// This function flushes the TX queue
void flush_TX();
/// \brief
/// Enable the features
/// \details
/// This function enables the right featuers on the nRF24L01+ for example
/// the no_ack functionality
void enable_features();
/// \brief
/// Reset enabled pipes
/// \details
/// This function resets all pipes 2-5, but keeps pipe 0 and 1 enabled
void reset_enabled_pipes();
public:
/// \brief
/// Constructor nRF24L01+
/// \details
/// The nRF24L01+ needs a ce and csn pin defenition to work
NRF24(hwlib::spi_bus & spi, hwlib::pin_out & ce, hwlib::pin_out & csn) :
spi( spi ), ce( ce ), csn( csn ), data_size( 32 )
{}
/// \brief
/// The start of the nRF24L01+
/// \details
/// This funtion gets the chip ready to write and read from the nRF24L01+
/// This funtion also ensures there are correct values in a couple registers
/// make sure this is the first function you call on the nRF24L01+
void start_up_chip();
/// \brief
/// Set a channel
/// \details
/// This funtion sets the channel whereover the nRF24L01+ will communicate
void set_channel(int channel);
/// \brief
/// Set the data rate
/// \details
/// This funtion sets the speed of the output data going through the air
void set_data_rate( dataRate rate );
/// \brief
/// Trigger receive mode
/// \details
/// This function forces the nRF24L01+ to operate in the RX ( receive ) mode
void RX_mode();
/// \brief
/// Trigger transmit mode
/// \details
/// This function forces the nRF24L01+ to operate in the TX ( transmit ) mode
void TX_mode();
/// \brief
/// Set the transmit adress
/// \details
/// This function writes the given adress to the registers so the nRF24L01+
/// can communicate with another nRF24L01+
void write_adress_TX(std::array<uint8_t, 5> & adress);
/// \brief
/// Set the receive adress
/// \details
/// This funtion enables the given pipe and writes the give adress to the
/// right registers so the nRF24L01+ can listen to the transmitted data on the right pipe
void write_adress_RX(uint8_t pipe, std::array<uint8_t, 5> & adress);
/// \brief
/// Read incoming data
/// \details
/// reads the incoming data and returns the first byte
void read(std::array<uint8_t, 32> & payload );
/// \brief
/// Write data (without ack)
/// \details
/// This funtion writes the data to the transmit queue, depending on the mode of
/// the nRF24L01+ module, the data will automaticly dissappear from the queue
void write_noack(std::array<uint8_t, 32> & payload);
};
#endif // NRF24_HPP
| 29.977143 | 109 | 0.634769 | Jordieboyz |
d2e56f87ced7c4b8300c4a05f3ebcc6c522bedc6 | 1,509 | cpp | C++ | 6. Tree/16.A1110.cpp | huangjiayu-zju/PAT-A | ecb07409727c56d556a5af1b201158bab0d0d2e8 | [
"MIT"
] | null | null | null | 6. Tree/16.A1110.cpp | huangjiayu-zju/PAT-A | ecb07409727c56d556a5af1b201158bab0d0d2e8 | [
"MIT"
] | null | null | null | 6. Tree/16.A1110.cpp | huangjiayu-zju/PAT-A | ecb07409727c56d556a5af1b201158bab0d0d2e8 | [
"MIT"
] | null | null | null | #include<cstdio>
#include<cstring>
#include<queue>
using namespace std;
const int maxn = 30;
//进行层序遍历,让空结点也入队,如果在访问完N个非空结点之前访问到了空结点,那么说明不是完全二叉树
bool isRoot[maxn];//节点是否是根结点
struct Node{
int left, right;//左右结点的下标
} node[maxn];
//input函数输入数据
int input(){
char id[3];
scanf("%s", id);
if(id[0] == '-'){
return -1;
}else if(strlen(id) == 1){
return id[0] - '0';
}else{
return (id[0] - '0') * 10 + (id[1] - '0');
}
}
//找到根结点函数编号
int findRoot(int n){
for (int i = 0; i < n; i++){
if(isRoot[i]){
return i;
}
}
return -1;
}
//BFS判断完全二叉树,root为根结点编号,last是最后一个结点编号(注意引用),n为结点个数
bool BFS(int root, int &last, int n){
queue<int> q;
q.push(root);
while(n){
int front = q.front();
q.pop();
if(front == -1){
return false; //访问到空结点,一定是非完全二叉树
}
n--;
last = front; //记录最后一个非空结点编号
q.push(node[front].left);
q.push(node[front].right);
}
return true;
}
int main(){
int n;
scanf("%d", &n);
memset(isRoot, true, sizeof(isRoot));
for (int i = 0; i < n; i++){
int left = input(), right = input();
isRoot[left] = isRoot[right] = false;
node[i].left = left;
node[i].right = right;
}
int root = findRoot(n), last;
bool isCompleteTree = BFS(root, last, n);
if(isCompleteTree){
printf("YES %d\n", last);
}else{
printf("NO %d\n", root);
}
return 0;
} | 20.671233 | 50 | 0.513585 | huangjiayu-zju |
d2e78785ed9f3d01e875fec26b0436d5b8383246 | 16,719 | hpp | C++ | include/rxcpp/rx-util.hpp | schiebel/dVO | 2096230d4ee677b9c548d57b702a44b87caef10d | [
"Apache-2.0"
] | null | null | null | include/rxcpp/rx-util.hpp | schiebel/dVO | 2096230d4ee677b9c548d57b702a44b87caef10d | [
"Apache-2.0"
] | null | null | null | include/rxcpp/rx-util.hpp | schiebel/dVO | 2096230d4ee677b9c548d57b702a44b87caef10d | [
"Apache-2.0"
] | null | null | null | // Copyright (c) Microsoft Open Technologies, Inc. All rights reserved. See License.txt in the project root for license information.
#pragma once
#include "rx-includes.hpp"
#if !defined(CPPRX_RX_UTIL_HPP)
#define CPPRX_RX_UTIL_HPP
#if !defined(RXCPP_THREAD_LOCAL)
#if defined(_MSC_VER)
#define RXCPP_THREAD_LOCAL __declspec(thread)
#else
#define RXCPP_THREAD_LOCAL __thread
#endif
#endif
#if !defined(RXCPP_SELECT_ANY)
#if defined(_MSC_VER)
#define RXCPP_SELECT_ANY __declspec(selectany)
#else
#define RXCPP_SELECT_ANY
#endif
#endif
#define RXCPP_CONCAT(Prefix, Suffix) Prefix ## Suffix
#define RXCPP_CONCAT_EVALUATE(Prefix, Suffix) RXCPP_CONCAT(Prefix, Suffix)
#define RXCPP_MAKE_IDENTIFIER(Prefix) RXCPP_CONCAT_EVALUATE(Prefix, __LINE__)
namespace rxcpp { namespace util {
template<class Type>
struct identity
{
typedef Type type;
Type operator()(const Type& left) const {return left;}
};
template <class T>
class maybe
{
bool is_set;
typename std::aligned_storage<sizeof(T), std::alignment_of<T>::value>::type
storage;
public:
maybe()
: is_set(false)
{
}
maybe(T value)
: is_set(false)
{
new (reinterpret_cast<T*>(&storage)) T(value);
is_set = true;
}
maybe(const maybe& other)
: is_set(false)
{
if (other.is_set) {
new (reinterpret_cast<T*>(&storage)) T(*other.get());
is_set = true;
}
}
maybe(maybe&& other)
: is_set(false)
{
if (other.is_set) {
new (reinterpret_cast<T*>(&storage)) T(std::move(*other.get()));
is_set = true;
other.reset();
}
}
~maybe()
{
reset();
}
void reset()
{
if (is_set) {
is_set = false;
reinterpret_cast<T*>(&storage)->~T();
}
}
T* get() {
return is_set ? reinterpret_cast<T*>(&storage) : 0;
}
const T* get() const {
return is_set ? reinterpret_cast<const T*>(&storage) : 0;
}
void set(T value) {
if (is_set) {
*reinterpret_cast<T*>(&storage) = std::move(value);
} else {
new (reinterpret_cast<T*>(&storage)) T(std::move(value));
is_set = true;
}
}
T& operator*() { return *get(); }
const T& operator*() const { return *get(); }
T* operator->() { return get(); }
const T* operator->() const { return get(); }
maybe& operator=(const T& other) {
set(other);
return *this;
}
maybe& operator=(const maybe& other) {
if (const T* pother = other.get()) {
set(*pother);
} else {
reset();
}
return *this;
}
// boolean-like operators
operator T*() { return get(); }
operator const T*() const { return get(); }
private:
};
template<class T>
struct reveal_type {private: reveal_type();};
#if RXCPP_USE_VARIADIC_TEMPLATES
template <int... Indices>
struct tuple_indices;
template <>
struct tuple_indices<-1> { // for an empty std::tuple<> there is no entry
typedef tuple_indices<> type;
};
template <int... Indices>
struct tuple_indices<0, Indices...> { // stop the recursion when 0 is reached
typedef tuple_indices<0, Indices...> type;
};
template <int Index, int... Indices>
struct tuple_indices<Index, Indices...> { // recursively build a sequence of indices
typedef typename tuple_indices<Index - 1, Index, Indices...>::type type;
};
template <typename T>
struct make_tuple_indices {
typedef typename tuple_indices<std::tuple_size<T>::value - 1>::type type;
};
namespace detail {
template<class T>
struct tuple_dispatch;
template<size_t... DisptachIndices>
struct tuple_dispatch<tuple_indices<DisptachIndices...>> {
template<class F, class T>
static
auto call(F&& f, T&& t)
-> decltype (std::forward<F>(f)(std::get<DisptachIndices>(std::forward<T>(t))...)) {
return std::forward<F>(f)(std::get<DisptachIndices>(std::forward<T>(t))...);
}
};}
template<class F, class T>
auto tuple_dispatch(F&& f, T&& t)
-> decltype(detail::tuple_dispatch<typename make_tuple_indices<typename std::decay<T>::type>::type>::call(std::forward<F>(f), std::forward<T>(t))) {
return detail::tuple_dispatch<typename make_tuple_indices<typename std::decay<T>::type>::type>::call(std::forward<F>(f), std::forward<T>(t));
}
namespace detail {
template<class T>
struct tuple_tie;
template<size_t... TIndices>
struct tuple_tie<tuple_indices<TIndices...>> {
template<class T>
static
auto tie(T&& t)
-> decltype (std::tie(std::get<TIndices>(std::forward<T>(t))...)) {
return std::tie(std::get<TIndices>(std::forward<T>(t))...);
}
};}
template<class T>
auto tuple_tie(T&& t)
-> decltype(detail::tuple_tie<typename make_tuple_indices<typename std::decay<T>::type>::type>::tie(std::forward<T>(t))) {
return detail::tuple_tie<typename make_tuple_indices<typename std::decay<T>::type>::type>::tie(std::forward<T>(t));
}
struct as_tuple {
template<class... AsTupleNext>
auto operator()(AsTupleNext... x)
-> decltype(std::make_tuple(std::move(x)...)) {
return std::make_tuple(std::move(x)...);}
template<class... AsTupleNext>
auto operator()(AsTupleNext... x) const
-> decltype(std::make_tuple(std::move(x)...)) {
return std::make_tuple(std::move(x)...);}
};
#else
namespace detail {
template<size_t TupleSize>
struct tuple_dispatch;
template<>
struct tuple_dispatch<0> {
template<class F, class T>
static auto call(F&& f, T&& )
-> decltype (std::forward<F>(f)()) {
return std::forward<F>(f)();}
};
template<>
struct tuple_dispatch<1> {
template<class F, class T>
static auto call(F&& f, T&& t)
-> decltype (std::forward<F>(f)(std::get<0>(std::forward<T>(t)))) {
return std::forward<F>(f)(std::get<0>(std::forward<T>(t)));}
};
template<>
struct tuple_dispatch<2> {
template<class F, class T>
static auto call(F&& f, T&& t)
-> decltype (std::forward<F>(f)(
std::get<0>(std::forward<T>(t)),
std::get<1>(std::forward<T>(t)))) {
return std::forward<F>(f)(
std::get<0>(std::forward<T>(t)),
std::get<1>(std::forward<T>(t)));}
};
template<>
struct tuple_dispatch<3> {
template<class F, class T>
static auto call(F&& f, T&& t)
-> decltype (std::forward<F>(f)(
std::get<0>(std::forward<T>(t)),
std::get<1>(std::forward<T>(t)),
std::get<2>(std::forward<T>(t)))) {
return std::forward<F>(f)(
std::get<0>(std::forward<T>(t)),
std::get<1>(std::forward<T>(t)),
std::get<2>(std::forward<T>(t)));}
};
template<>
struct tuple_dispatch<4> {
template<class F, class T>
static auto call(F&& f, T&& t)
-> decltype (std::forward<F>(f)(
std::get<0>(std::forward<T>(t)),
std::get<1>(std::forward<T>(t)),
std::get<2>(std::forward<T>(t)),
std::get<3>(std::forward<T>(t)))) {
return std::forward<F>(f)(
std::get<0>(std::forward<T>(t)),
std::get<1>(std::forward<T>(t)),
std::get<2>(std::forward<T>(t)),
std::get<3>(std::forward<T>(t)));}
};
template<>
struct tuple_dispatch<5> {
template<class F, class T>
static auto call(F&& f, T&& t)
-> decltype (std::forward<F>(f)(
std::get<0>(std::forward<T>(t)),
std::get<1>(std::forward<T>(t)),
std::get<2>(std::forward<T>(t)),
std::get<3>(std::forward<T>(t)),
std::get<4>(std::forward<T>(t)))) {
return std::forward<F>(f)(
std::get<0>(std::forward<T>(t)),
std::get<1>(std::forward<T>(t)),
std::get<2>(std::forward<T>(t)),
std::get<3>(std::forward<T>(t)),
std::get<4>(std::forward<T>(t)));}
};
}
template<class F, class T>
auto tuple_dispatch(F&& f, T&& t)
-> decltype(detail::tuple_dispatch<std::tuple_size<typename std::decay<T>::type>::value>::call(std::forward<F>(f), std::forward<T>(t))) {
return detail::tuple_dispatch<std::tuple_size<typename std::decay<T>::type>::value>::call(std::forward<F>(f), std::forward<T>(t));
}
struct as_tuple {
auto operator()()
-> decltype(std::make_tuple()) {
return std::make_tuple();}
template<class AsTupleNext>
auto operator()(AsTupleNext x)
-> decltype(std::make_tuple(std::move(x))) {
return std::make_tuple(std::move(x));}
template<
class AsTupleNext1,
class AsTupleNext2>
auto operator()(
AsTupleNext1 x1,
AsTupleNext2 x2)
-> decltype(std::make_tuple(
std::move(x1),
std::move(x2))) {
return std::make_tuple(
std::move(x1),
std::move(x2));}
template<
class AsTupleNext1,
class AsTupleNext2,
class AsTupleNext3>
auto operator()(
AsTupleNext1 x1,
AsTupleNext2 x2,
AsTupleNext3 x3)
-> decltype(std::make_tuple(
std::move(x1),
std::move(x2),
std::move(x3))) {
return std::make_tuple(
std::move(x1),
std::move(x2),
std::move(x3));}
template<
class AsTupleNext1,
class AsTupleNext2,
class AsTupleNext3,
class AsTupleNext4>
auto operator()(
AsTupleNext1 x1,
AsTupleNext2 x2,
AsTupleNext3 x3,
AsTupleNext4 x4)
-> decltype(std::make_tuple(
std::move(x1),
std::move(x2),
std::move(x3),
std::move(x4))) {
return std::make_tuple(
std::move(x1),
std::move(x2),
std::move(x3),
std::move(x4));}
template<
class AsTupleNext1,
class AsTupleNext2,
class AsTupleNext3,
class AsTupleNext4,
class AsTupleNext5>
auto operator()(
AsTupleNext1 x1,
AsTupleNext2 x2,
AsTupleNext3 x3,
AsTupleNext4 x4,
AsTupleNext5 x5)
-> decltype(std::make_tuple(
std::move(x1),
std::move(x2),
std::move(x3),
std::move(x4),
std::move(x5))) {
return std::make_tuple(
std::move(x1),
std::move(x2),
std::move(x3),
std::move(x4),
std::move(x5));}
auto operator()() const
-> decltype(std::make_tuple()) {
return std::make_tuple();}
template<class AsTupleNext>
auto operator()(AsTupleNext x) const
-> decltype(std::make_tuple(std::move(x))) {
return std::make_tuple(std::move(x));}
template<
class AsTupleNext1,
class AsTupleNext2>
auto operator()(
AsTupleNext1 x1,
AsTupleNext2 x2) const
-> decltype(std::make_tuple(
std::move(x1),
std::move(x2))) {
return std::make_tuple(
std::move(x1),
std::move(x2));}
template<
class AsTupleNext1,
class AsTupleNext2,
class AsTupleNext3>
auto operator()(
AsTupleNext1 x1,
AsTupleNext2 x2,
AsTupleNext3 x3) const
-> decltype(std::make_tuple(
std::move(x1),
std::move(x2),
std::move(x3))) {
return std::make_tuple(
std::move(x1),
std::move(x2),
std::move(x3));}
template<
class AsTupleNext1,
class AsTupleNext2,
class AsTupleNext3,
class AsTupleNext4>
auto operator()(
AsTupleNext1 x1,
AsTupleNext2 x2,
AsTupleNext3 x3,
AsTupleNext4 x4) const
-> decltype(std::make_tuple(
std::move(x1),
std::move(x2),
std::move(x3),
std::move(x4))) {
return std::make_tuple(
std::move(x1),
std::move(x2),
std::move(x3),
std::move(x4));}
template<
class AsTupleNext1,
class AsTupleNext2,
class AsTupleNext3,
class AsTupleNext4,
class AsTupleNext5>
auto operator()(
AsTupleNext1 x1,
AsTupleNext2 x2,
AsTupleNext3 x3,
AsTupleNext4 x4,
AsTupleNext5 x5) const
-> decltype(std::make_tuple(
std::move(x1),
std::move(x2),
std::move(x3),
std::move(x4),
std::move(x5))) {
return std::make_tuple(
std::move(x1),
std::move(x2),
std::move(x3),
std::move(x4),
std::move(x5));}
};
#endif //RXCPP_USE_VARIADIC_TEMPLATES
struct pass_through {
template<class X>
typename std::decay<X>::type operator()(X&& x) {return std::forward<X>(x);}
template<class X>
typename std::decay<X>::type operator()(X&& x) const {return std::forward<X>(x);}
};
struct pass_through_second {
template<class X, class Y>
typename std::decay<Y>::type operator()(X&& , Y&& y) {return std::forward<Y>(y);}
template<class X, class Y>
typename std::decay<Y>::type operator()(X&& , Y&& y) const {return std::forward<Y>(y);}
};
template<typename Function>
class unwinder
{
public:
~unwinder()
{
if (!!function)
{
try {
(*function)();
} catch (...) {
std::unexpected();
}
}
}
explicit unwinder(Function* functionArg)
: function(functionArg)
{
}
void dismiss()
{
function = nullptr;
}
private:
unwinder();
unwinder(const unwinder&);
unwinder& operator=(const unwinder&);
Function* function;
};
}}
#define RXCPP_UNWIND(Name, Function) \
RXCPP_UNWIND_EXPLICIT(uwfunc_ ## Name, Name, Function)
#define RXCPP_UNWIND_AUTO(Function) \
RXCPP_UNWIND_EXPLICIT(RXCPP_MAKE_IDENTIFIER(uwfunc_), RXCPP_MAKE_IDENTIFIER(unwind_), Function)
#define RXCPP_UNWIND_EXPLICIT(FunctionName, UnwinderName, Function) \
auto FunctionName = (Function); \
rxcpp::util::unwinder<decltype(FunctionName)> UnwinderName(std::addressof(FunctionName))
#endif | 32.846758 | 157 | 0.479574 | schiebel |
d2ed706f8b363b7cd001fd30e1fa19c3e986bfe1 | 106 | cc | C++ | index_test/test_seek.cc | PudgeXD/courseForLeveldb | 5321a35f3a1b1ef2ee6e82cca069d72ae803d1c0 | [
"BSD-3-Clause"
] | null | null | null | index_test/test_seek.cc | PudgeXD/courseForLeveldb | 5321a35f3a1b1ef2ee6e82cca069d72ae803d1c0 | [
"BSD-3-Clause"
] | null | null | null | index_test/test_seek.cc | PudgeXD/courseForLeveldb | 5321a35f3a1b1ef2ee6e82cca069d72ae803d1c0 | [
"BSD-3-Clause"
] | null | null | null | //
// Created by rui on 19-6-10.
//
#include <iostream>
using namespace std;
int main(){
return 0;
} | 8.833333 | 29 | 0.613208 | PudgeXD |
d2ed736990e1208ac482d11c480f9fd230cc1596 | 6,270 | hpp | C++ | cpp-projects/exvr-designer/data/states.hpp | FlorianLance/exvr | 4d210780737479e9576c90e9c80391c958787f44 | [
"MIT"
] | null | null | null | cpp-projects/exvr-designer/data/states.hpp | FlorianLance/exvr | 4d210780737479e9576c90e9c80391c958787f44 | [
"MIT"
] | null | null | null | cpp-projects/exvr-designer/data/states.hpp | FlorianLance/exvr | 4d210780737479e9576c90e9c80391c958787f44 | [
"MIT"
] | null | null | null |
/***********************************************************************************
** exvr-designer **
** MIT License **
** Copyright (c) [2018] [Florian Lance][EPFL-LNCO] **
** 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. **
************************************************************************************/
#pragma once
// base
#include "utility/tuple_array.hpp"
// qt-utility
#include "data/unity_types.hpp"
// local
#include "element.hpp"
namespace tool::ex {
using namespace std::literals::string_view_literals;
enum class ExpLauncherCommand : int{
Load=0, Play, Pause, Stop, Next, Previous, UpdateComponent, UpdateConnector, Quit,
Action, GoToSpecificInstanceElement, PlayPause, PlayDelay, Error, Clean,
SizeEnum
};
enum class ExpLauncherState : int{
NotStarted=0,
Starting,
Idle,
LoadingExperiment,
Closing,
SizeEnum
};
enum class ExpState : int{
NotLoaded = 0,
Loaded,
Running,
Paused,
SizeEnum
};
using Description = std::string_view;
using TExpLauncherState = std::tuple<ExpLauncherState, Description>;
static constexpr TupleArray<ExpLauncherState::SizeEnum, TExpLauncherState> expLauncherStates = {{
TExpLauncherState
{ExpLauncherState::NotStarted, "[ExVR-exp] ExVR-exp not launched."sv},
{ExpLauncherState::Starting, "[ExVR-exp] ExVR-exp is starting."sv},
{ExpLauncherState::Idle, "[ExVR-exp] Idle."sv},
{ExpLauncherState::LoadingExperiment, "[ExVR-exp] ExVR-exp is loading an experiment..."sv},
{ExpLauncherState::Closing, "[ExVR-exp] ExVR-exp is closing."sv},
}};
[[maybe_unused]] static Description get_description(ExpLauncherState s) {
return expLauncherStates.at<0,1>(s);
}
using TExpState = std::tuple<ExpState, Description>;
static constexpr TupleArray<ExpState::SizeEnum, TExpState> expStates = {{
TExpState
{ExpState::NotLoaded, "[ExVR-exp] <b>No experiment loaded.</b>"sv},
{ExpState::Loaded, "[ExVR-exp] <b>Experiment loaded</b>"sv},
{ExpState::Running, "[ExVR-exp] <b>Experiment is running</b>"sv},
{ExpState::Paused, "[ExVR-exp] <b>Experiment paused</b>"sv},
}};
[[maybe_unused]] static Description get_description(ExpState s) {
return expStates.at<0,1>(s);
}
[[maybe_unused]] static QString to_command_id(ExpLauncherCommand cmd){
return QString::number(static_cast<int>(cmd));
}
enum class FontStyle : int {
Normal = 0, Bold = 1, Italic =2, Bold_and_italic =3,
SizeEnum};
enum class Alignment : int {
UpperLeft = 0, UpperCenter = 1, UpperRight =2, MiddleLeft =3, MiddleCenter = 4, MiddleRight = 5, LowerLeft = 6, LowerCenter =7, LowerRight = 8,
SizeEnum};
enum class TextOverlflow : int {
Wrap = 0, Overflow = 1,
SizeEnum};
struct States{
States(QString nVersion) : numVersion(nVersion){
auto split = numVersion.split(".");
majorNumVersion = split[0].toInt();
minorNumVersion = split[1].toInt();
}
void reset(){
neverLoaded = true;
currentElementKey = -1;
currentConditionKey = -1;
currentElementName = "";
currentTypeSpecificInfo = "";
experimentTimeS = 0.0;
currentElementTimeS = 0.0;
currentIntervalEndTimeS = 0.0;
currentOrder = "";
nbCalls = "";
}
const QString numVersion;
int majorNumVersion;
int minorNumVersion;
int maximumDeepLevel = -1;
unsigned int randomizationSeed = 0;
QString loadedExpDesignerVersion = "unknow";
QString designerPathUsedForLoadedExp = "unknow";
QString currentExpfilePath;
QString currentName = "unknow";
QString currentMode = "designer";
QString currentInstanceName = "debug-instance.xml";
ExpLauncherState explauncherState = ExpLauncherState::NotStarted;
ExpState expState = ExpState::NotLoaded;
bool followsCurrentCondition = false;
bool neverLoaded = true;
int currentElementKey=-1;
int currentConditionKey=-1;
Element::Type currentElementType;
QString currentElementName = "";
QString currentTypeSpecificInfo = "";
double experimentTimeS = 0.0;
double currentElementTimeS = 0.0;
double currentIntervalEndTimeS = 0.0;
QString currentOrder = "";
QString nbCalls = "";
};
}
| 37.771084 | 151 | 0.568262 | FlorianLance |
d2f0a3d686afb1cab613fb674d44c04eb5dd68a7 | 2,402 | cpp | C++ | core/utils/Params.cpp | dillonl/ComprehensiveVCFMerge | dee320975c13ba6765fb844b00b90fb56dcff7b2 | [
"MIT"
] | null | null | null | core/utils/Params.cpp | dillonl/ComprehensiveVCFMerge | dee320975c13ba6765fb844b00b90fb56dcff7b2 | [
"MIT"
] | null | null | null | core/utils/Params.cpp | dillonl/ComprehensiveVCFMerge | dee320975c13ba6765fb844b00b90fb56dcff7b2 | [
"MIT"
] | null | null | null | #include "Params.h"
#include "Utility.h"
namespace cvm
{
Params::Params(int argc, char** argv) : m_options("CVM", " - Comprehensive VCF Merger (CVM) merges multiple VCF files into a single VCF. CVM reconstructs the sequence of each VCF's alleles with the reference sequence and compares them across all VCFs to discover duplicate variants no matter how the alleles are distributed.")
{
parse(argc, argv);
}
Params::~Params()
{
}
void Params::parse(int argc, char** argv)
{
this->m_options.add_options()
("h,help","Print help message")
("s,silent", "Run without reports")
("r,reference", "Path to input reference (FASTA) file [required]", cxxopts::value< std::string >())
("v,vcfs", "Path to input VCF files, separate multiple files by space [required]", cxxopts::value< std::vector< std::string > >())
("l,labels", "Labels for VCF files, separate multiple labels by space [required]", cxxopts::value< std::vector< std::string > >())
("o,output_vcf", "Output VCF file name [required]", cxxopts::value< std::string >());
this->m_options.parse(argc, argv);
}
std::vector< std::string > Params::getUsageErrors()
{
std::vector< std::string > errorMessages;
auto vcfCount = m_options.count("v");
auto labelCount = m_options.count("l");
if (vcfCount <= 1 || labelCount <= 1)
{
errorMessages.emplace_back("You must provide at least 2 vcfs and labels");
}
if (vcfCount != labelCount)
{
errorMessages.emplace_back("Please provide a label for every vcf");
}
return errorMessages;
}
bool Params::showHelp()
{
return m_options.count("h");
}
bool Params::isSilent()
{
return m_options.count("s");
}
std::string Params::getHelpMessage()
{
return this->m_options.help();
}
std::vector< std::string > Params::getInVCFPaths()
{
auto vcfPaths = m_options["v"].as< std::vector< std::string > >();
validateFilePaths(vcfPaths, true);
return vcfPaths;
}
std::vector< std::string > Params::getInVCFLabels()
{
return m_options["l"].as< std::vector< std::string > >();
}
std::string Params::getReferencePath()
{
return m_options["r"].as< std::string >();
}
std::string Params::getOutVCFPath()
{
return m_options["o"].as< std::string >();
}
void Params::validateFilePaths(const std::vector< std::string >& paths, bool exitOnFailure)
{
for (auto path : paths)
{
fileExists(path, exitOnFailure);
}
}
}
| 27.295455 | 327 | 0.669858 | dillonl |
d2fcc65acb0ec4dbb237827ea399e216cbf7cd16 | 5,286 | hpp | C++ | include/RootMotion/FinalIK/RagdollUtility_Child.hpp | RedBrumbler/BeatSaber-Quest-Codegen | 73dda50b5a3e51f10d86b766dcaa24b0c6226e25 | [
"Unlicense"
] | null | null | null | include/RootMotion/FinalIK/RagdollUtility_Child.hpp | RedBrumbler/BeatSaber-Quest-Codegen | 73dda50b5a3e51f10d86b766dcaa24b0c6226e25 | [
"Unlicense"
] | null | null | null | include/RootMotion/FinalIK/RagdollUtility_Child.hpp | RedBrumbler/BeatSaber-Quest-Codegen | 73dda50b5a3e51f10d86b766dcaa24b0c6226e25 | [
"Unlicense"
] | null | null | null | // Autogenerated from CppHeaderCreator
// Created by Sc2ad
// =========================================================================
#pragma once
// Begin includes
#include "beatsaber-hook/shared/utils/typedefs.h"
#include "beatsaber-hook/shared/utils/byref.hpp"
// Including type: RootMotion.FinalIK.RagdollUtility
#include "RootMotion/FinalIK/RagdollUtility.hpp"
// Including type: UnityEngine.Vector3
#include "UnityEngine/Vector3.hpp"
// Including type: UnityEngine.Quaternion
#include "UnityEngine/Quaternion.hpp"
#include "beatsaber-hook/shared/utils/il2cpp-utils-methods.hpp"
#include "beatsaber-hook/shared/utils/il2cpp-utils-properties.hpp"
#include "beatsaber-hook/shared/utils/il2cpp-utils-fields.hpp"
#include "beatsaber-hook/shared/utils/utils.h"
// Completed includes
// Begin forward declares
// Forward declaring namespace: UnityEngine
namespace UnityEngine {
// Forward declaring type: Transform
class Transform;
}
// Completed forward declares
#include "beatsaber-hook/shared/utils/il2cpp-type-check.hpp"
NEED_NO_BOX(::RootMotion::FinalIK::RagdollUtility::Child);
DEFINE_IL2CPP_ARG_TYPE(::RootMotion::FinalIK::RagdollUtility::Child*, "RootMotion.FinalIK", "RagdollUtility/Child");
// Type namespace: RootMotion.FinalIK
namespace RootMotion::FinalIK {
// Size: 0x34
#pragma pack(push, 1)
// Autogenerated type: RootMotion.FinalIK.RagdollUtility/RootMotion.FinalIK.Child
// [TokenAttribute] Offset: FFFFFFFF
class RagdollUtility::Child : public ::Il2CppObject {
public:
#ifdef USE_CODEGEN_FIELDS
public:
#else
#ifdef CODEGEN_FIELD_ACCESSIBILITY
CODEGEN_FIELD_ACCESSIBILITY:
#else
protected:
#endif
#endif
// public UnityEngine.Transform t
// Size: 0x8
// Offset: 0x10
::UnityEngine::Transform* t;
// Field size check
static_assert(sizeof(::UnityEngine::Transform*) == 0x8);
// public UnityEngine.Vector3 localPosition
// Size: 0xC
// Offset: 0x18
::UnityEngine::Vector3 localPosition;
// Field size check
static_assert(sizeof(::UnityEngine::Vector3) == 0xC);
// public UnityEngine.Quaternion localRotation
// Size: 0x10
// Offset: 0x24
::UnityEngine::Quaternion localRotation;
// Field size check
static_assert(sizeof(::UnityEngine::Quaternion) == 0x10);
public:
// Get instance field reference: public UnityEngine.Transform t
::UnityEngine::Transform*& dyn_t();
// Get instance field reference: public UnityEngine.Vector3 localPosition
::UnityEngine::Vector3& dyn_localPosition();
// Get instance field reference: public UnityEngine.Quaternion localRotation
::UnityEngine::Quaternion& dyn_localRotation();
// public System.Void .ctor(UnityEngine.Transform transform)
// Offset: 0x1F71B84
template<::il2cpp_utils::CreationType creationType = ::il2cpp_utils::CreationType::Temporary>
static RagdollUtility::Child* New_ctor(::UnityEngine::Transform* transform) {
static auto ___internal__logger = ::Logger::get().WithContext("::RootMotion::FinalIK::RagdollUtility::Child::.ctor");
return THROW_UNLESS((::il2cpp_utils::New<RagdollUtility::Child*, creationType>(transform)));
}
// public System.Void FixTransform(System.Single weight)
// Offset: 0x1F727CC
void FixTransform(float weight);
// public System.Void StoreLocalState()
// Offset: 0x1F7277C
void StoreLocalState();
}; // RootMotion.FinalIK.RagdollUtility/RootMotion.FinalIK.Child
#pragma pack(pop)
static check_size<sizeof(RagdollUtility::Child), 36 + sizeof(::UnityEngine::Quaternion)> __RootMotion_FinalIK_RagdollUtility_ChildSizeCheck;
static_assert(sizeof(RagdollUtility::Child) == 0x34);
}
#include "beatsaber-hook/shared/utils/il2cpp-utils-methods.hpp"
// Writing MetadataGetter for method: RootMotion::FinalIK::RagdollUtility::Child::New_ctor
// Il2CppName: .ctor
// Cannot get method pointer of value based method overload from template for constructor!
// Try using FindMethod instead!
// Writing MetadataGetter for method: RootMotion::FinalIK::RagdollUtility::Child::FixTransform
// Il2CppName: FixTransform
template<>
struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<void (RootMotion::FinalIK::RagdollUtility::Child::*)(float)>(&RootMotion::FinalIK::RagdollUtility::Child::FixTransform)> {
static const MethodInfo* get() {
static auto* weight = &::il2cpp_utils::GetClassFromName("System", "Single")->byval_arg;
return ::il2cpp_utils::FindMethod(classof(RootMotion::FinalIK::RagdollUtility::Child*), "FixTransform", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{weight});
}
};
// Writing MetadataGetter for method: RootMotion::FinalIK::RagdollUtility::Child::StoreLocalState
// Il2CppName: StoreLocalState
template<>
struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<void (RootMotion::FinalIK::RagdollUtility::Child::*)()>(&RootMotion::FinalIK::RagdollUtility::Child::StoreLocalState)> {
static const MethodInfo* get() {
return ::il2cpp_utils::FindMethod(classof(RootMotion::FinalIK::RagdollUtility::Child*), "StoreLocalState", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{});
}
};
| 47.621622 | 192 | 0.723231 | RedBrumbler |
d2fd3a734d71d5af651bcceb133dbba657137ea1 | 2,216 | hpp | C++ | include/mlcmst_subnet_solver.hpp | qaskai/MLCMST | 0fa0529347eb6a44f45cf52dff477291c6fad433 | [
"MIT"
] | null | null | null | include/mlcmst_subnet_solver.hpp | qaskai/MLCMST | 0fa0529347eb6a44f45cf52dff477291c6fad433 | [
"MIT"
] | null | null | null | include/mlcmst_subnet_solver.hpp | qaskai/MLCMST | 0fa0529347eb6a44f45cf52dff477291c6fad433 | [
"MIT"
] | null | null | null | #pragma once
#include <memory>
#include <vector>
#include <unordered_map>
#include <mlcmst_solver.hpp>
#include <network/mlcst.hpp>
#include <network/mlcc_network.hpp>
namespace MLCMST {
class MLCMST_SubnetSolver final
{
public:
struct Result {
double cost;
network::MLCST mlcmst;
std::vector<int> mapping;
};
explicit MLCMST_SubnetSolver(std::unique_ptr<MLCMST_Solver> solver);
~MLCMST_SubnetSolver();
std::pair<network::MLCST, std::vector<int>> subnetTree(
const network::MLCCNetwork& network, const std::vector<int>& subnet_vertices);
double subnetTreeCost(const network::MLCCNetwork& network, const std::vector<int>& subnet_vertices);
std::unordered_map<int, std::pair< network::MLCST, std::vector<int> >> allSubnetTrees(
const network::MLCCNetwork& network, const std::vector<int>& vertex_subnet);
std::unordered_map<int, double> allSubnetTreeCosts(
const network::MLCCNetwork& network, const std::vector<int>& vertex_subnet);
std::unordered_map<int, std::pair< network::MLCST, std::vector<int> > >allSubnetTrees(
const network::MLCCNetwork& network, const std::unordered_map<int,std::vector<int>>& groups);
std::unordered_map<int, double> allSubnetTreeCosts(
const network::MLCCNetwork& network, const std::unordered_map<int,std::vector<int>>& groups);
std::unordered_map<int, Result> solveAllSubnets(
const network::MLCCNetwork& network, const std::vector<int>& subnet_vertices);
std::unordered_map<int, Result> solveAllSubnets(
const network::MLCCNetwork& network, const std::unordered_map<int, std::vector<int>>& groups);
Result solveSubnet(const network::MLCCNetwork& network, std::vector<int> subnet_vertices);
network::MLCST solveMLCMST(const network::MLCCNetwork& network, const std::vector<int>& vertex_subnet);
network::MLCST solveMLCMST(
const network::MLCCNetwork& network, const std::unordered_map<int, std::vector<int>>& groups);
private:
std::unique_ptr< MLCMST_Solver > solver_;
std::unordered_map<int, std::vector<int>> createGroups(int center, const std::vector<int>& vertex_subnet);
};
}
| 37.559322 | 110 | 0.707581 | qaskai |
9601782884722b4a1c497fbb5e7b9cf01da189da | 309 | cpp | C++ | LearnOpenGL/SimpleTriangles.cpp | VestLee/LearnOpenGL | 68e93a1f7516b797febe90c87261f0ff3c571d7e | [
"MIT"
] | null | null | null | LearnOpenGL/SimpleTriangles.cpp | VestLee/LearnOpenGL | 68e93a1f7516b797febe90c87261f0ff3c571d7e | [
"MIT"
] | null | null | null | LearnOpenGL/SimpleTriangles.cpp | VestLee/LearnOpenGL | 68e93a1f7516b797febe90c87261f0ff3c571d7e | [
"MIT"
] | null | null | null | #include <Windows.h>
#include <stdio.h>
#include <GL/glut.h>
int main(int argc, char** argv)
{
glutInit(&argc, argv);
glutInitDisplayMode(GLUT_SINGLE | GLUT_RGB | GLUT_DEPTH);
glutInitWindowSize(300, 300);
glutCreateWindow("OpenGL");
printf("OpenGL version: %s\n", glGetString(GL_VERSION));
return 0;
} | 23.769231 | 58 | 0.721683 | VestLee |
960273e0d5fa342a9a7801f5c029da7b14da3bec | 32,700 | hh | C++ | include/cagey-math/old/BasePoint.hh | theycallmecoach/cagey-math | e3a70d6e26abad90bbbaf6bc5f4e7da89651ab59 | [
"MIT"
] | 1 | 2019-05-10T23:34:08.000Z | 2019-05-10T23:34:08.000Z | include/cagey-math/old/BasePoint.hh | theycallmecoach/cagey-math | e3a70d6e26abad90bbbaf6bc5f4e7da89651ab59 | [
"MIT"
] | null | null | null | include/cagey-math/old/BasePoint.hh | theycallmecoach/cagey-math | e3a70d6e26abad90bbbaf6bc5f4e7da89651ab59 | [
"MIT"
] | null | null | null | ////////////////////////////////////////////////////////////////////////////////
//
// cagey-math - C++-17 Vector Math Library
// Copyright (c) 2016 Kyle Girard <[email protected]>
//
// The MIT License (MIT)
//
// 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.
//
////////////////////////////////////////////////////////////////////////////////
#pragma once
#include <type_traits> //for std::is_arithmetic
#include <array> //for std::array
#include <utility> //for std::index_sequence
#include <algorithm> //for std::transform, std::negate, std::equal
#include <numeric> //for std::numeric_limits
#include <iostream>
namespace cagey::math {
template <template <typename, std::size_t> class D, typename T, std::size_t N>
class BasePoint {
public:
/** @cond doxygen has some issues with static assert */
static_assert(N != 0, "BasePoint cannot have zero elements");
static_assert(std::is_arithmetic<T>::value,
"Underlying type must be a number");
/** @endcond */
/// The underlying type of this Point
using Type = T;
/// The number of elements in this Point
const static std::size_t Size = N;
/**
* Construct a Point with all elements initialized to Zero
*/
constexpr BasePoint() noexcept;
/**
* Construct a Point with all elements initialized to the given value
*
* @param v the value to assign to all elements of this Point
*/
explicit BasePoint(T const v) noexcept;
/**
* Construct a Point using the given pointer. Note: It assumed the given
* pointer contains N values;
*/
explicit BasePoint(T *const v) noexcept;
/**
* Construct a Point using the values from the given std::array
*
* @param vals vals[0] is assigned to data[0] etc. etc.
*/
constexpr explicit BasePoint(std::array<T, Size> const &vals) noexcept;
/**
* Conversion Copy Constructor. Construct a Point using a Point with a
* different
* underlying type. Only simple type conversion is performed
*/
template <typename U, typename I = std::make_index_sequence<Size>>
constexpr explicit BasePoint(BasePoint<D, U, Size> const &other) noexcept;
/**
* Index operator
*
* @param i index into this Point
* @return a reference to the element at index i
*/
constexpr auto operator[](std::size_t i) noexcept -> T &;
/**
* Index operator
*
* @param i index into this Point
* @return a reference to the element at index i
*/
constexpr auto operator[](std::size_t i) const noexcept -> T const &;
/**
* Return an iterator to the first element of this Point
*
* @return an iterator pointing to the begining of this Point
*/
constexpr auto begin() noexcept -> T *;
/**
* Return an iterator to the first element of this Point
*
* @return an iterator pointing to the begining of this Point
*/
constexpr auto begin() const noexcept -> T *;
/**
* Return an iterator to the end of this Point.
*
* @return an iterator pointing to the end of this Point
*/
constexpr auto end() noexcept -> T *;
/**
* Return an iterator to the end of this Point.
*
* @return an iterator pointing to the end of this Point
*/
constexpr auto end() const noexcept -> T *;
private:
template <class U, std::size_t... I>
constexpr explicit BasePoint(BasePoint<D, U, Size> const &other,
std::index_sequence<I...>) noexcept;
public:
/// Array containing Point elements
std::array<T, N> data;
};
/**
* Point two element specialization
*/
template <template <typename, std::size_t> class D, typename T>
class BasePoint<D, T, 2> {
/** @cond doxygen has issues with static_assert */
static_assert(std::is_arithmetic<T>::value,
"Underlying type must be a number");
/** @endcond */
public:
/// The underlying type of this Point
using Type = T;
/// The number of elements in this Point
const static std::size_t Size = 2;
/**
* Construct a Point with all elements initialized to Zero
*/
constexpr BasePoint() noexcept;
/**
* Construct a Point with all elements initialized to the given value
*
* @param v the value to assign to all elements of this Point
*/
constexpr explicit BasePoint(T const v) noexcept;
/**
* Construct a Point with the given elements a and b are assigned to x and y
* respectively
*/
constexpr BasePoint(T const a, T const b) noexcept;
/**
* Construct a Point using the given pointer. Note: It assumed the given
* pointer contains two values;
*/
explicit BasePoint(T *const v) noexcept;
/**
* Construct a Point using the values from the given std::array
*
* @param vals vals[0] is assigned to data[0] etc. etc.
*/
constexpr explicit BasePoint(std::array<T, Size> const &vals) noexcept;
/**
* Conversion Copy Constructor. Construct a Point using a Point with a
* different
* underlying type. Only simple type conversion is performed
*/
template <typename U>
constexpr explicit BasePoint(BasePoint<D, U, Size> const &other) noexcept;
/**
* Index operator
*
* @param i index into this Point
* @return a reference to the element at index i
*/
constexpr auto operator[](std::size_t i) noexcept -> T &;
/**
* Index operator
*
* @param i index into this Point
* @return a reference to the element at index i
*/
constexpr auto operator[](std::size_t i) const noexcept -> T const &;
/**
* Return an iterator to the first element of this Point
*
* @return an iterator pointing to the begining of this Point
*/
constexpr auto begin() noexcept -> T *;
/**
* Return an iterator to the first element of this Point
*
* @return an iterator pointing to the begining of this Point
*/
constexpr auto begin() const noexcept -> T *;
/**
* Return an iterator to the end of this Point.
*
* @return an iterator pointing to the end of this Point
*/
constexpr auto end() noexcept -> T *;
/**
* Return an iterator to the end of this Point.
*
* @return an iterator pointing to the end of this Point
*/
constexpr auto end() const noexcept -> T *;
public:
/**
* Anonymous union to allow access to members using different names
*/
union {
/// Data represented as a std::array
std::array<T, 2> data;
struct {
T x; ///< The first element
T y; ///<The second element
};
struct {
T w; ///< Width
T h; ///< Height
};
};
};
/**
* Point three element specialization
*/
template <template <typename, std::size_t> class D, typename T>
class BasePoint<D, T, 3> {
/** @cond doxygen has issues with static_assert */
static_assert(std::is_arithmetic<T>::value,
"Underlying type must be a number");
/** @endcond */
public:
/// The underlying type of this Point
using Type = T;
/// The number of elements in this Point
const static std::size_t Size = 3;
/**
* Construct a Point with all elements initialized to Zero
*/
constexpr BasePoint() noexcept;
/**
* Construct a Point with all elements initialized to the given value
*
* @param v the value to assign to all elements of this Point
*/
constexpr explicit BasePoint(T const v) noexcept;
/**
* Construct a Vector with the given elements a,b,c -> x, y, z
* @param a value to assign to x
* @param b value to assign to y
* @param c value to assign to z
*/
constexpr BasePoint(T const a, T const b, T const c) noexcept;
/**
* Construct a Point using the given pointer. Note: It assumed the given
* pointer contains two values;
*/
explicit BasePoint(T *const v) noexcept;
/**
* Construct a Point using the values from the given std::array
*
* @param vals vals[0] is assigned to data[0] etc. etc.
*/
constexpr explicit BasePoint(std::array<T, Size> const &vals) noexcept;
/**
* Conversion Copy Constructor. Construct a Point using a Point with a
* different
* underlying type. Only simple type conversion is performed
*/
template <typename U>
constexpr explicit BasePoint(BasePoint<D, U, Size> const &other) noexcept;
/**
* Index operator
*
* @param i index into this Point
* @return a reference to the element at index i
*/
constexpr auto operator[](std::size_t i) noexcept -> T &;
/**
* Index operator
*
* @param i index into this Point
* @return a reference to the element at index i
*/
constexpr auto operator[](std::size_t i) const noexcept -> T const &;
/**
* Return an iterator to the first element of this Point
*
* @return an iterator pointing to the begining of this Point
*/
constexpr auto begin() noexcept -> T *;
/**
* Return an iterator to the first element of this Point
*
* @return an iterator pointing to the begining of this Point
*/
constexpr auto begin() const noexcept -> T *;
/**
* Return an iterator to the end of this Point.
*
* @return an iterator pointing to the end of this Point
*/
constexpr auto end() noexcept -> T *;
/**
* Return an iterator to the end of this Point.
*
* @return an iterator pointing to the end of this Point
*/
constexpr auto end() const noexcept -> T *;
public:
/**
* Anonymous union to allow access to members using different names
*/
union {
/// Data represented as a std::array
std::array<T, Size> data;
struct {
T x; ///< The first element
T y; ///<The second element
T z; ///<The third element
};
struct {
T r; ///< First element
T g; ///< Second element
T b; ///< Third element
};
};
};
/**
* Point four element specialization
*/
template <template <typename, std::size_t> class D, typename T>
class BasePoint<D, T, 4> {
/** @cond doxygen has issues with static_assert */
static_assert(std::is_arithmetic<T>::value,
"Underlying type must be a number");
/** @endcond */
public:
/// The underlying type of this Point
using Type = T;
/// The number of elements in this Point
const static std::size_t Size = 4;
/**
* Construct a Point with all elements initialized to Zero
*/
constexpr BasePoint() noexcept;
/**
* Construct a Point with all elements initialized to the given value
*
* @param v the value to assign to all elements of this Point
*/
constexpr explicit BasePoint(T const v) noexcept;
/**
* Construct a BasePoint with the given elements a,b,c, d -> x, y, z, w
* @param a value to assign to x
* @param b value to assign to y
* @param c value to assign to z
* @param d value to assign to w
*/
constexpr BasePoint(T const a, T const b, T const c, T const d) noexcept;
/**
* Construct a Point using the given pointer. Note: It assumed the given
* pointer contains two values;
*/
explicit BasePoint(T *const v) noexcept;
/**
* Construct a Point using the values from the given std::array
*
* @param vals vals[0] is assigned to data[0] etc. etc.
*/
constexpr explicit BasePoint(std::array<T, Size> const &vals) noexcept;
/**
* Conversion Copy Constructor. Construct a Point using a Point with a
* different
* underlying type. Only simple type conversion is performed
*/
template <typename U>
constexpr explicit BasePoint(BasePoint<D, U, Size> const &other) noexcept;
/**
* Index operator
*
* @param i index into this Point
* @return a reference to the element at index i
*/
constexpr auto operator[](std::size_t i) noexcept -> T &;
/**
* Index operator
*
* @param i index into this Point
* @return a reference to the element at index i
*/
constexpr auto operator[](std::size_t i) const noexcept -> T const &;
/**
* Return an iterator to the first element of this Point
*
* @return an iterator pointing to the begining of this Point
*/
constexpr auto begin() noexcept -> T *;
/**
* Return an iterator to the first element of this Point
*
* @return an iterator pointing to the begining of this Point
*/
constexpr auto begin() const noexcept -> T *;
/**
* Return an iterator to the end of this Point.
*
* @return an iterator pointing to the end of this Point
*/
constexpr auto end() noexcept -> T *;
/**
* Return an iterator to the end of this Point.
*
* @return an iterator pointing to the end of this Point
*/
constexpr auto end() const noexcept -> T *;
public:
/**
* Anonymous union to allow access to members using different names
*/
union {
/// Data represented as a std::array
std::array<T, Size> data;
struct {
T x; ///< The first element
T y; ///<The second element
T z; ///<The third element
T w; ///<The fourth element
};
// Allow access to elements with a different name
struct {
T r; ///< First Element
T g; ///< Second Element
T b; ///< Third Element
T a; ///< Fourth Element
};
};
};
/**
* Swap the contents of the two BasePoints
*/
template <template <typename, std::size_t> class D, typename T, std::size_t S>
auto swap(BasePoint<D, T, S> & rhs, BasePoint<D, T, S> & lhs)->void {
std::swap(rhs.data, lhs.data);
}
/**
* Returns the smallest element in the given BasePoint
*
* @param vec the BasePoint to search for a small element
* @return the smallest element of the given BasePoint
*/
template <template <typename, std::size_t> class D, typename T, std::size_t S>
inline auto min(BasePoint<D, T, S> const &vec)->T {
return *std::min_element(std::begin(vec), std::end(vec));
}
/**
* Returns the largest element in the given BasePoint
*
* @param vec the BasePoint to search for a large element
* @return the largest element in the given BasePoint
*/
template <template <typename, std::size_t> class D, typename T, std::size_t S>
inline auto max(BasePoint<D, T, S> const &vec)->T {
return *std::max_element(std::begin(vec), std::end(vec));
}
/**
* Returns the sum of all the elements in the given BasePoint
*
* @param vec the BasePoint to search for a large element
* @return the num of all of the elements of the given BasePoint
*/
template <template <typename, std::size_t> class D, typename T, std::size_t S>
inline auto sum(BasePoint<D, T, S> const &vec)->T {
return std::accumulate(std::begin(vec), std::end(vec), T(0));
}
////////////////////////////////////////////////////////////////////////////////
//// BasePoint() Impl
////////////////////////////////////////////////////////////////////////////////
// template<template<typename,std::size_t> class D,typename T, std::size_t S>
// inline constexpr BasePoint<D,T,S>::BasePoint() noexcept : data() {};
//
// template<template<typename,std::size_t> class D,typename T>
// inline constexpr BasePoint<D,T,2>::BasePoint() noexcept : data() {};
//////////////////////////////////////////////////////////////////////////////
// BasePoint() Impl
//////////////////////////////////////////////////////////////////////////////
template <template <typename, std::size_t> class D, typename T, std::size_t S>
inline constexpr BasePoint<D, T, S>::BasePoint() noexcept : data(){};
template <template <typename, std::size_t> class D, typename T>
inline constexpr BasePoint<D, T, 2>::BasePoint() noexcept : data(){};
template <template <typename, std::size_t> class D, typename T>
inline constexpr BasePoint<D, T, 3>::BasePoint() noexcept : data(){};
template <template <typename, std::size_t> class D, typename T>
inline constexpr BasePoint<D, T, 4>::BasePoint() noexcept : data(){};
//////////////////////////////////////////////////////////////////////////////
// BasePoint(T) Impl
//////////////////////////////////////////////////////////////////////////////
template <template <typename, std::size_t> class D, typename T, std::size_t S>
inline BasePoint<D, T, S>::BasePoint(T const v) noexcept {
data.fill(v);
}
template <template <typename, std::size_t> class D, typename T>
inline constexpr BasePoint<D, T, 2>::BasePoint(T const v) noexcept
: data{{v, v}} {}
template <template <typename, std::size_t> class D, typename T>
inline constexpr BasePoint<D, T, 3>::BasePoint(T const v) noexcept
: data{{v, v, v}} {}
template <template <typename, std::size_t> class D, typename T>
inline constexpr BasePoint<D, T, 4>::BasePoint(T const v) noexcept
: data{{v, v, v, v}} {}
//////////////////////////////////////////////////////////////////////////////
// BasePoint() Component Impl
//////////////////////////////////////////////////////////////////////////////
template <template <typename, std::size_t> class D, typename T>
inline constexpr BasePoint<D, T, 2>::BasePoint(T const a, T const b) noexcept
: x{a},
y{b} {}
template <template <typename, std::size_t> class D, typename T>
inline constexpr BasePoint<D, T, 3>::BasePoint(T const a, T const b,
T const c) noexcept : x{a},
y{b},
z{c} {}
template <template <typename, std::size_t> class D, typename T>
inline constexpr BasePoint<D, T, 4>::BasePoint(
T const a, T const b, T const c, T const d) noexcept : x{a},
y{b},
z{c},
w{d} {}
//////////////////////////////////////////////////////////////////////////////
// BasePoint(T*) Impl
//////////////////////////////////////////////////////////////////////////////
template <template <typename, std::size_t> class D, typename T, std::size_t S>
inline BasePoint<D, T, S>::BasePoint(T * const v) noexcept {
std::copy(std::begin(v), std::end(v), data.begin());
}
template <template <typename, std::size_t> class D, typename T>
inline BasePoint<D, T, 2>::BasePoint(T * const v) noexcept : x{v[0]},
y{v[1]} {}
template <template <typename, std::size_t> class D, typename T>
inline BasePoint<D, T, 3>::BasePoint(T * const v) noexcept : x{v[0]},
y{v[1]},
z{v[2]} {}
template <template <typename, std::size_t> class D, typename T>
inline BasePoint<D, T, 4>::BasePoint(T * const v) noexcept : x{v[0]},
y{v[1]},
z{v[2]},
w{v[3]} {}
//////////////////////////////////////////////////////////////////////////////
// BasePoint(std::array) Impl
//////////////////////////////////////////////////////////////////////////////
template <template <typename, std::size_t> class D, typename T, std::size_t S>
inline constexpr BasePoint<D, T, S>::BasePoint(
std::array<T, Size> const &vals) noexcept : data(vals) {}
template <template <typename, std::size_t> class D, typename T>
inline constexpr BasePoint<D, T, 2>::BasePoint(
std::array<T, Size> const &vals) noexcept : data(vals) {}
template <template <typename, std::size_t> class D, typename T>
inline constexpr BasePoint<D, T, 3>::BasePoint(
std::array<T, Size> const &vals) noexcept : data(vals) {}
template <template <typename, std::size_t> class D, typename T>
inline constexpr BasePoint<D, T, 4>::BasePoint(
std::array<T, Size> const &vals) noexcept : data(vals) {}
//////////////////////////////////////////////////////////////////////////////
// BasePoint(BasePoint<U>) Impl
//////////////////////////////////////////////////////////////////////////////
template <template <typename, std::size_t> class D, typename T, size_t S>
template <typename U, typename I>
inline constexpr BasePoint<D, T, S>::BasePoint(
BasePoint<D, U, Size> const &other) noexcept : BasePoint(other, I()) {}
template <template <typename, std::size_t> class D, typename T, size_t S>
template <typename U, std::size_t... I>
inline constexpr BasePoint<D, T, S>::BasePoint(
BasePoint<D, U, Size> const &other, std::index_sequence<I...>)noexcept
: data{{(T(other.data[I]))...}} {}
template <template <typename, std::size_t> class D, typename T>
template <typename U>
inline constexpr BasePoint<D, T, 2>::BasePoint(
BasePoint<D, U, Size> const &p) noexcept : data{{T(p.x), T(p.y)}} {}
template <template <typename, std::size_t> class D, typename T>
template <typename U>
inline constexpr BasePoint<D, T, 3>::BasePoint(
BasePoint<D, U, Size> const &other) noexcept
: data{{T(other[0]), T(other[1]), T(other[2])}} {}
template <template <typename, std::size_t> class D, typename T>
template <typename U>
inline constexpr BasePoint<D, T, 4>::BasePoint(
BasePoint<D, U, Size> const &other) noexcept
: data{{T(other[0]), T(other[1]), T(other[2]), T(other[3])}} {}
//////////////////////////////////////////////////////////////////////////////
// BasePoint::operator[] Impl
//////////////////////////////////////////////////////////////////////////////
template <template <typename, std::size_t> class D, typename T, std::size_t S>
inline constexpr auto BasePoint<D, T, S>::operator[](
std::size_t i) noexcept->T & {
return this->data[i];
}
template <template <typename, std::size_t> class D, typename T>
inline constexpr auto BasePoint<D, T, 2>::operator[](
std::size_t i) noexcept->T & {
return this->data[i];
}
template <template <typename, std::size_t> class D, typename T>
inline constexpr auto BasePoint<D, T, 3>::operator[](
std::size_t i) noexcept->T & {
return this->data[i];
}
template <template <typename, std::size_t> class D, typename T>
inline constexpr auto BasePoint<D, T, 4>::operator[](
std::size_t i) noexcept->T & {
return this->data[i];
}
template <template <typename, std::size_t> class D, typename T, std::size_t S>
inline constexpr auto BasePoint<D, T, S>::operator[](std::size_t i)
const noexcept->T const & {
return data[i];
}
template <template <typename, std::size_t> class D, typename T>
inline constexpr auto BasePoint<D, T, 2>::operator[](std::size_t i)
const noexcept->T const & {
return this->data[i];
}
template <template <typename, std::size_t> class D, typename T>
inline constexpr auto BasePoint<D, T, 3>::operator[](std::size_t i)
const noexcept->T const & {
return this->data[i];
}
template <template <typename, std::size_t> class D, typename T>
inline constexpr auto BasePoint<D, T, 4>::operator[](std::size_t i)
const noexcept->T const & {
return this->data[i];
}
//////////////////////////////////////////////////////////////////////////////
// BasePoint::begin() Impl
//////////////////////////////////////////////////////////////////////////////
template <template <typename, std::size_t> class D, typename T, std::size_t S>
inline constexpr auto BasePoint<D, T, S>::begin() noexcept->T * {
return data.begin();
}
template <template <typename, std::size_t> class D, typename T>
inline constexpr auto BasePoint<D, T, 2>::begin() noexcept->T * {
return data.begin();
}
template <template <typename, std::size_t> class D, typename T>
inline constexpr auto BasePoint<D, T, 3>::begin() noexcept->T * {
return data.begin();
}
template <template <typename, std::size_t> class D, typename T>
inline constexpr auto BasePoint<D, T, 4>::begin() noexcept->T * {
return data.begin();
}
template <template <typename, std::size_t> class D, typename T, std::size_t S>
inline constexpr auto BasePoint<D, T, S>::begin() const noexcept->T * {
return data.begin();
}
template <template <typename, std::size_t> class D, typename T>
inline constexpr auto BasePoint<D, T, 2>::begin() const noexcept->T * {
return data.begin();
}
template <template <typename, std::size_t> class D, typename T>
inline constexpr auto BasePoint<D, T, 3>::begin() const noexcept->T * {
return data.begin();
}
template <template <typename, std::size_t> class D, typename T>
inline constexpr auto BasePoint<D, T, 4>::begin() const noexcept->T * {
return data.begin();
}
//////////////////////////////////////////////////////////////////////////////
// BasePoint::end() Impl
//////////////////////////////////////////////////////////////////////////////
template <template <typename, std::size_t> class D, typename T, std::size_t S>
inline constexpr auto BasePoint<D, T, S>::end() noexcept->T * {
return data.end();
}
template <template <typename, std::size_t> class D, typename T>
inline constexpr auto BasePoint<D, T, 2>::end() noexcept->T * {
return data.end();
}
template <template <typename, std::size_t> class D, typename T>
inline constexpr auto BasePoint<D, T, 3>::end() noexcept->T * {
return data.end();
}
template <template <typename, std::size_t> class D, typename T>
inline constexpr auto BasePoint<D, T, 4>::end() noexcept->T * {
return data.end();
}
template <template <typename, std::size_t> class D, typename T, std::size_t S>
inline constexpr auto BasePoint<D, T, S>::end() const noexcept->T * {
return data.end();
}
template <template <typename, std::size_t> class D, typename T>
inline constexpr auto BasePoint<D, T, 2>::end() const noexcept->T * {
return data.end();
}
template <template <typename, std::size_t> class D, typename T>
inline constexpr auto BasePoint<D, T, 3>::end() const noexcept->T * {
return data.end();
}
template <template <typename, std::size_t> class D, typename T>
inline constexpr auto BasePoint<D, T, 4>::end() const noexcept->T * {
return data.end();
}
//////////////////////////////////////////////////////////////////////////////
// BasePoint::operator+= Impl
//////////////////////////////////////////////////////////////////////////////
template <template <typename, std::size_t> class D, typename T, std::size_t S>
inline auto operator+=(BasePoint<D, T, S> & lhs, BasePoint<D, T, S> & rhs)
->void {
std::transform(lhs.begin(), lhs.end(), rhs.begin(), lhs.begin(),
[](T l, T r) -> T { return l + r; });
}
//////////////////////////////////////////////////////////////////////////////
// BasePoint::operator-= Impl
//////////////////////////////////////////////////////////////////////////////
template <template <typename, std::size_t> class D, typename T, std::size_t S>
inline auto operator-=(BasePoint<D, T, S> & lhs, BasePoint<D, T, S> & rhs)
->void {
std::transform(lhs.begin(), lhs.end(), rhs.begin(), lhs.begin(),
[](T l, T r) -> T { return l - r; });
}
//////////////////////////////////////////////////////////////////////////////
// BasePoint::operator*= Impl
//////////////////////////////////////////////////////////////////////////////
template <template <typename, std::size_t> class D, typename T, std::size_t S>
inline auto operator*=(BasePoint<D, T, S> & lhs, T value)->void {
std::for_each(lhs.begin(), lhs.end(), [value](T &t) { t *= value; });
}
//////////////////////////////////////////////////////////////////////////////
// BasePoint::operator/= Impl
//////////////////////////////////////////////////////////////////////////////
template <template <typename, std::size_t> class D, typename T, std::size_t S>
inline auto operator/=(BasePoint<D, T, S> & lhs, T value)->void {
std::for_each(lhs.begin(), lhs.end(), [value](T &t) { t /= value; });
}
//////////////////////////////////////////////////////////////////////////////
// BasePoint::operator== Impl
//////////////////////////////////////////////////////////////////////////////
template <template <typename, std::size_t> class D, typename T, std::size_t S>
auto operator==(BasePoint<D, T, S> const &rhs, BasePoint<D, T, S> const &lhs)
->BasePoint<D, T, S> {
return rhs.data == rhs.data;
}
template <template <typename, std::size_t> class D, typename T, std::size_t S>
auto operator!=(BasePoint<D, T, S> const &rhs, BasePoint<D, T, S> const &lhs)
->BasePoint<D, T, S> {
return !(rhs.data == rhs.data);
}
//////////////////////////////////////////////////////////////////////////////
// BasePoint::operator+ Impl
//////////////////////////////////////////////////////////////////////////////
template <template <typename, std::size_t> class D, typename T, std::size_t S>
auto operator+(BasePoint<D, T, S> rhs, BasePoint<D, T, S> const &lhs)
->BasePoint<D, T, S> {
rhs += lhs;
return rhs;
}
//////////////////////////////////////////////////////////////////////////////
// BasePoint::operator- Impl
//////////////////////////////////////////////////////////////////////////////
template <template <typename, std::size_t> class D, typename T, std::size_t S>
auto operator-(BasePoint<D, T, S> vec)->BasePoint<D, T, S> {
std::transform(vec.begin(), vec.end(), vec.begin(), std::negate<T>());
return vec;
}
template <template <typename, std::size_t> class D, typename T, std::size_t S>
auto operator-(BasePoint<D, T, S> rhs, BasePoint<D, T, S> const &lhs)
->BasePoint<D, T, S> {
rhs -= lhs;
return rhs;
}
//////////////////////////////////////////////////////////////////////////////
// BasePoint::operator* Impl
//////////////////////////////////////////////////////////////////////////////
template <template <typename, std::size_t> class D, typename T, std::size_t S>
auto operator*(BasePoint<D, T, S> rhs, T lhs)->BasePoint<D, T, S> {
rhs *= lhs;
return rhs;
}
//////////////////////////////////////////////////////////////////////////////
// BasePoint::operator/ Impl
//////////////////////////////////////////////////////////////////////////////
template <template <typename, std::size_t> class D, typename T, std::size_t S>
auto operator/(BasePoint<D, T, S> rhs, T lhs)->BasePoint<D, T, S> {
rhs /= lhs;
return rhs;
}
//////////////////////////////////////////////////////////////////////////////
// BasePoint::operator<< Impl
//////////////////////////////////////////////////////////////////////////////
template <template <typename, std::size_t> class D, typename T, std::size_t S>
std::ostream &operator<<(std::ostream & sink, BasePoint<D, T, S> const &vec) {
sink << "( ";
std::for_each(vec.begin(), vec.end() - 1,
[&sink](T &v) { sink << v << ", "; });
sink << vec[S - 1] << " )";
return sink;
}
} // namespace cagey::math
| 34.750266 | 82 | 0.55208 | theycallmecoach |
9603020de6c69df040ff3512875e9dc04a7adb7b | 70,508 | cpp | C++ | piLibs/src/libRender/opengl4x/piGL4X_Renderer.cpp | Livictor213/testing2 | 4121cbb23ec6cb55d8aad3524d1dc029165c8532 | [
"MIT"
] | 6 | 2021-03-27T01:54:55.000Z | 2021-12-15T22:50:28.000Z | piLibs/src/libRender/opengl4x/piGL4X_Renderer.cpp | Livictor213/testing2 | 4121cbb23ec6cb55d8aad3524d1dc029165c8532 | [
"MIT"
] | null | null | null | piLibs/src/libRender/opengl4x/piGL4X_Renderer.cpp | Livictor213/testing2 | 4121cbb23ec6cb55d8aad3524d1dc029165c8532 | [
"MIT"
] | null | null | null | #define USETEXTURECACHE
#include <malloc.h>
#include <stdio.h>
#define GLCOREARB_PROTOTYPES
#include "glcorearb.h"
#include "piGL4X_Renderer.h"
#include "piGL4X_Ext.h"
#include "piGL4X_RenderContext.h"
#include "../../libSystem/piStr.h"
namespace piLibs {
typedef struct
{
unsigned int mProgID;
}piIShader;
typedef struct
{
GLuint64 mHandle;
piTextureInfo mInfo;
piTextureFilter mFilter;
piTextureWrap mWrap;
unsigned int mObjectID;
bool mIsResident;
}piITexture;
typedef struct
{
wchar_t *mKey;
piITexture *mTexture;
int mReference;
}TextureSlot;
typedef struct
{
unsigned int mObjectID;
// int mNumStreams;
// piRArrayLayout mStreams[2];
}piIVertexArray;
typedef struct
{
unsigned int mObjectID;
//void *mPtr;
unsigned int mSize;
//GLsync mSync;
}piIBuffer;
typedef struct
{
unsigned int mObjectID;
}piISampler;
typedef struct
{
unsigned int mObjectID;
unsigned int mSamples;
unsigned int mXres;
unsigned int mYres;
}piIRTarget;
static int unidades[32] = { GL_TEXTURE0, GL_TEXTURE1, GL_TEXTURE2, GL_TEXTURE3,
GL_TEXTURE4, GL_TEXTURE5, GL_TEXTURE6, GL_TEXTURE7,
GL_TEXTURE8, GL_TEXTURE9, GL_TEXTURE10, GL_TEXTURE11,
GL_TEXTURE12, GL_TEXTURE13, GL_TEXTURE14, GL_TEXTURE15,
GL_TEXTURE16, GL_TEXTURE17, GL_TEXTURE18, GL_TEXTURE19,
GL_TEXTURE20, GL_TEXTURE21, GL_TEXTURE22, GL_TEXTURE23,
GL_TEXTURE24, GL_TEXTURE25, GL_TEXTURE26, GL_TEXTURE27,
GL_TEXTURE28, GL_TEXTURE29, GL_TEXTURE30, GL_TEXTURE31 };
static int format2gl( int format, int *bpp, int *mode, int *moInternal, int *mode3, int compressed )
{
switch( format )
{
case piFORMAT_C1I8: *bpp = 1; *mode = GL_RED; *moInternal = GL_R8; *mode3 = GL_UNSIGNED_BYTE; if (compressed) *moInternal = GL_COMPRESSED_RED; break;
case piFORMAT_C2I8: *bpp = 2; *mode = GL_RG; *moInternal = GL_RG8; *mode3 = GL_UNSIGNED_BYTE; if (compressed) *moInternal = GL_COMPRESSED_RGB; break;
case piFORMAT_C3I8: *bpp = 3; *mode = GL_RGB; *moInternal = GL_RGB8; *mode3 = GL_UNSIGNED_BYTE; if (compressed) *moInternal = GL_COMPRESSED_RGB; break;
case piFORMAT_C4I8: *bpp = 4; *mode = GL_BGRA; *moInternal = GL_RGBA8; *mode3 = GL_UNSIGNED_BYTE; if (compressed) *moInternal = GL_COMPRESSED_RGBA; break;
case piFORMAT_D24: *bpp = 4; *mode = GL_DEPTH_COMPONENT; *moInternal = GL_DEPTH_COMPONENT24; *mode3 = GL_UNSIGNED_BYTE; break;
case piFORMAT_D32F: *bpp = 4; *mode = GL_DEPTH_COMPONENT; *moInternal = GL_DEPTH_COMPONENT32F; *mode3 = GL_FLOAT; break;
case piFORMAT_C1F16: *bpp = 2; *mode = GL_RED; *moInternal = GL_R16F; *mode3 = GL_FLOAT; break;
case piFORMAT_C2F16: *bpp = 4; *mode = GL_RG; *moInternal = GL_RG16F; *mode3 = GL_FLOAT; break;
case piFORMAT_C3F16: *bpp = 6; *mode = GL_RGB; *moInternal = GL_RGB16F; *mode3 = GL_FLOAT; break;
case piFORMAT_C4F16: *bpp = 8; *mode = GL_RGBA; *moInternal = GL_RGBA16F; *mode3 = GL_FLOAT; break;
case piFORMAT_C1F32: *bpp = 4; *mode = GL_RED; *moInternal = GL_R32F; *mode3 = GL_FLOAT; break;
case piFORMAT_C4F32: *bpp = 16; *mode = GL_RGBA; *moInternal = GL_RGBA32F; *mode3 = GL_FLOAT; break;
case piFORMAT_C1I8I: *bpp = 1; *mode = GL_RED_INTEGER; *moInternal = GL_R8UI; *mode3 = GL_UNSIGNED_BYTE; break;
case piFORMAT_C1I16I: *bpp = 2; *mode = GL_RED_INTEGER; *moInternal = GL_R16UI; *mode3 = GL_UNSIGNED_SHORT; break;
case piFORMAT_C1I32I: *bpp = 4; *mode = GL_RED_INTEGER; *moInternal = GL_R32UI; *mode3 = GL_UNSIGNED_INT; break;
case piFORMAT_C4I1010102: *bpp = 4; *mode = GL_BGRA; *moInternal = GL_RGB10_A2; *mode3 = GL_UNSIGNED_BYTE; break;
case piFORMAT_C3I111110: *bpp = 4; *mode = GL_BGRA; *moInternal = GL_R11F_G11F_B10F; *mode3 = GL_UNSIGNED_BYTE; break;
default: return( 0 );
}
return( 1 );
}
static uint64 piTexture_GetMem( const piITexture *me )
{
int mode, fInternal, mode3, bpp;
if( !format2gl( me->mInfo.mFormat, &bpp, &mode, &fInternal, &mode3, me->mInfo.mCompressed ) ) return 0;
return me->mInfo.mXres * me->mInfo.mYres * me->mInfo.mZres * bpp;
}
//static const unsigned int filter2gl[] = { GL_NEAREST, GL_LINEAR, GL_LINEAR_MIPMAP_LINEAR };
static const unsigned int wrap2gl[] = { GL_CLAMP_TO_BORDER, GL_CLAMP_TO_EDGE, GL_REPEAT, GL_MIRROR_CLAMP_TO_EDGE, GL_MIRRORED_REPEAT };
static const unsigned int glType[] = { GL_UNSIGNED_BYTE, GL_FLOAT, GL_INT, GL_DOUBLE, GL_HALF_FLOAT };
static const unsigned int glSizeof[] = { 1, 4, 4, 8, 2};
//---------------------------------------------
piRendererGL4X::piRendererGL4X():piRenderer()
{
}
piRendererGL4X::~piRendererGL4X()
{
}
static const float verts2f[] = { -1.0f, 1.0f,
-1.0f, -1.0f,
1.0f, 1.0f,
1.0f, -1.0f };
static const float verts3f[] = {
-1.0f, -1.0f, -1.0f,
-1.0f, -1.0f, 1.0f,
-1.0f, 1.0f, -1.0f,
-1.0f, 1.0f, 1.0f,
1.0f, 1.0f, -1.0f,
1.0f, 1.0f, 1.0f,
1.0f, -1.0f, -1.0f,
1.0f, -1.0f, 1.0f,
1.0f, 1.0f, 1.0f,
1.0f, 1.0f, -1.0f,
-1.0f, 1.0f, 1.0f,
-1.0f, 1.0f, -1.0f,
1.0f, -1.0f, -1.0f,
1.0f, -1.0f, 1.0f,
-1.0f, -1.0f, -1.0f,
-1.0f, -1.0f, 1.0f,
-1.0f, 1.0f, 1.0f,
-1.0f, -1.0f, 1.0f,
1.0f, 1.0f, 1.0f,
1.0f, -1.0f, 1.0f,
-1.0f, -1.0f, -1.0f,
-1.0f, 1.0f, -1.0f,
1.0f, -1.0f, -1.0f,
1.0f, 1.0f, -1.0f };
static const float verts3f3f[] = {
-1.0f, -1.0f, -1.0f, -1.0f, 0.0f, 0.0f,
-1.0f, -1.0f, 1.0f, -1.0f, 0.0f, 0.0f,
-1.0f, 1.0f, -1.0f, -1.0f, 0.0f, 0.0f,
-1.0f, 1.0f, 1.0f, -1.0f, 0.0f, 0.0f,
1.0f, 1.0f, -1.0f, 1.0f, 0.0f, 0.0f,
1.0f, 1.0f, 1.0f, 1.0f, 0.0f, 0.0f,
1.0f, -1.0f, -1.0f, 1.0f, 0.0f, 0.0f,
1.0f, -1.0f, 1.0f, 1.0f, 0.0f, 0.0f,
1.0f, 1.0f, 1.0f, 0.0f, 1.0f, 0.0f,
1.0f, 1.0f, -1.0f, 0.0f, 1.0f, 0.0f,
-1.0f, 1.0f, 1.0f, 0.0f, 1.0f, 0.0f,
-1.0f, 1.0f, -1.0f, 0.0f, 1.0f, 0.0f,
1.0f, -1.0f, -1.0f, 0.0f, -1.0f, 0.0f,
1.0f, -1.0f, 1.0f, 0.0f, -1.0f, 0.0f,
-1.0f, -1.0f, -1.0f, 0.0f, -1.0f, 0.0f,
-1.0f, -1.0f, 1.0f, 0.0f, -1.0f, 0.0f,
-1.0f, 1.0f, 1.0f, 0.0f, 0.0f, 1.0f,
-1.0f, -1.0f, 1.0f, 0.0f, 0.0f, 1.0f,
1.0f, 1.0f, 1.0f, 0.0f, 0.0f, 1.0f,
1.0f, -1.0f, 1.0f, 0.0f, 0.0f, 1.0f,
-1.0f, -1.0f, -1.0f, 0.0f, 0.0f, -1.0f,
-1.0f, 1.0f, -1.0f, 0.0f, 0.0f, -1.0f,
1.0f, -1.0f, -1.0f, 0.0f, 0.0f, -1.0f,
1.0f, 1.0f, -1.0f, 0.0f, 0.0f, -1.0f };
void CALLBACK piRendererGL4X::DebugLog( GLenum source, GLenum type, GLuint id, GLenum severity, GLsizei length, const GLchar *message, const void *vme )
{
piRendererGL4X *me = (piRendererGL4X*)vme;
if( !me->mReporter ) return;
const char *sources = "Unknown";
if( source==GL_DEBUG_SOURCE_API_ARB ) sources = "API";
if( source==GL_DEBUG_SOURCE_WINDOW_SYSTEM_ARB ) sources = "OS";
if( source==GL_DEBUG_SOURCE_SHADER_COMPILER_ARB ) sources = "Shader Compiler";
if( source==GL_DEBUG_SOURCE_THIRD_PARTY_ARB ) sources = "Third Party";
if( source==GL_DEBUG_SOURCE_APPLICATION_ARB ) sources = "Application";
const char *types = "Unknown";
if( type==GL_DEBUG_TYPE_ERROR_ARB ) types = "Error";
if( type==GL_DEBUG_TYPE_DEPRECATED_BEHAVIOR_ARB ) types = "Deprecated Behavior";
if( type==GL_DEBUG_TYPE_UNDEFINED_BEHAVIOR_ARB ) types = "Undefined Behavior";
if( type==GL_DEBUG_TYPE_PORTABILITY_ARB ) types = "Portability";
if( type==GL_DEBUG_TYPE_PERFORMANCE_ARB ) types = "Performance";
int severitiID = 0;
const char *severities = "Unknown";
if( severity==GL_DEBUG_SEVERITY_HIGH_ARB ) { severitiID = 2; severities = "High"; }
if( severity==GL_DEBUG_SEVERITY_MEDIUM_ARB ) { severitiID = 1; severities = "Medium"; }
if( severity==GL_DEBUG_SEVERITY_LOW_ARB ) { severitiID = 0; severities = "Low"; }
if( severity!=GL_DEBUG_SEVERITY_HIGH_ARB ) return;
char tmp[2048];
pisprintf( tmp, sizeof(tmp), "Renderer Error, source = \"%s\", type = \"%s\", severity = \"%s\", description = \"%s\"", sources, types, severities, message );
me->mReporter->Error( tmp, severitiID );
}
void piRendererGL4X::PrintInfo( void )
{
if( !mReporter ) return;
char *str = (char*)malloc( 65536 );
if( !str ) return;
int nume = 0;
glGetIntegerv(GL_NUM_EXTENSIONS, &nume);
sprintf( str, "OpenGL %s\nGLSL %s\n%s by %s\n%d extensions\n", (const char*)glGetString( GL_VERSION ), (const char*)glGetString( GL_SHADING_LANGUAGE_VERSION ),
(const char*)glGetString( GL_RENDERER ), (const char*)glGetString( GL_VENDOR ), nume );
#if 1
for( int i=0; i<nume; i++ )
{
strcat( str, (char const*)oglGetStringi(GL_EXTENSIONS, i) );
strcat( str, "\n" );
}
#endif
mReporter->Info( str );
free( str );
}
bool piRendererGL4X::Initialize(int id, const void **hwnd, int num, bool disableVSync, piRenderReporter *reporter)
{
mID = id;
mBindedTarget = nullptr;
mReporter = reporter;
mMngTexSlots = nullptr;
mRC = new piGL4X_RenderContext();
if( !mRC )
return false;
if (!mRC->Create(hwnd, num, disableVSync, true, true))
{
mRC->Delete();
return false;
}
mRC->Enable();
mExt = piGL4X_Ext_Init(reporter);
if( !mExt )
return false;
int maxZMultisample, maxCMultisample, maxGSInvocations, maxTextureUnits, maxVerticesPerPatch;
glGetIntegerv( GL_MAX_DEPTH_TEXTURE_SAMPLES, &maxZMultisample );
glGetIntegerv( GL_MAX_COLOR_TEXTURE_SAMPLES, &maxCMultisample );
glGetIntegerv( GL_MAX_GEOMETRY_SHADER_INVOCATIONS, &maxGSInvocations );
glGetIntegerv( GL_MAX_COMBINED_TEXTURE_IMAGE_UNITS, &maxTextureUnits );
glGetIntegerv(GL_MAX_PATCH_VERTICES, &maxVerticesPerPatch );
if( reporter )
{
char str[256];
sprintf( str, "Num Texture Units: %d", maxTextureUnits ); reporter->Info( str );
sprintf( str, "Max Vertex per Patch: %d", maxVerticesPerPatch); reporter->Info(str);
sprintf( str, "Max GS invocations: %d", maxGSInvocations); reporter->Info(str);
}
//--- texture management ---
mMngTexMax = 512;
mMngTexMemCurrent = 0;
mMngTexMemPeak = 0;
mMngTexNumCurrent = 0;
mMngTexNumPeak = 0;
mMngTexSlots = (TextureSlot*)malloc( mMngTexMax*sizeof(TextureSlot) );
if( !mMngTexSlots )
return false;
memset( mMngTexSlots, 0, mMngTexMax*sizeof(TextureSlot) );
//////////////
mVBO[0] = this->CreateBuffer(verts2f, sizeof(verts2f), piBufferType_Static);
mVBO[1] = this->CreateBuffer(verts3f3f, sizeof(verts3f3f), piBufferType_Static);
mVBO[2] = this->CreateBuffer(verts3f, sizeof(verts3f), piBufferType_Static);
const piRArrayLayout lay0 = { 2 * sizeof(float), 1, 0, { { 2, piRArrayType_Float, false } } };
const piRArrayLayout lay1 = { 6 * sizeof(float), 2, 0, { { 3, piRArrayType_Float, false }, { 3, piRArrayType_Float, false } } };
const piRArrayLayout lay2 = { 3 * sizeof(float), 1, 0, { { 3, piRArrayType_Float, false } } };
const piRArrayLayout lay3 = { 2 * sizeof(float), 1, 0, { { 2, piRArrayType_Float, false } } };
const piRArrayLayout lay4 = { 4 * sizeof(float), 2, 0, { { 2, piRArrayType_Float, false }, { 2, piRArrayType_Float, false } } };
mVA[0] = this->CreateVertexArray(1, mVBO[0], &lay0, nullptr, nullptr, nullptr);
mVA[1] = this->CreateVertexArray(1, mVBO[1], &lay1, nullptr, nullptr, nullptr);
mVA[2] = this->CreateVertexArray(1, mVBO[2], &lay2, nullptr, nullptr, nullptr);
// set log
if( reporter )
{
oglDebugMessageCallback( DebugLog, this );
oglDebugMessageControl( GL_DONT_CARE, GL_DONT_CARE,GL_DONT_CARE, 0, 0, GL_TRUE );
glEnable( GL_DEBUG_OUTPUT );
glEnable( GL_DEBUG_OUTPUT_SYNCHRONOUS );
}
glDisable(GL_DITHER);
glDepthFunc(GL_LEQUAL);
glHint( GL_FRAGMENT_SHADER_DERIVATIVE_HINT, GL_NICEST );
glHint(GL_POLYGON_SMOOTH_HINT, GL_NICEST );
PrintInfo();
return true;
}
void piRendererGL4X::SetActiveWindow( int id )
{
mRC->SetActiveWindow( id );
}
void piRendererGL4X::Enable(void)
{
mRC->Enable();
}
void piRendererGL4X::Disable(void)
{
mRC->Disable(false);
}
void piRendererGL4X::Report( void )
{
if( !mReporter ) return;
mReporter->Begin( mMngTexMemCurrent, mMngTexMemPeak, mMngTexNumCurrent, mMngTexNumPeak );
if( mMngTexNumCurrent!=0 )
{
TextureSlot *slots = (TextureSlot*)mMngTexSlots;
for( int i=0; i<mMngTexNumCurrent; i++ )
{
mReporter->Texture( slots[i].mKey,
piTexture_GetMem( slots[i].mTexture ) >> 10L,
slots[i].mTexture->mInfo.mFormat,
slots[i].mTexture->mInfo.mCompressed,
slots[i].mTexture->mInfo.mXres,
slots[i].mTexture->mInfo.mYres,
slots[i].mTexture->mInfo.mZres );
}
}
mReporter->End();
}
void piRendererGL4X::Deinitialize( void )
{
//--- texture management ---
if( mMngTexSlots!=nullptr) free( mMngTexSlots );
this->DestroyVertexArray(mVA[0]);
this->DestroyVertexArray(mVA[1]);
this->DestroyVertexArray(mVA[2]);
this->DestroyBuffer(mVBO[0]);
this->DestroyBuffer(mVBO[1]);
this->DestroyBuffer(mVBO[2]);
piGL4X_Ext_Free( (NGLEXTINFO*)mExt );
mRC->Disable( false );
mRC->Destroy();
mRC->Delete();
delete mRC;
}
void piRendererGL4X::SwapBuffers( void )
{
//glFlush();
mRC->SwapBuffers();
}
static int check_framebuffer( NGLEXTINFO *mExt )
{
GLenum status;
status = oglCheckFramebufferStatus(GL_FRAMEBUFFER);
switch( status )
{
case GL_FRAMEBUFFER_COMPLETE:
break;
case GL_FRAMEBUFFER_UNSUPPORTED:
break;
case GL_FRAMEBUFFER_INCOMPLETE_MISSING_ATTACHMENT:
return 0;
case GL_FRAMEBUFFER_INCOMPLETE_DRAW_BUFFER:
return 0;
case GL_FRAMEBUFFER_INCOMPLETE_READ_BUFFER:
return 0;
default:
return 0;
}
if( status!=GL_FRAMEBUFFER_COMPLETE )
return 0;
return 1;
}
void piRendererGL4X::SetShadingSamples( int shadingSamples )
{
piIRTarget *rt = (piIRTarget*)mBindedTarget;
if( shadingSamples>1 && rt!=NULL )
{
glEnable( GL_SAMPLE_SHADING );
oglMinSampleShading( (float)shadingSamples/(float)rt->mSamples );
}
else
{
glDisable( GL_SAMPLE_SHADING );
}
}
piRTarget piRendererGL4X::CreateRenderTarget( piTexture vtex0, piTexture vtex1, piTexture vtex2, piTexture vtex3, piTexture zbuf )
{
const piITexture *tex[4] = { (piITexture*)vtex0, (piITexture*)vtex1, (piITexture*)vtex2, (piITexture*)vtex3 };
const piITexture *zbu = (piITexture*)zbuf;
piIRTarget *me = (piIRTarget*)malloc( sizeof(piIRTarget) );
if( !me )
return nullptr;
me->mObjectID = 0;
bool hasLayers = false;
bool found = false;
for( int i=0; i<4; i++ )
{
if( !tex[i] ) continue;
me->mSamples = tex[i]->mInfo.mMultisample;
me->mXres = tex[i]->mInfo.mXres;
me->mYres = tex[i]->mInfo.mYres;
//hasLayers = (tex[i]->mInfo.mType == piTEXTURE_CUBE);
//hasLayers = (tex[i]->mInfo.mType == piTEXTURE_2D_ARRAY);
found = true;
break;
}
if( !found )
{
if( zbu )
{
me->mSamples = zbu->mInfo.mMultisample;
me->mXres = zbu->mInfo.mXres;
me->mYres = zbu->mInfo.mYres;
found = true;
}
}
if (!found) {
free(me);
return nullptr;
}
oglCreateFramebuffers(1, (GLuint*)&me->mObjectID);
if( zbu )
{
if (hasLayers )
oglNamedFramebufferTextureLayer(me->mObjectID, GL_DEPTH_ATTACHMENT, zbu->mObjectID, 0, 0);
else
oglNamedFramebufferTexture(me->mObjectID, GL_DEPTH_ATTACHMENT, zbu->mObjectID, 0);
}
else
{
if (hasLayers)
oglNamedFramebufferTextureLayer(me->mObjectID, GL_DEPTH_ATTACHMENT, 0, 0, 0);
else
oglNamedFramebufferTexture(me->mObjectID, GL_DEPTH_ATTACHMENT, 0, 0);
}
GLenum mMRT[4];
int mNumMRT = 0;
for( int i=0; i<4; i++ )
{
if( tex[i] )
{
if (hasLayers)
oglNamedFramebufferTextureLayer(me->mObjectID, GL_COLOR_ATTACHMENT0 + i, tex[i]->mObjectID, 0, 0);
else
oglNamedFramebufferTexture(me->mObjectID, GL_COLOR_ATTACHMENT0 + i, tex[i]->mObjectID, 0);
mMRT[i] = GL_COLOR_ATTACHMENT0 + i;
mNumMRT++;
}
else
{
if (hasLayers)
oglNamedFramebufferTextureLayer(me->mObjectID, GL_COLOR_ATTACHMENT0 + i, 0, 0, 0);
else
oglNamedFramebufferTexture(me->mObjectID, GL_COLOR_ATTACHMENT0 + i, 0, 0);
mMRT[i] = 0;
}
}
oglNamedFramebufferDrawBuffers(me->mObjectID, mNumMRT, mMRT);
GLenum st = oglCheckNamedFramebufferStatus(me->mObjectID, GL_FRAMEBUFFER);
if (st != GL_FRAMEBUFFER_COMPLETE)
return nullptr;
return me;
}
void piRendererGL4X::DestroyRenderTarget( piRTarget obj )
{
piIRTarget *me = (piIRTarget*)obj;
oglDeleteFramebuffers( 1, (GLuint*)&me->mObjectID );
}
void piRendererGL4X::RenderTargetSampleLocations(piRTarget vdst, const float *locations )
{
/*
const piIRTarget *dst = (piIRTarget*)vdst;
if( locations==nullptr )
{
oglNamedFramebufferParameteri(dst->mObjectID, GL_FRAMEBUFFER_PROGRAMMABLE_SAMPLE_LOCATIONS_ARB, 0);
}
else
{
oglNamedFramebufferParameteri(dst->mObjectID, GL_FRAMEBUFFER_PROGRAMMABLE_SAMPLE_LOCATIONS_ARB, 1);
oglNamedFramebufferSampleLocationsfv(dst->mObjectID, 0, dst->mSamples, locations);
}
*/
}
void piRendererGL4X::RenderTargetGetDefaultSampleLocation(piRTarget vdst, const int id, float *location)
{
const piIRTarget *dst = (piIRTarget*)vdst;
oglGetMultisamplefv( GL_SAMPLE_LOCATION_ARB, id, location);
}
void piRendererGL4X::BlitRenderTarget( piRTarget vdst, piRTarget vsrc, bool color, bool depth )
{
const piIRTarget *src = (piIRTarget*)vsrc;
const piIRTarget *dst = (piIRTarget*)vdst;
int flag = 0;
if( color ) flag += GL_COLOR_BUFFER_BIT;
if( depth ) flag += GL_DEPTH_BUFFER_BIT;
const GLenum mMRT[1] = { GL_COLOR_ATTACHMENT0 };
oglNamedFramebufferDrawBuffers(dst->mObjectID, 1, mMRT);
oglBlitNamedFramebuffer( src->mObjectID, dst->mObjectID,
0, 0, dst->mXres, dst->mYres,
0, 0, dst->mXres, dst->mYres,
flag, GL_NEAREST );
}
bool piRendererGL4X::SetRenderTarget( piRTarget obj )
{
if( obj==NULL )
{
mBindedTarget = NULL;
oglBindFramebuffer( GL_FRAMEBUFFER, 0 );
const GLenum zeros[4] = { 0, 0, 0, 0 };// { GL_NONE, GL_NONE, GL_NONE, GL_NONE };// segun la especificacion...
oglDrawBuffers(4, zeros);
glDrawBuffer(GL_BACK);
//glReadBuffer(GL_BACK);
//glDisable(GL_MULTISAMPLE);
}
else
{
piIRTarget *me = (piIRTarget*)obj;
mBindedTarget = obj;
oglBindFramebuffer( GL_FRAMEBUFFER, me->mObjectID );
//glEnable(GL_FRAMEBUFFER_SRGB);
if( me->mSamples>1 )
{
glEnable(GL_MULTISAMPLE);
}
else
{
glDisable(GL_MULTISAMPLE);
}
}
return true;
}
void piRendererGL4X::SetViewport( int id, const int *vp )
{
//glViewport( vp[0], vp[1], vp[2], vp[3] );
oglViewportIndexedf(id, float(vp[0]), float(vp[1]), float(vp[2]), float(vp[3]) );
}
//===========================================================================================================================================
static int ilog2i(int x) { int r = 0; while (x >>= 1) r++; return r; }
static piITexture *piITexture_Create( const piTextureInfo *info, piTextureFilter rfilter, piTextureWrap rwrap, float aniso, void *buffer, void *mExt )
{
int mode, moInternal, mode3, bpp;
if (!format2gl(info->mFormat, &bpp, &mode, &moInternal, &mode3, info->mCompressed))
return nullptr;
piITexture *me = (piITexture*)malloc( sizeof(piITexture) );
if( !me )
return nullptr;
me->mHandle = 0;
me->mIsResident = false;
me->mInfo = *info;
me->mFilter = rfilter;
me->mWrap = rwrap;
//const int filter = filter2gl[ rfilter ];
const int wrap = wrap2gl[ rwrap ];
if( info->mType==piTEXTURE_2D )
{
if (info->mMultisample>1)
{
oglCreateTextures(GL_TEXTURE_2D_MULTISAMPLE, 1, &me->mObjectID);
oglTextureStorage2DMultisample(me->mObjectID, info->mMultisample, moInternal, info->mXres, info->mYres, GL_FALSE);
}
else
{
oglCreateTextures(GL_TEXTURE_2D, 1, &me->mObjectID);
switch (rfilter)
{
case piFILTER_NONE:
if (moInternal == GL_DEPTH_COMPONENT24)
{
oglTextureStorage2D(me->mObjectID, 1, GL_DEPTH_COMPONENT24, info->mXres, info->mYres);
oglTextureParameteri(me->mObjectID, GL_TEXTURE_COMPARE_MODE, GL_NONE);
}
else
{
oglTextureStorage2D(me->mObjectID, 1, moInternal, info->mXres, info->mYres);
if (buffer) oglTextureSubImage2D(me->mObjectID, 0, 0, 0, info->mXres, info->mYres, mode, mode3, buffer);
}
oglTextureParameteri(me->mObjectID, GL_TEXTURE_BASE_LEVEL, 0);
oglTextureParameteri(me->mObjectID, GL_TEXTURE_MAX_LEVEL, 0);
oglTextureParameteri(me->mObjectID, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
oglTextureParameteri(me->mObjectID, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
oglTextureParameteri(me->mObjectID, GL_TEXTURE_WRAP_S, wrap);
oglTextureParameteri(me->mObjectID, GL_TEXTURE_WRAP_T, wrap);
break;
case piFILTER_LINEAR:
if (moInternal == GL_DEPTH_COMPONENT24)
{
oglTextureStorage2D(me->mObjectID, 1, GL_DEPTH_COMPONENT24, info->mXres, info->mYres);
oglTextureParameteri(me->mObjectID, GL_TEXTURE_COMPARE_MODE, GL_NONE);
}
else
{
oglTextureStorage2D(me->mObjectID, 1, moInternal, info->mXres, info->mYres);
if( buffer ) oglTextureSubImage2D(me->mObjectID, 0, 0, 0, info->mXres, info->mYres, mode, mode3, buffer);
}
oglTextureParameteri(me->mObjectID, GL_TEXTURE_BASE_LEVEL, 0);
oglTextureParameteri(me->mObjectID, GL_TEXTURE_MAX_LEVEL, 0);
oglTextureParameteri(me->mObjectID, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
oglTextureParameteri(me->mObjectID, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
oglTextureParameteri(me->mObjectID, GL_TEXTURE_WRAP_S, wrap);
oglTextureParameteri(me->mObjectID, GL_TEXTURE_WRAP_T, wrap);
break;
case piFILTER_PCF:
if (moInternal == GL_DEPTH_COMPONENT24)
{
oglTextureStorage2D(me->mObjectID, 1, GL_DEPTH_COMPONENT24, info->mXres, info->mYres);
oglTextureParameteri(me->mObjectID, GL_TEXTURE_COMPARE_MODE, GL_COMPARE_REF_TO_TEXTURE);
oglTextureParameteri(me->mObjectID, GL_TEXTURE_COMPARE_FUNC, GL_LEQUAL);
}
else
{
return nullptr;
//oglTextureStorage2D(me->mObjectID, 1, moInternal, info->mXres, info->mYres);
//if (buffer) oglTextureSubImage2D(me->mObjectID, 0, 0, 0, info->mXres, info->mYres, mode, mode3, buffer);
}
oglTextureParameteri(me->mObjectID, GL_TEXTURE_BASE_LEVEL, 0);
oglTextureParameteri(me->mObjectID, GL_TEXTURE_MAX_LEVEL, 0);
oglTextureParameteri(me->mObjectID, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
oglTextureParameteri(me->mObjectID, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
oglTextureParameteri(me->mObjectID, GL_TEXTURE_WRAP_S, wrap);
oglTextureParameteri(me->mObjectID, GL_TEXTURE_WRAP_T, wrap);
break;
case piFILTER_MIPMAP:
{
const int numMipmaps = ilog2i(info->mXres );
oglTextureStorage2D(me->mObjectID, numMipmaps, moInternal, info->mXres, info->mYres);
if (buffer) oglTextureSubImage2D(me->mObjectID, 0, 0, 0, info->mXres, info->mYres, mode, mode3, buffer);
oglGenerateTextureMipmap(me->mObjectID);
oglTextureParameteri(me->mObjectID, GL_TEXTURE_BASE_LEVEL, 0);
oglTextureParameteri(me->mObjectID, GL_TEXTURE_MAX_LEVEL, numMipmaps);
oglTextureParameteri(me->mObjectID, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
oglTextureParameteri(me->mObjectID, GL_TEXTURE_MIN_FILTER, GL_LINEAR_MIPMAP_LINEAR);
oglTextureParameteri(me->mObjectID, GL_TEXTURE_WRAP_S, wrap);
oglTextureParameteri(me->mObjectID, GL_TEXTURE_WRAP_T, wrap);
if( aniso>1.0001f )
oglTextureParameterf(me->mObjectID, 0x84FE, aniso); // GL_TEXTURE_MAX_ANISOTROPY_EXT
break;
}
case piFILTER_NONE_MIPMAP:
{
const int numMipmaps = ilog2i(info->mXres );
oglTextureStorage2D(me->mObjectID, numMipmaps, moInternal, info->mXres, info->mYres);
if (buffer) oglTextureSubImage2D(me->mObjectID, 0, 0, 0, info->mXres, info->mYres, mode, mode3, buffer);
oglGenerateTextureMipmap(me->mObjectID);
oglTextureParameteri(me->mObjectID, GL_TEXTURE_BASE_LEVEL, 0);
oglTextureParameteri(me->mObjectID, GL_TEXTURE_MAX_LEVEL, numMipmaps);
oglTextureParameteri(me->mObjectID, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
oglTextureParameteri(me->mObjectID, GL_TEXTURE_MIN_FILTER, GL_NEAREST_MIPMAP_LINEAR );
oglTextureParameteri(me->mObjectID, GL_TEXTURE_WRAP_S, wrap);
oglTextureParameteri(me->mObjectID, GL_TEXTURE_WRAP_T, wrap);
if( aniso>1.0001f )
oglTextureParameterf(me->mObjectID, 0x84FE, aniso); // GL_TEXTURE_MAX_ANISOTROPY_EXT
break;
}
}
}
}
else if( info->mType==piTEXTURE_3D )
{
oglCreateTextures(GL_TEXTURE_3D, 1, &me->mObjectID);
oglTextureStorage3D(me->mObjectID, 1, moInternal, info->mXres, info->mYres, info->mZres);
if (buffer) oglTextureSubImage3D(me->mObjectID, 0, 0, 0, 0, info->mXres, info->mYres, info->mZres, mode, mode3, buffer);
oglTextureParameteri(me->mObjectID, GL_TEXTURE_BASE_LEVEL, 0);
oglTextureParameteri(me->mObjectID, GL_TEXTURE_MAX_LEVEL, 0);
oglTextureParameteri(me->mObjectID, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
oglTextureParameteri(me->mObjectID, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
oglTextureParameteri(me->mObjectID, GL_TEXTURE_WRAP_R, wrap);
oglTextureParameteri(me->mObjectID, GL_TEXTURE_WRAP_S, wrap);
oglTextureParameteri(me->mObjectID, GL_TEXTURE_WRAP_T, wrap);
}
else if( info->mType==piTEXTURE_CUBE )
{
if (rfilter == piFILTER_MIPMAP)
{
const int numMipmaps = ilog2i(info->mXres);
oglCreateTextures(GL_TEXTURE_CUBE_MAP_ARRAY, 1, &me->mObjectID);
oglTextureStorage3D(me->mObjectID, numMipmaps, moInternal, info->mXres, info->mYres, 6);
if (buffer)
{
oglTextureSubImage3D(me->mObjectID, 0, 0, 0, 0, info->mXres, info->mYres, 6, mode, mode3, buffer);
oglGenerateTextureMipmap(me->mObjectID);
}
oglTextureParameteri(me->mObjectID, GL_TEXTURE_MAX_LEVEL, numMipmaps);
oglTextureParameteri(me->mObjectID, GL_TEXTURE_MIN_FILTER, GL_LINEAR_MIPMAP_LINEAR);
}
else
{
oglCreateTextures(GL_TEXTURE_CUBE_MAP_ARRAY, 1, &me->mObjectID);
oglTextureStorage3D(me->mObjectID, 1, moInternal, info->mXres, info->mYres, 6);
if (buffer)
oglTextureSubImage3D(me->mObjectID, 0, 0, 0, 0, info->mXres, info->mYres, 6, mode, mode3, buffer);
oglTextureParameteri(me->mObjectID, GL_TEXTURE_MAX_LEVEL, 0);
oglTextureParameteri(me->mObjectID, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
}
oglTextureParameteri(me->mObjectID, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
oglTextureParameteri(me->mObjectID, GL_TEXTURE_BASE_LEVEL, 0);
oglTextureParameteri(me->mObjectID, GL_TEXTURE_WRAP_R, GL_CLAMP_TO_EDGE);
oglTextureParameteri(me->mObjectID, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
oglTextureParameteri(me->mObjectID, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
oglTextureParameteri(me->mObjectID, GL_TEXTURE_CUBE_MAP_SEAMLESS, GL_TRUE);
oglTextureParameterf(me->mObjectID, GL_TEXTURE_MIN_LOD, -1000.f);
oglTextureParameterf(me->mObjectID, GL_TEXTURE_MAX_LOD, 1000.f);
oglTextureParameterf(me->mObjectID, GL_TEXTURE_LOD_BIAS, 0.0f);
oglTextureParameteri(me->mObjectID, GL_TEXTURE_COMPARE_MODE, GL_NONE);
oglTextureParameteri(me->mObjectID, GL_TEXTURE_COMPARE_FUNC, GL_LEQUAL);
oglTextureParameterf(me->mObjectID, 0x84FE, aniso);
}
else if( info->mType==piTEXTURE_2D_ARRAY )
{
oglCreateTextures(GL_TEXTURE_2D_ARRAY, 1, &me->mObjectID);
oglTextureStorage3D(me->mObjectID, 1, moInternal, info->mXres, info->mYres, info->mZres);
//if (buffer) oglTextureSubImage3D(me->mObjectID, 0, 0, 0, 0, info->mXres, info->mYres, info->mZres, mode, mode3, buffer);
if( rfilter==piFILTER_PCF )
{
oglTextureParameteri(me->mObjectID, GL_TEXTURE_COMPARE_MODE, GL_COMPARE_REF_TO_TEXTURE);
oglTextureParameteri(me->mObjectID, GL_TEXTURE_COMPARE_FUNC, GL_LEQUAL);
oglTextureParameteri(me->mObjectID, GL_TEXTURE_BASE_LEVEL, 0);
oglTextureParameteri(me->mObjectID, GL_TEXTURE_MAX_LEVEL, 0);
oglTextureParameteri(me->mObjectID, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
oglTextureParameteri(me->mObjectID, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
}
else
{
oglTextureParameteri(me->mObjectID, GL_TEXTURE_BASE_LEVEL, 0);
oglTextureParameteri(me->mObjectID, GL_TEXTURE_MAX_LEVEL, 0);
oglTextureParameteri(me->mObjectID, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
oglTextureParameteri(me->mObjectID, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
}
oglTextureParameteri(me->mObjectID, GL_TEXTURE_WRAP_R, wrap);
oglTextureParameteri(me->mObjectID, GL_TEXTURE_WRAP_S, wrap);
oglTextureParameteri(me->mObjectID, GL_TEXTURE_WRAP_T, wrap);
}
me->mHandle = oglGetTextureHandle( me->mObjectID );
return me;
}
piTexture piRendererGL4X::CreateTextureFromID(unsigned int id, piTextureFilter filter )
{
piITexture *me = (piITexture*)malloc(sizeof(piITexture));
if (!me)
return nullptr;
me->mObjectID = id;
//me->mInfo = *info;
me->mFilter = filter;
//me->mWrap = rwrap;
return me;
}
piTexture piRendererGL4X::CreateTexture( const wchar_t *key, const piTextureInfo *info, piTextureFilter filter, piTextureWrap wrap1, float aniso, void *buffer )
{
#ifdef USETEXTURECACHE
// look for an existing copy (linear)
TextureSlot *slots = (TextureSlot*)mMngTexSlots;
if( key )
{
for( int i=0; i<mMngTexNumCurrent; i++ )
{
TextureSlot *ts = slots + i;
piITexture *tex = (piITexture*)ts->mTexture;
if( tex->mInfo.mType == info->mType && tex->mFilter == filter &&
tex->mInfo.mFormat == info->mFormat && tex->mInfo.mCompressed == info->mCompressed &&
tex->mInfo.mXres == info->mXres && tex->mInfo.mYres == info->mYres && tex->mInfo.mZres == info->mZres &&
piwstrequ(ts->mKey,key) )
{
ts->mReference++;
return (piTexture)tex;
}
}
}
// mp free slots? make room
if( mMngTexNumCurrent>=mMngTexMax )
{
const int newmax = 4*mMngTexMax/3;
mMngTexSlots = (TextureSlot*)realloc( mMngTexSlots, newmax*sizeof(TextureSlot) );
if (!mMngTexSlots) return nullptr;
slots = (TextureSlot*)mMngTexSlots;
mMngTexMax = newmax;
}
// ok, create the texture
piITexture *tex = piITexture_Create( info, filter, wrap1, aniso, buffer, mExt );
if (!tex) return nullptr;
TextureSlot *ts = slots + mMngTexNumCurrent;
ts->mTexture = tex;
int err = 0;
ts->mKey = piwstrdup( key, &err );
if (err) return nullptr;
ts->mReference = 1;
#else
piITexture *tex = piITexture_Create( type, format, compressed, filter, wrap1, wrap2, buffer, xres, yres, zres, ext );
#endif
mMngTexMemCurrent += piTexture_GetMem( tex );
mMngTexNumCurrent += 1;
if( mMngTexNumCurrent>mMngTexNumPeak ) mMngTexNumPeak = mMngTexNumCurrent;
if( mMngTexMemCurrent>mMngTexMemPeak ) mMngTexMemPeak = mMngTexMemCurrent;
return tex;
}
void piRendererGL4X::ComputeMipmaps( piTexture vme )
{
piITexture *me = (piITexture*)vme;
if( me->mFilter!=piFILTER_MIPMAP ) return;
oglGenerateTextureMipmap(me->mObjectID);
}
void piRendererGL4X::DestroyTexture( piTexture me )
{
#ifdef USETEXTURECACHE
TextureSlot *slots = (TextureSlot*)mMngTexSlots;
// find (linear...)
int id = -1;
for( int i=0; i<mMngTexNumCurrent; i++ )
{
if( slots[i].mTexture == (piITexture*)me )
{
id = i;
break;
}
}
if( id==-1 )
{
return;
}
slots[id].mReference--;
if( slots[id].mReference==0 )
{
mMngTexMemCurrent -= piTexture_GetMem( slots[id].mTexture );
//piITexture_Destroy( slots[id].mTexture, ext );
glDeleteTextures( 1, &slots[id].mTexture->mObjectID );
free( me );
free( slots[id].mKey );
// shrink list
slots[id] = slots[mMngTexNumCurrent-1];
mMngTexNumCurrent--;
}
else if( slots[id].mReference<0 )
{
// megaerror
int i = 0;
}
else
{
int i = 0;
}
#else
mMngTexMemCurrent -= piITexture_GetMem( (piITexture*)me );
//piITexture_Destroy( (piITexture*)me, ext );
glDeleteTextures( 1, &me->mObjectID );
free( me );
mMngTexNumCurrent--;
#endif
}
void piRendererGL4X::AttachTextures( int num,
piTexture vt0, piTexture vt1, piTexture vt2, piTexture vt3, piTexture vt4, piTexture vt5, piTexture vt6, piTexture vt7,
piTexture vt8, piTexture vt9, piTexture vt10, piTexture vt11, piTexture vt12, piTexture vt13, piTexture vt14, piTexture vt15 )
{
piITexture *t[16] = { (piITexture*)vt0, (piITexture*)vt1, (piITexture*)vt2, (piITexture*)vt3, (piITexture*)vt4, (piITexture*)vt5, (piITexture*)vt6, (piITexture*)vt7,
(piITexture*)vt8, (piITexture*)vt9, (piITexture*)vt10, (piITexture*)vt11, (piITexture*)vt12, (piITexture*)vt13, (piITexture*)vt14, (piITexture*)vt15 };
GLuint texIDs[16];
for (int i = 0; i<num; i++)
texIDs[i] = (t[i]) ? t[i]->mObjectID : 0;
oglBindTextures( 0, num, texIDs );
}
void piRendererGL4X::DettachTextures( void )
{
#if 0
GLuint texIDs[6] = { 0, 0, 0, 0, 0, 0 };
oglBindTextures( 0, 6, texIDs );
#endif
}
void piRendererGL4X::AttachImage(int unit, piTexture texture, int level, bool layered, int layer, piTextureFormat format)
{
int mode, moInternal, mode3, bpp;
if (!format2gl(format, &bpp, &mode, &moInternal, &mode3, 0))
return;
oglBindImageTexture(unit, ((piITexture*)texture)->mObjectID, level, layered, layer, GL_READ_WRITE, moInternal);
}
void piRendererGL4X::ClearTexture( piTexture vme, int level, const void *data )
{
piITexture *me = (piITexture*)vme;
int mode, mode2, mode3, bpp;
if( !format2gl( me->mInfo.mFormat, &bpp, &mode, &mode2, &mode3, me->mInfo.mCompressed ) )
return;
oglActiveTexture( unidades[0] );
if( me->mInfo.mType==piTEXTURE_2D )
{
oglClearTexImage( me->mObjectID, level, mode, mode3, data );
}
else if( me->mInfo.mType==piTEXTURE_2D_ARRAY )
{
oglClearTexSubImage( me->mObjectID, level, 0, 0, 0, me->mInfo.mXres, me->mInfo.mYres, me->mInfo.mZres, mode, mode3, data );
}
}
void piRendererGL4X::UpdateTexture( piTexture vme, int x0, int y0, int z0, int xres, int yres, int zres, const void *buffer )
{
piITexture *me = (piITexture*)vme;
int fFormat, fInternal, fType, bpp;
if( !format2gl( me->mInfo.mFormat, &bpp, &fFormat, &fInternal, &fType, me->mInfo.mCompressed ) )
return;
if( me->mInfo.mType==piTEXTURE_2D )
{
oglTextureSubImage2D( me->mObjectID, 0, x0, y0, xres, yres, fFormat, fType, buffer);
if (me->mFilter == piFILTER_MIPMAP)
oglGenerateTextureMipmap(me->mObjectID);
}
else if( me->mInfo.mType==piTEXTURE_2D_ARRAY )
{
oglTextureSubImage3D( me->mObjectID, 0, x0, y0, z0, xres, yres, zres, fFormat, fType, buffer);
}
}
void piRendererGL4X::MakeResident( piTexture vme )
{
piITexture *me = (piITexture*)vme;
if( me->mIsResident ) return;
oglMakeTextureHandleResident( me->mHandle );
me->mIsResident = true;
}
void piRendererGL4X::MakeNonResident( piTexture vme )
{
piITexture *me = (piITexture*)vme;
if( !me->mIsResident ) return;
oglMakeTextureHandleNonResident( me->mHandle );
me->mIsResident = false;
}
uint64 piRendererGL4X::GetTextureHandle( piTexture vme )
{
piITexture *me = (piITexture*)vme;
return me->mHandle;
}
//==================================================
piSampler piRendererGL4X::CreateSampler(piTextureFilter filter, piTextureWrap wrap, float maxAnisotrop)
{
piISampler *me = (piISampler*)malloc( sizeof(piISampler) );
if( !me )
return nullptr;
oglGenSamplers( 1, &me->mObjectID );
//oglCreateSamplers( 1, &me->mObjectID );
int glwrap = wrap2gl[ wrap ];
if (filter == piFILTER_NONE)
{
oglSamplerParameteri(me->mObjectID, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
oglSamplerParameteri(me->mObjectID, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
oglSamplerParameteri(me->mObjectID, GL_TEXTURE_COMPARE_MODE, GL_NONE);
oglSamplerParameteri(me->mObjectID, GL_TEXTURE_COMPARE_FUNC, GL_LEQUAL);
oglSamplerParameterf(me->mObjectID, GL_TEXTURE_MIN_LOD, -1000.f);
oglSamplerParameterf(me->mObjectID, GL_TEXTURE_MAX_LOD, 1000.f);
oglSamplerParameterf(me->mObjectID, GL_TEXTURE_LOD_BIAS, 0.0f);
oglSamplerParameterf(me->mObjectID, 0x84FE, maxAnisotrop);
}
else if (filter == piFILTER_LINEAR)
{
oglSamplerParameteri(me->mObjectID, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
oglSamplerParameteri(me->mObjectID, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
oglSamplerParameteri(me->mObjectID, GL_TEXTURE_COMPARE_MODE, GL_NONE);
oglTextureParameteri(me->mObjectID, GL_TEXTURE_COMPARE_FUNC, GL_LEQUAL);
oglSamplerParameterf(me->mObjectID, GL_TEXTURE_MIN_LOD, -1000.f);
oglSamplerParameterf(me->mObjectID, GL_TEXTURE_MAX_LOD, 1000.f);
oglSamplerParameterf(me->mObjectID, GL_TEXTURE_LOD_BIAS, 0.0f);
oglSamplerParameterf(me->mObjectID, 0x84FE, maxAnisotrop);
}
else if (filter == piFILTER_MIPMAP)
{
oglSamplerParameteri(me->mObjectID, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
oglSamplerParameteri(me->mObjectID, GL_TEXTURE_MIN_FILTER, GL_LINEAR_MIPMAP_LINEAR);
oglSamplerParameteri(me->mObjectID, GL_TEXTURE_COMPARE_MODE, GL_NONE);
oglSamplerParameteri(me->mObjectID, GL_TEXTURE_COMPARE_FUNC, GL_LEQUAL);
oglSamplerParameterf(me->mObjectID, GL_TEXTURE_MIN_LOD, -1000.f);
oglSamplerParameterf(me->mObjectID, GL_TEXTURE_MAX_LOD, 1000.f);
oglSamplerParameterf(me->mObjectID, GL_TEXTURE_LOD_BIAS, 0.0f);
oglSamplerParameterf(me->mObjectID, 0x84FE, maxAnisotrop);
}
else // if (filter == piFILTER_PCF)
{
oglSamplerParameteri(me->mObjectID, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
oglSamplerParameteri(me->mObjectID, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
oglSamplerParameteri(me->mObjectID, GL_TEXTURE_COMPARE_MODE, GL_COMPARE_REF_TO_TEXTURE);
oglSamplerParameteri(me->mObjectID, GL_TEXTURE_COMPARE_FUNC, GL_LEQUAL);
oglSamplerParameterf(me->mObjectID, GL_TEXTURE_MIN_LOD, -1000.f);
oglSamplerParameterf(me->mObjectID, GL_TEXTURE_MAX_LOD, 1000.f);
oglSamplerParameterf(me->mObjectID, GL_TEXTURE_LOD_BIAS, 0.0f);
oglSamplerParameterf(me->mObjectID, 0x84FE, maxAnisotrop);
}
oglSamplerParameteri( me->mObjectID, GL_TEXTURE_WRAP_R, glwrap );
oglSamplerParameteri( me->mObjectID, GL_TEXTURE_WRAP_S, glwrap );
oglSamplerParameteri( me->mObjectID, GL_TEXTURE_WRAP_T, glwrap );
return me;
}
void piRendererGL4X::DestroySampler( piSampler obj )
{
piISampler *me = (piISampler*)obj;
oglDeleteSamplers( 1, &me->mObjectID );
}
void piRendererGL4X::AttachSamplers(int num, piSampler vt0, piSampler vt1, piSampler vt2, piSampler vt3, piSampler vt4, piSampler vt5, piSampler vt6, piSampler vt7)
{
piISampler *t[8] = { (piISampler*)vt0, (piISampler*)vt1, (piISampler*)vt2, (piISampler*)vt3, (piISampler*)vt4, (piISampler*)vt5, (piISampler*)vt6, (piISampler*)vt7 };
GLuint texIDs[8];
for( int i=0; i<num; i++ )
{
texIDs[i] = ( t[i] ) ? t[i]->mObjectID : 0;
}
oglBindSamplers( 0, num, texIDs );
}
void piRendererGL4X::DettachSamplers( void )
{
GLuint texIDs[8] = { 0, 0, 0, 0, 0, 0, 0, 0 };
oglBindSamplers( 0, 8, texIDs );
}
//===========================================================================================================================================
static const char *versionStr = "#version 440 core\n";
static bool createOptionsString(char *buffer, const int bufferLength, const piShaderOptions *options )
{
const int num = options->mNum;
if (num>64) return false;
int ptr = 0;
for (int i = 0; i<num; i++)
{
int offset = pisprintf(buffer + ptr, bufferLength - ptr, "#define %s %d\n", options->mOption[i].mName, options->mOption[i].mValue);
ptr += offset;
}
buffer[ptr] = 0;
return true;
}
piShader piRendererGL4X::CreateShader( const piShaderOptions *options, const char *vs, const char *cs, const char *es, const char *gs, const char *fs, char *error)
{
piIShader *me = (piIShader*)malloc( sizeof(piIShader) );
if( !me )
return nullptr;
//glEnable( GL_DEPTH_TEST );
const char *vtext = vs;
const char *ctext = cs;
const char *etext = es;
const char *gtext = gs;
const char *ftext = fs;
me->mProgID = oglCreateProgram();
const int mVertShaderID = vs?oglCreateShader( GL_VERTEX_SHADER ):-1;
const int mCtrlShaderID = cs?oglCreateShader( GL_TESS_CONTROL_SHADER ):-1;
const int mEvalShaderID = es?oglCreateShader( GL_TESS_EVALUATION_SHADER ):-1;
const int mGeomShaderID = gs?oglCreateShader( GL_GEOMETRY_SHADER ):-1;
const int mFragShaderID = fs?oglCreateShader( GL_FRAGMENT_SHADER ):-1;
char optionsStr[80*64] = { 0 };
if (options != nullptr)
{
if (!createOptionsString(optionsStr, 80 * 64, options)) {
free(me);
return nullptr;
}
}
const GLchar *vstrings[3] = { versionStr, optionsStr, vtext };
const GLchar *cstrings[3] = { versionStr, optionsStr, ctext };
const GLchar *estrings[3] = { versionStr, optionsStr, etext };
const GLchar *gstrings[3] = { versionStr, optionsStr, gtext };
const GLchar *fstrings[3] = { versionStr, optionsStr, ftext };
if( vs ) oglShaderSource(mVertShaderID, 3, vstrings, 0);
if( cs ) oglShaderSource(mCtrlShaderID, 3, cstrings, 0);
if( es ) oglShaderSource(mEvalShaderID, 3, estrings, 0);
if( gs ) oglShaderSource(mGeomShaderID, 3, gstrings, 0);
if( fs ) oglShaderSource(mFragShaderID, 3, fstrings, 0);
int result = 0;
//--------
if( vs )
{
oglCompileShader( mVertShaderID );
oglGetShaderiv( mVertShaderID, GL_COMPILE_STATUS, &result );
if( !result )
{
if (error) {
error[0] = 'V'; error[1] = 'S'; error[2] = ':';
oglGetShaderInfoLog(mVertShaderID, 1024, NULL, (char *)(error + 3));
}
free(me);
return nullptr;
}
}
//--------
if( cs )
{
oglCompileShader( mCtrlShaderID );
oglGetShaderiv( mCtrlShaderID, GL_COMPILE_STATUS, &result );
if( !result )
{
if( error ) { error[0]='C'; error[1]='S'; error[2]=':'; oglGetShaderInfoLog( mCtrlShaderID, 1024, NULL, (char *)(error+3) ); }
free(me);
return nullptr;
}
}
//--------
if( es )
{
oglCompileShader( mEvalShaderID );
oglGetShaderiv( mEvalShaderID, GL_COMPILE_STATUS, &result );
if( !result )
{
if( error ) { error[0]='E'; error[1]='S'; error[2]=':'; oglGetShaderInfoLog( mEvalShaderID, 1024, NULL, (char *)(error+3) ); }
return nullptr;
}
}
//--------
if( gs )
{
oglCompileShader( mGeomShaderID );
oglGetShaderiv( mGeomShaderID, GL_COMPILE_STATUS, &result );
if( !result )
{
if( error ) { error[0]='G'; error[1]='S'; error[2]=':'; oglGetShaderInfoLog( mGeomShaderID, 1024, NULL, (char *)(error+3) ); }
return nullptr;
}
}
//--------
if( fs )
{
oglCompileShader( mFragShaderID );
oglGetShaderiv( mFragShaderID, GL_COMPILE_STATUS, &result );
if( !result )
{
if( error ) { error[0]='F'; error[1]='S'; error[2]=':'; oglGetShaderInfoLog( mFragShaderID, 1024, NULL, (char *)(error+3) ); }
return nullptr;
}
}
//--------
if( vs ) oglAttachShader( me->mProgID, mVertShaderID );
if( cs ) oglAttachShader( me->mProgID, mCtrlShaderID );
if( es ) oglAttachShader( me->mProgID, mEvalShaderID );
if( gs ) oglAttachShader( me->mProgID, mGeomShaderID );
if( fs ) oglAttachShader( me->mProgID, mFragShaderID );
//--------
oglLinkProgram( me->mProgID );
oglGetProgramiv( me->mProgID, GL_LINK_STATUS, &result );
if( !result )
{
if( error ) { error[0]='L'; error[1]='I'; error[2]=':'; oglGetProgramInfoLog( me->mProgID, 1024, NULL, (char *)(error+3) ); }
return nullptr;
}
if( vs ) oglDeleteShader( mVertShaderID );
if( cs ) oglDeleteShader( mCtrlShaderID );
if( es ) oglDeleteShader( mEvalShaderID );
if( gs ) oglDeleteShader( mGeomShaderID );
if( fs ) oglDeleteShader( mFragShaderID );
return (piShader)me;
}
piShader piRendererGL4X::CreateCompute(const piShaderOptions *options, const char *cs, char *error)
{
if (!cs)
return nullptr;
piIShader *me = (piIShader*)malloc(sizeof(piIShader));
if (!me)
return nullptr;
const char *ctext = cs;
char optionsStr[80 * 64] = { 0 };
if (options != nullptr) createOptionsString(optionsStr, 80*64, options);
me->mProgID = oglCreateProgram();
const int mShaderID = oglCreateShader(GL_COMPUTE_SHADER);
const GLchar *vstrings[3] = { versionStr, optionsStr, ctext };
oglShaderSource(mShaderID, 3, vstrings, 0);
int result = 0;
//--------
oglCompileShader(mShaderID);
oglGetShaderiv(mShaderID, GL_COMPILE_STATUS, &result);
if (!result)
{
if (error) {
error[0] = 'C'; error[1] = 'S'; error[2] = ':';
oglGetShaderInfoLog(mShaderID, 1024, NULL, (char *)(error + 3));
}
free(me);
return(0);
}
//--------
oglAttachShader(me->mProgID, mShaderID);
//--------
oglLinkProgram(me->mProgID);
oglGetProgramiv(me->mProgID, GL_LINK_STATUS, &result);
if (!result)
{
if (error) { error[0] = 'L'; error[1] = 'I'; error[2] = ':'; oglGetProgramInfoLog(me->mProgID, 1024, NULL, (char *)(error + 3)); }
free(me);
return(0);
}
oglDeleteShader(mShaderID);
return (piShader)me;
}
void piRendererGL4X::DestroyShader( piShader vme )
{
piIShader *me = (piIShader *)vme;
oglDeleteProgram( me->mProgID );
}
void piRendererGL4X::AttachShader( piShader vme )
{
piIShader *me = (piIShader *)vme;
//if (me->mProgID==this->mB
oglUseProgram( me->mProgID );
//glEnable( GL_VERTEX_PROGRAM_POINT_SIZE );
}
void piRendererGL4X::DettachShader( void )
{
//glDisable(GL_VERTEX_PROGRAM_POINT_SIZE);
oglUseProgram( 0 );
}
void piRendererGL4X::AttachShaderConstants(piBuffer obj, int unit)
{
piIBuffer *me = (piIBuffer *)obj;
oglBindBufferRange(GL_UNIFORM_BUFFER, unit, me->mObjectID, 0, me->mSize);
}
void piRendererGL4X::AttachShaderBuffer(piBuffer obj, int unit)
{
piIBuffer *me = (piIBuffer *)obj;
oglBindBufferBase(GL_SHADER_STORAGE_BUFFER, unit, me->mObjectID );
}
void piRendererGL4X::DettachShaderBuffer(int unit)
{
oglBindBufferBase(GL_SHADER_STORAGE_BUFFER, unit, 0);
}
void piRendererGL4X::AttachAtomicsBuffer(piBuffer obj, int unit)
{
piIBuffer *me = (piIBuffer *)obj;
oglBindBufferBase(GL_ATOMIC_COUNTER_BUFFER, unit, me->mObjectID);
}
void piRendererGL4X::DettachAtomicsBuffer(int unit)
{
oglBindBufferBase(GL_ATOMIC_COUNTER_BUFFER, unit, 0);
}
void piRendererGL4X::SetShaderConstant4F(const unsigned int pos, const float *value, int num)
{
oglUniform4fv(pos,num,value);
}
void piRendererGL4X::SetShaderConstant3F(const unsigned int pos, const float *value, int num)
{
oglUniform3fv(pos,num,value);
}
void piRendererGL4X::SetShaderConstant2F(const unsigned int pos, const float *value, int num)
{
oglUniform2fv(pos,num,value);
}
void piRendererGL4X::SetShaderConstant1F(const unsigned int pos, const float *value, int num)
{
oglUniform1fv(pos,num,value);
}
void piRendererGL4X::SetShaderConstant1I(const unsigned int pos, const int *value, int num)
{
oglUniform1iv(pos,num,value);
}
void piRendererGL4X::SetShaderConstant1UI(const unsigned int pos, const unsigned int *value, int num)
{
oglUniform1uiv(pos,num,value);
}
void piRendererGL4X::SetShaderConstantMat4F(const unsigned int pos, const float *value, int num, bool transpose)
{
oglUniformMatrix4fv(pos,num,transpose,value);
//oglProgramUniformMatrix4fv( ((piIShader *)mBindedShader)->mProgID, pos, num, transpose, value ); // can do without binding!
}
void piRendererGL4X::SetShaderConstantSampler(const unsigned int pos, int unit)
{
oglUniform1i(pos,unit);
}
static const int r2gl_blendMode[] = {
GL_ONE,
GL_SRC_ALPHA,
GL_SRC_COLOR,
GL_ONE_MINUS_SRC_COLOR,
GL_ONE_MINUS_SRC_ALPHA,
GL_DST_ALPHA,
GL_ONE_MINUS_DST_ALPHA,
GL_DST_COLOR,
GL_ONE_MINUS_DST_COLOR,
GL_SRC_ALPHA_SATURATE,
GL_ZERO
};
static const int r2gl_blendEqua[] = {
GL_FUNC_ADD,
GL_FUNC_SUBTRACT,
GL_FUNC_REVERSE_SUBTRACT,
GL_MIN,
GL_MAX
};
void piRendererGL4X::SetBlending( int buf, piBlendEquation equRGB, piBlendOperations srcRGB, piBlendOperations dstRGB,
piBlendEquation equALP, piBlendOperations srcALP, piBlendOperations dstALP )
{
oglBlendEquationSeparatei(buf, r2gl_blendEqua[equRGB], r2gl_blendEqua[equALP]);
oglBlendFuncSeparatei( buf, r2gl_blendMode[srcRGB], r2gl_blendMode[dstRGB],
r2gl_blendMode[srcALP], r2gl_blendMode[dstALP]);
}
void piRendererGL4X::SetWriteMask( bool c0, bool c1, bool c2, bool c3, bool z )
{
glDepthMask( z?GL_TRUE:GL_FALSE );
oglColorMaski( 0, c0, c0, c0, c0 );
oglColorMaski( 1, c0, c0, c0, c0 );
oglColorMaski( 2, c0, c0, c0, c0 );
oglColorMaski( 3, c0, c0, c0, c0 );
}
void piRendererGL4X::SetState( piState state, bool value )
{
if( state==piSTATE_WIREFRAME )
{
if( value ) glPolygonMode( GL_FRONT_AND_BACK, GL_LINE );
else glPolygonMode( GL_FRONT_AND_BACK, GL_FILL );
}
else if( state==piSTATE_FRONT_FACE )
{
if( !value ) glFrontFace( GL_CW );
else glFrontFace( GL_CCW );
}
else if (state == piSTATE_DEPTH_TEST)
{
if (value) glEnable(GL_DEPTH_TEST);
else glDisable(GL_DEPTH_TEST);
}
else if( state== piSTATE_CULL_FACE )
{
if( value ) glEnable(GL_CULL_FACE);
else glDisable(GL_CULL_FACE);
}
else if( state == piSTATE_ALPHA_TO_COVERAGE )
{
if (value) { glEnable(GL_SAMPLE_ALPHA_TO_COVERAGE); glEnable(GL_SAMPLE_ALPHA_TO_ONE); glDisable(GL_SAMPLE_COVERAGE ); }
else { glDisable(GL_SAMPLE_ALPHA_TO_COVERAGE); glDisable(GL_SAMPLE_ALPHA_TO_ONE); glDisable(GL_SAMPLE_COVERAGE); }
}
else if( state == piSTATE_DEPTH_CLAMP )
{
if( value ) glEnable( GL_DEPTH_CLAMP);
else glDisable( GL_DEPTH_CLAMP);
}
else if( state == piSTATE_VIEWPORT_FLIPY )
{
if( value ) oglClipControl(GL_UPPER_LEFT, GL_ZERO_TO_ONE);
else oglClipControl(GL_LOWER_LEFT, GL_NEGATIVE_ONE_TO_ONE);
}
else if( state == piSTATE_BLEND )
{
if (value) glEnable(GL_BLEND);
else glDisable(GL_BLEND);
}
}
void piRendererGL4X::Clear( const float *color0, const float *color1, const float *color2, const float *color3, const bool depth0 )
{
if( mBindedTarget == NULL )
{
int mode = 0;
if( color0 ) { mode |= GL_COLOR_BUFFER_BIT; glClearColor( color0[0], color0[1], color0[2], color0[3] ); }
if( depth0 ) { mode |= GL_DEPTH_BUFFER_BIT; glClearDepth( 1.0f ); }
glClear( mode );
}
else
{
float z = 1.0f;
if( color0 ) oglClearBufferfv( GL_COLOR, 0, color0 );
if( color1 ) oglClearBufferfv( GL_COLOR, 1, color1 );
if( color2 ) oglClearBufferfv( GL_COLOR, 2, color2 );
if( color3 ) oglClearBufferfv( GL_COLOR, 3, color3 );
if( depth0 ) oglClearBufferfv( GL_DEPTH, 0, &z );
}
// glClearBufferfi( GL_DEPTH_STENCIL, 0, z, s );
}
//-----------------------
piBuffer piRendererGL4X::CreateBuffer(const void *data, unsigned int amount, piBufferType mode)
{
piIBuffer *me = (piIBuffer*)malloc(sizeof(piIBuffer));
if (!me)
return nullptr;
oglCreateBuffers(1, &me->mObjectID);
if (mode == piBufferType_Dynamic)
{
oglNamedBufferStorage(me->mObjectID, amount, data, GL_DYNAMIC_STORAGE_BIT);
//oglNamedBufferStorage(me->mObjectID, amount, data, GL_MAP_WRITE_BIT | GL_MAP_PERSISTENT_BIT | GL_MAP_COHERENT_BIT );
//me->mPtr = oglMapNamedBufferRange(me->mObjectID, 0, amount, GL_MAP_WRITE_BIT | GL_MAP_PERSISTENT_BIT | GL_MAP_COHERENT_BIT );
//if (me->mPtr == nullptr )
// return 0;
//me->mSync = oglFenceSync(GL_SYNC_GPU_COMMANDS_COMPLETE, 0);
}
else
{
oglNamedBufferStorage(me->mObjectID, amount, data, 0);
//me->mPtr = nullptr;
}
me->mSize = amount;
return (piBuffer)me;
}
//glGenBuffers(1, &me->mObjectID);
//glBindBuffer(GL_SHADER_STORAGE_BUFFER, me->mObjectID);
//glBufferData(GL_SHADER_STORAGE_BUFFER, amount, nullptr, GL_DYNAMIC_COPY);
void piRendererGL4X::DestroyBuffer(piBuffer vme)
{
piIBuffer *me = (piIBuffer*)vme;
oglDeleteBuffers(1, &me->mObjectID );
}
void piRendererGL4X::UpdateBuffer(piBuffer obj, const void *data, int offset, int len)
{
piIBuffer *me = (piIBuffer *)obj;
oglNamedBufferSubData(me->mObjectID, offset, len, data);
/*
while(1)
{
GLenum waitReturn = oglClientWaitSync(me->mSync, GL_SYNC_FLUSH_COMMANDS_BIT, 1);
if (waitReturn == GL_ALREADY_SIGNALED || waitReturn == GL_CONDITION_SATISFIED)
break;
}
memcpy(me->mPtr, data, len);
*/
//void *ptr = oglMapNamedBufferRange(me->mObjectID, 0, len, GL_MAP_WRITE_BIT | GL_MAP_COHERENT_BIT | GL_MAP_INVALIDATE_BUFFER_BIT);
//memcpy(ptr, data, len);
//oglUnmapNamedBuffer( me->mObjectID );
}
piVertexArray piRendererGL4X::CreateVertexArray( int numStreams,
piBuffer vb0, const piRArrayLayout *streamLayout0,
piBuffer vb1, const piRArrayLayout *streamLayout1,
piBuffer eb )
{
piIVertexArray *me = (piIVertexArray*)malloc(sizeof(piIVertexArray));
if( !me )
return nullptr;
oglCreateVertexArrays(1, &me->mObjectID);
if (!me->mObjectID)
return nullptr;
unsigned int aid = 0;
for( int j=0; j<numStreams; j++ )
{
unsigned int sid = j;
//me->mStreams[j] = (j == 0) *streamLayout0 : *streamLayout1;
const piRArrayLayout * st = (j == 0) ? streamLayout0 : streamLayout1;
piBuffer vb = (j==0 ) ? vb0 : vb1;
int offset = 0;
const int num = st->mNumElements;
for( int i=0; i<num; i++ )
{
oglEnableVertexArrayAttrib(me->mObjectID, aid);
oglVertexArrayAttribFormat(me->mObjectID, aid, st->mEntry[i].mNumComponents, glType[st->mEntry[i].mType], st->mEntry[i].mNormalize, offset);
oglVertexArrayAttribBinding(me->mObjectID, aid, sid);
offset += st->mEntry[i].mNumComponents*glSizeof[st->mEntry[i].mType];
aid++;
}
oglVertexArrayVertexBuffer(me->mObjectID, sid, ((piIBuffer*)vb)->mObjectID, 0, st->mStride);
//oglVertexArrayBindingDivisor(me->mObjectID, bid, (streamLayout->mDivisor>0) ? streamLayout->mDivisor : 1 );
}
if (eb != nullptr )
oglVertexArrayElementBuffer(me->mObjectID, ((piIBuffer*)eb)->mObjectID);
return (piVertexArray)me;
}
void piRendererGL4X::DestroyVertexArray(piVertexArray vme)
{
piIVertexArray *me = (piIVertexArray*)vme;
oglDeleteVertexArrays(1, &me->mObjectID);
}
void piRendererGL4X::AttachVertexArray(piVertexArray vme)
{
piIVertexArray *me = (piIVertexArray*)vme;
oglBindVertexArray(me->mObjectID);
}
void piRendererGL4X::DettachVertexArray( void )
{
oglBindVertexArray( 0 );
}
void piRendererGL4X::DrawPrimitiveIndexed(piPrimitiveType pt, int num, int numInstances, int baseVertex, int baseInstance)
{
GLenum glpt = GL_TRIANGLES;
if (pt == piPT_Triangle) glpt = GL_TRIANGLES;
else if (pt == piPT_Point) glpt = GL_POINTS;
else if (pt == piPT_TriangleStrip) glpt = GL_TRIANGLE_STRIP;
else if (pt == piPT_LineStrip) glpt = GL_LINE_STRIP;
else if (pt == piPT_TriPatch) { glpt = GL_PATCHES; oglPatchParameteri(GL_PATCH_VERTICES, 3); }
else if (pt == piPT_QuadPatch) { glpt = GL_PATCHES; oglPatchParameteri(GL_PATCH_VERTICES, 4); }
else if (pt == piPT_LinesAdj) glpt = GL_LINES_ADJACENCY;
else if (pt == piPT_LineStripAdj) glpt = GL_LINE_STRIP_ADJACENCY;
else if (pt == piPT_16Patch) { glpt = GL_PATCHES; oglPatchParameteri(GL_PATCH_VERTICES, 16); }
else if (pt == piPT_32Patch) { glpt = GL_PATCHES; oglPatchParameteri(GL_PATCH_VERTICES, 32); }
else if (pt == piPT_Lines) glpt = GL_LINES;
/*
unsigned int cmd[5] = { num, // num elements
1, // num instances
0, // first index
0, // base vertex
0 };// base instance
subdata( GL_DRAW_INDIRECT_BUFFER, cmd )
oglDrawElementsIndirect(glpt[pt], GL_UNSIGNED_INT, 0);
*/
oglDrawElementsInstancedBaseVertexBaseInstance( glpt, num, GL_UNSIGNED_INT,
NULL, // indices
numInstances, // prim count
baseVertex, // base vertex
baseInstance); // base instance
}
void piRendererGL4X::DrawPrimitiveNotIndexed(piPrimitiveType pt, int first, int num, int numInstanced)
{
GLenum glpt = GL_TRIANGLES;
if (pt == piPT_Triangle) glpt = GL_TRIANGLES;
else if (pt == piPT_Point) glpt = GL_POINTS;
else if (pt == piPT_TriangleStrip) glpt = GL_TRIANGLE_STRIP;
else if (pt == piPT_LineStrip) glpt = GL_LINE_STRIP;
else if (pt == piPT_TriPatch) { glpt = GL_PATCHES; oglPatchParameteri(GL_PATCH_VERTICES, 3); }
else if (pt == piPT_QuadPatch) { glpt = GL_PATCHES; oglPatchParameteri(GL_PATCH_VERTICES, 4); }
else if (pt == piPT_LinesAdj) glpt = GL_LINES_ADJACENCY;
else if (pt == piPT_LineStripAdj) glpt = GL_LINE_STRIP_ADJACENCY;
else if (pt == piPT_16Patch) { glpt = GL_PATCHES; oglPatchParameteri(GL_PATCH_VERTICES, 16); }
else if (pt == piPT_32Patch) { glpt = GL_PATCHES; oglPatchParameteri(GL_PATCH_VERTICES, 32); }
else if (pt == piPT_Lines) glpt = GL_LINES;
oglDrawArraysInstanced(glpt, first, num, numInstanced);
}
void piRendererGL4X::DrawPrimitiveNotIndexedMultiple(piPrimitiveType pt, const int *firsts, const int *counts, int num)
{
GLenum glpt = GL_TRIANGLES;
if (pt == piPT_Triangle) glpt = GL_TRIANGLES;
else if (pt == piPT_Point) glpt = GL_POINTS;
else if (pt == piPT_TriangleStrip) glpt = GL_TRIANGLE_STRIP;
else if (pt == piPT_LineStrip) glpt = GL_LINE_STRIP;
else if (pt == piPT_TriPatch) { glpt = GL_PATCHES; oglPatchParameteri(GL_PATCH_VERTICES, 3); }
else if (pt == piPT_QuadPatch) { glpt = GL_PATCHES; oglPatchParameteri(GL_PATCH_VERTICES, 4); }
else if (pt == piPT_LinesAdj) glpt = GL_LINES_ADJACENCY;
else if (pt == piPT_LineStripAdj) glpt = GL_LINE_STRIP_ADJACENCY;
else if (pt == piPT_16Patch) { glpt = GL_PATCHES; oglPatchParameteri(GL_PATCH_VERTICES, 16); }
else if (pt == piPT_32Patch) { glpt = GL_PATCHES; oglPatchParameteri(GL_PATCH_VERTICES, 32); }
else if (pt == piPT_Lines) glpt = GL_LINES;
oglMultiDrawArrays(glpt,firsts,counts,num);
}
void piRendererGL4X::DrawPrimitiveNotIndexedIndirect(piPrimitiveType pt, piBuffer cmds, int num)
{
piIBuffer *buf = (piIBuffer *)cmds;
oglBindBuffer(GL_DRAW_INDIRECT_BUFFER, buf->mObjectID);
GLenum glpt = GL_TRIANGLES;
if (pt == piPT_Triangle) glpt = GL_TRIANGLES;
else if (pt == piPT_Point) glpt = GL_POINTS;
else if (pt == piPT_TriangleStrip) glpt = GL_TRIANGLE_STRIP;
else if (pt == piPT_LineStrip) glpt = GL_LINE_STRIP;
else if (pt == piPT_TriPatch) { glpt = GL_PATCHES; oglPatchParameteri(GL_PATCH_VERTICES, 3); }
else if (pt == piPT_QuadPatch) { glpt = GL_PATCHES; oglPatchParameteri(GL_PATCH_VERTICES, 4); }
else if (pt == piPT_LinesAdj) glpt = GL_LINES_ADJACENCY;
else if (pt == piPT_LineStripAdj) glpt = GL_LINE_STRIP_ADJACENCY;
else if (pt == piPT_16Patch) { glpt = GL_PATCHES; oglPatchParameteri(GL_PATCH_VERTICES, 16); }
else if (pt == piPT_32Patch) { glpt = GL_PATCHES; oglPatchParameteri(GL_PATCH_VERTICES, 32); }
else if (pt == piPT_Lines) glpt = GL_LINES;
oglMultiDrawArraysIndirect(glpt, 0, num, sizeof(piDrawArraysIndirectCommand));
oglBindBuffer(GL_DRAW_INDIRECT_BUFFER, 0);
}
void piRendererGL4X::DrawPrimitiveIndirect(piPrimitiveType pt, piBuffer cmds, int num)
{
piIBuffer *buf = (piIBuffer *)cmds;
oglBindBuffer(GL_DRAW_INDIRECT_BUFFER, buf->mObjectID);
GLenum glpt = GL_TRIANGLES;
if (pt == piPT_Triangle) glpt = GL_TRIANGLES;
else if (pt == piPT_Point) glpt = GL_POINTS;
else if (pt == piPT_TriangleStrip) glpt = GL_TRIANGLE_STRIP;
else if (pt == piPT_LineStrip) glpt = GL_LINE_STRIP;
else if (pt == piPT_TriPatch) { glpt = GL_PATCHES; oglPatchParameteri(GL_PATCH_VERTICES, 3); }
else if (pt == piPT_QuadPatch) { glpt = GL_PATCHES; oglPatchParameteri(GL_PATCH_VERTICES, 4); }
else if (pt == piPT_LinesAdj) glpt = GL_LINES_ADJACENCY;
else if (pt == piPT_LineStripAdj) glpt = GL_LINE_STRIP_ADJACENCY;
else if (pt == piPT_16Patch) { glpt = GL_PATCHES; oglPatchParameteri(GL_PATCH_VERTICES, 16); }
else if (pt == piPT_32Patch) { glpt = GL_PATCHES; oglPatchParameteri(GL_PATCH_VERTICES, 32); }
else if (pt == piPT_Lines) glpt = GL_LINES;
oglMultiDrawElementsIndirect(glpt, GL_UNSIGNED_INT, 0, num, sizeof(piDrawElementsIndirectCommand));
oglBindBuffer(GL_DRAW_INDIRECT_BUFFER, 0);
}
void piRendererGL4X::DrawUnitQuad_XY( int numInstanced )
{
this->AttachVertexArray( mVA[0] );
oglDrawArraysInstanced(GL_TRIANGLE_STRIP, 0, 4, numInstanced);
this->DettachVertexArray();
}
void piRendererGL4X::DrawUnitCube_XYZ_NOR(int numInstanced)
{
this->AttachVertexArray(mVA[1]);
oglDrawArraysInstanced(GL_TRIANGLE_STRIP, 0, 4, numInstanced);
oglDrawArraysInstanced(GL_TRIANGLE_STRIP, 4, 4, numInstanced);
oglDrawArraysInstanced(GL_TRIANGLE_STRIP, 8, 4, numInstanced);
oglDrawArraysInstanced(GL_TRIANGLE_STRIP, 12, 4, numInstanced);
oglDrawArraysInstanced(GL_TRIANGLE_STRIP, 16, 4, numInstanced);
oglDrawArraysInstanced(GL_TRIANGLE_STRIP, 20, 4, numInstanced);
this->DettachVertexArray();
}
void piRendererGL4X::DrawUnitCube_XYZ(int numInstanced)
{
this->AttachVertexArray(mVA[2]);
oglDrawArraysInstanced(GL_TRIANGLE_STRIP, 0, 4, numInstanced);
oglDrawArraysInstanced(GL_TRIANGLE_STRIP, 4, 4, numInstanced);
oglDrawArraysInstanced(GL_TRIANGLE_STRIP, 8, 4, numInstanced);
oglDrawArraysInstanced(GL_TRIANGLE_STRIP, 12, 4, numInstanced);
oglDrawArraysInstanced(GL_TRIANGLE_STRIP, 16, 4, numInstanced);
oglDrawArraysInstanced(GL_TRIANGLE_STRIP, 20, 4, numInstanced);
this->DettachVertexArray();
}
void piRendererGL4X::ExecuteCompute(int tx, int ty, int tz, int gsx, int gsy, int gsz)
{
int ngx = tx / gsx; if( (ngx*gsx) < tx ) ngx++;
int ngy = ty / gsy; if( (ngy*gsy) < ty ) ngy++;
int ngz = tz / gsz; if( (ngz*gsz) < tz ) ngz++;
oglDispatchCompute( ngx, ngy, ngz );
}
void piRendererGL4X::SetLineWidth( float size )
{
glLineWidth( size );
}
void piRendererGL4X::SetPointSize( bool mode, float size )
{
if( mode )
{
glEnable( GL_PROGRAM_POINT_SIZE );
glPointSize( size );
}
else
glDisable( GL_PROGRAM_POINT_SIZE );
}
void piRendererGL4X::GetTextureRes( piTexture vme, int *res )
{
piITexture *me = (piITexture*)vme;
res[0] = me->mInfo.mXres;
res[1] = me->mInfo.mYres;
res[2] = me->mInfo.mZres;
}
void piRendererGL4X::GetTextureFormat( piTexture vme, piTextureFormat *format )
{
piITexture *me = (piITexture*)vme;
format[0] = me->mInfo.mFormat;
}
void piRendererGL4X::GetTextureInfo( piTexture vme, piTextureInfo *info )
{
piITexture *me = (piITexture*)vme;
info[0] = me->mInfo;
info->mDeleteMe = me->mObjectID;
}
void piRendererGL4X::GetTextureSampling(piTexture vme, piTextureFilter *rfilter, piTextureWrap *rwrap)
{
piITexture *me = (piITexture*)vme;
rfilter[0] = me->mFilter;
rwrap[0] = me->mWrap;
}
void piRendererGL4X::GetTextureContent( piTexture vme, void *data, const piTextureFormat fmt )
{
piITexture *me = (piITexture*)vme;
int mode, mode2, mode3, bpp;
//if( !format2gl( me->mInfo.mFormat, &bpp, &mode, &mode2, &mode3, me->mInfo.mCompressed ) )
if( !format2gl( fmt, &bpp, &mode, &mode2, &mode3, me->mInfo.mCompressed ) )
return;
oglGetTextureImage(me->mObjectID, 0, mode, mode3, me->mInfo.mXres*me->mInfo.mYres*me->mInfo.mZres * bpp, data);
}
void piRendererGL4X::GetTextureContent(piTexture vme, void *data, int x, int y, int z, int xres, int yres, int zres)
{
piITexture *me = (piITexture*)vme;
int exteriorFormat, internalFormat, ftype, bpp;
if (!format2gl(me->mInfo.mFormat, &bpp, &exteriorFormat, &internalFormat, &ftype, me->mInfo.mCompressed))
return;
oglGetTextureSubImage( me->mObjectID,
0,
x, y, z, xres, yres, zres,
exteriorFormat, ftype,
xres*yres*zres*bpp, data );
}
//------------
/*
void piRendererGL4X::SetAttribute1F( int pos, const float data )
{
oglVertexAttrib1f( pos, data );
}
void piRendererGL4X::SetAttribute2F( int pos, const float *data )
{
oglVertexAttrib2fv( pos, data );
}
void piRendererGL4X::SetAttribute3F( int pos, const float *data )
{
oglVertexAttrib3fv( pos, data );
}
void piRendererGL4X::SetAttribute4F( int pos, const float *data )
{
oglVertexAttrib4fv( pos, data );
}
*/
void piRendererGL4X::PolygonOffset( bool mode, bool wireframe, float a, float b )
{
if( mode )
{
glEnable( wireframe?GL_POLYGON_OFFSET_LINE:GL_POLYGON_OFFSET_FILL );
glPolygonOffset( a, b );
}
else
{
glDisable( wireframe?GL_POLYGON_OFFSET_LINE:GL_POLYGON_OFFSET_FILL );
}
}
void piRendererGL4X::RenderMemoryBarrier(piBarrierType type)
{
GLbitfield bf = 0;
if( type & piBARRIER_SHADER_STORAGE ) bf |= GL_SHADER_STORAGE_BARRIER_BIT;
if( type & piBARRIER_UNIFORM ) bf |= GL_UNIFORM_BARRIER_BIT;
if( type & piBARRIER_ATOMICS ) bf |= GL_ATOMIC_COUNTER_BARRIER_BIT;
if( type & piBARRIER_IMAGE ) bf |= GL_SHADER_IMAGE_ACCESS_BARRIER_BIT;
if (type & piBARRIER_COMMAND ) bf |= GL_COMMAND_BARRIER_BIT;
if (type & piBARRIER_TEXTURE ) bf |= GL_TEXTURE_UPDATE_BARRIER_BIT;
if( type == piBARRIER_ALL) bf = GL_ALL_BARRIER_BITS;
oglMemoryBarrier(bf);
}
}
| 35.628095 | 188 | 0.632552 | Livictor213 |
96093b609c018eb3ef7b6d80a160f60ad79f433f | 1,488 | cpp | C++ | LightOJ/LightOJ - 1298/Accepted.cpp | kzvd4729/Problem-Solving | 13b105e725a4c2f8db7fecc5d7a8f932b9fef4ab | [
"MIT"
] | 1 | 2022-02-11T16:55:36.000Z | 2022-02-11T16:55:36.000Z | LightOJ/LightOJ - 1298/Accepted.cpp | kzvd4729/Problem-Solving | 13b105e725a4c2f8db7fecc5d7a8f932b9fef4ab | [
"MIT"
] | null | null | null | LightOJ/LightOJ - 1298/Accepted.cpp | kzvd4729/Problem-Solving | 13b105e725a4c2f8db7fecc5d7a8f932b9fef4ab | [
"MIT"
] | null | null | null | /****************************************************************************************
* @author: kzvd4729 created: 2019-05-15 00:42:06
* solution_verdict: Accepted language: C++
* run_time (ms): 783 memory_used (MB): 4.1
* problem: https://vjudge.net/problem/LightOJ-1298
****************************************************************************************/
#include<bits/stdc++.h>
#define long long long
using namespace std;
const int N=2e6;
const long mod=1000000007;
long dp[502][502];
bool isPrime(int x)
{
int sq=sqrt(x+1);
for(int i=2;i<=sq;i++)
if(x%i==0)return false;
return true;
}
vector<int>prime;
long dfs(int pi,int mt)
{
if(pi<0)return mt?0:1;
if(dp[pi][mt]!=-1)return dp[pi][mt];
long now=0,ml=1;
for(int i=1;i<=mt;i++)
{
now=(now+((ml*(prime[pi]-1))%mod)*dfs(pi-1,mt-i))%mod;
ml=(ml*prime[pi])%mod;
}
return dp[pi][mt]=now;
}
int main()
{
//freopen("inp.txt","r",stdin);
//freopen("out.txt","w",stdout);
//ios_base::sync_with_stdio(0);cin.tie(0);
int t,tc=0;cin>>t;
for(int i=2; ;i++)
{
if(prime.size()>500)break;
if(isPrime(i))
prime.push_back(i);
}
memset(dp,-1,sizeof(dp));
while(t--)
{
long ans=0;
int n,p;cin>>n>>p;
cout<<"Case "<<++tc<<": "<<dfs(p-1,n)<<"\n";
}
return 0;
} | 28.075472 | 111 | 0.438172 | kzvd4729 |
960bcbc38b50b7fee00c52e57087d6ad10fb6fee | 7,316 | hxx | C++ | include/idocp/contact_complementarity/contact_normal_force.hxx | KY-Lin22/idocp | 8cacfea7bb2184023eb15316aea07154a62d59bb | [
"BSD-3-Clause"
] | 1 | 2021-09-04T07:43:04.000Z | 2021-09-04T07:43:04.000Z | include/idocp/contact_complementarity/contact_normal_force.hxx | KY-Lin22/idocp | 8cacfea7bb2184023eb15316aea07154a62d59bb | [
"BSD-3-Clause"
] | null | null | null | include/idocp/contact_complementarity/contact_normal_force.hxx | KY-Lin22/idocp | 8cacfea7bb2184023eb15316aea07154a62d59bb | [
"BSD-3-Clause"
] | null | null | null | #ifndef IDOCP_CONTACT_NORMAL_FORCE_HXX_
#define IDOCP_CONTACT_NORMAL_FORCE_HXX_
#include "idocp/contact_complementarity/contact_normal_force.hpp"
#include <exception>
#include <iostream>
#include <assert.h>
namespace idocp {
inline ContactNormalForce::ContactNormalForce(
const Robot& robot, const double barrier,
const double fraction_to_boundary_rate)
: ContactComplementarityComponentBase(barrier, fraction_to_boundary_rate),
dimc_(robot.max_point_contacts()) {
}
inline ContactNormalForce::ContactNormalForce()
: ContactComplementarityComponentBase(),
dimc_(0) {
}
inline ContactNormalForce::~ContactNormalForce() {
}
inline bool ContactNormalForce::isFeasible_impl(Robot& robot,
ConstraintComponentData& data,
const SplitSolution& s) const {
for (int i=0; i<robot.max_point_contacts(); ++i) {
if (robot.is_contact_active(i)) {
if (s.f[i].coeff(2) < 0) {
return false;
}
}
}
return true;
}
inline void ContactNormalForce::setSlackAndDual_impl(
Robot& robot, ConstraintComponentData& data, const double dtau,
const SplitSolution& s) const {
assert(dtau > 0);
for (int i=0; i<robot.max_point_contacts(); ++i) {
data.slack.coeffRef(i) = dtau * s.f[i].coeff(2);
}
setSlackAndDualPositive(data.slack, data.dual);
}
inline void ContactNormalForce::augmentDualResidual_impl(
Robot& robot, ConstraintComponentData& data, const double dtau,
const SplitSolution& s, KKTResidual& kkt_residual) const {
assert(dtau > 0);
int dimf_stack = 0;
for (int i=0; i<robot.max_point_contacts(); ++i) {
if (robot.is_contact_active(i)) {
kkt_residual.lf().coeffRef(dimf_stack+2) -= dtau * data.dual.coeff(i);
dimf_stack += 3;
}
}
}
inline void ContactNormalForce::condenseSlackAndDual_impl(
Robot& robot, ConstraintComponentData& data, const double dtau,
const SplitSolution& s, KKTMatrix& kkt_matrix,
KKTResidual& kkt_residual) const {
assert(dtau > 0);
int dimf_stack = 0;
for (int i=0; i<robot.max_point_contacts(); ++i) {
if (robot.is_contact_active(i)) {
kkt_matrix.Qff().coeffRef(dimf_stack+2, dimf_stack+2)
+= dtau * dtau * data.dual.coeff(i) / data.slack.coeff(i);
data.residual.coeffRef(i) = - dtau * s.f[i].coeff(2) + data.slack.coeff(i);
data.duality.coeffRef(i) = computeDuality(data.slack.coeff(i),
data.dual.coeff(i));
kkt_residual.lf().coeffRef(dimf_stack+2)
-= dtau * (data.dual.coeff(i)*data.residual.coeff(i)-data.duality.coeff(i))
/ data.slack.coeff(i);
dimf_stack += 3;
}
}
}
inline void ContactNormalForce::computeSlackAndDualDirection_impl(
Robot& robot, ConstraintComponentData& data, const double dtau,
const SplitSolution& s, const SplitDirection& d) const {
int dimf_stack = 0;
for (int i=0; i<robot.max_point_contacts(); ++i) {
if (robot.is_contact_active(i)) {
data.dslack.coeffRef(i)
= dtau * d.df().coeff(dimf_stack+2) - data.residual.coeff(i);
data.ddual.coeffRef(i) = computeDualDirection(data.slack.coeff(i),
data.dual.coeff(i),
data.dslack.coeff(i),
data.duality.coeff(i));
dimf_stack += 3;
}
}
}
inline double ContactNormalForce::residualL1Nrom_impl(
Robot& robot, ConstraintComponentData& data, const double dtau,
const SplitSolution& s) const {
double norm = 0;
for (int i=0; i<robot.max_point_contacts(); ++i) {
if (robot.is_contact_active(i)) {
norm += std::abs(data.slack.coeff(i) - dtau * s.f[i].coeff(2));
norm += std::abs(computeDuality(data.slack.coeff(i),
data.dual.coeff(i)));
}
}
return norm;
}
inline double ContactNormalForce::squaredKKTErrorNorm_impl(
Robot& robot, ConstraintComponentData& data, const double dtau,
const SplitSolution& s) const {
double norm = 0;
for (int i=0; i<robot.max_point_contacts(); ++i) {
if (robot.is_contact_active(i)) {
const double residual = data.slack.coeff(i) - dtau * s.f[i].coeff(2);
const double duality = computeDuality(data.slack.coeff(i),
data.dual.coeff(i));
norm += residual * residual + duality * duality;
}
}
return norm;
}
inline int ContactNormalForce::dimc_impl() const {
return dimc_;
}
inline double ContactNormalForce::maxSlackStepSize_impl(
const ConstraintComponentData& data,
const std::vector<bool>& is_contact_active) const {
double min_step_size = 1;
for (int i=0; i<dimc_; ++i) {
if (is_contact_active[i]) {
const double fraction_to_boundary
= fractionToBoundary(data.slack.coeff(i), data.dslack.coeff(i));
if (fraction_to_boundary > 0 && fraction_to_boundary < 1) {
if (fraction_to_boundary < min_step_size) {
min_step_size = fraction_to_boundary;
}
}
}
}
assert(min_step_size > 0);
assert(min_step_size <= 1);
return min_step_size;
}
inline double ContactNormalForce::maxDualStepSize_impl(
const ConstraintComponentData& data,
const std::vector<bool>& is_contact_active) const {
double min_step_size = 1;
for (int i=0; i<dimc_; ++i) {
if (is_contact_active[i]) {
const double fraction_to_boundary
= fractionToBoundary(data.dual.coeff(i), data.ddual.coeff(i));
if (fraction_to_boundary > 0 && fraction_to_boundary < 1) {
if (fraction_to_boundary < min_step_size) {
min_step_size = fraction_to_boundary;
}
}
}
}
assert(min_step_size > 0);
assert(min_step_size <= 1);
return min_step_size;
}
inline void ContactNormalForce::updateSlack_impl(
ConstraintComponentData& data, const std::vector<bool>& is_contact_active,
const double step_size) const {
for (int i=0; i<dimc_; ++i) {
if (is_contact_active[i]) {
data.slack.coeffRef(i) += step_size * data.dslack.coeff(i);
}
}
}
inline void ContactNormalForce::updateDual_impl(
ConstraintComponentData& data, const std::vector<bool>& is_contact_active,
const double step_size) const {
for (int i=0; i<dimc_; ++i) {
if (is_contact_active[i]) {
data.dual.coeffRef(i) += step_size * data.ddual.coeff(i);
}
}
}
inline double ContactNormalForce::costSlackBarrier_impl(
const ConstraintComponentData& data,
const std::vector<bool>& is_contact_active) const {
double cost = 0;
for (int i=0; i<dimc_; ++i) {
if (is_contact_active[i]) {
cost += costSlackBarrier(data.slack.coeff(i));
}
}
return cost;
}
inline double ContactNormalForce::costSlackBarrier_impl(
const ConstraintComponentData& data,
const std::vector<bool>& is_contact_active, const double step_size) const {
double cost = 0;
for (int i=0; i<dimc_; ++i) {
if (is_contact_active[i]) {
cost += costSlackBarrier(data.slack.coeff(i), data.dslack.coeff(i),
step_size);
}
}
return cost;
}
} // namespace idocp
#endif // IDOCP_CONTACT_NORMAL_FORCE_HXX_ | 30.739496 | 86 | 0.642564 | KY-Lin22 |
960d8ac353f53dd95e742ad5cc52fcc2f6226b6d | 4,905 | hpp | C++ | src/config/gc.hpp | Gwenio/synafis | 37176e965318ae555fdc542fc87ffb79866f770f | [
"ISC"
] | 1 | 2019-01-27T14:44:50.000Z | 2019-01-27T14:44:50.000Z | src/config/gc.hpp | Gwenio/synafis | 37176e965318ae555fdc542fc87ffb79866f770f | [
"ISC"
] | null | null | null | src/config/gc.hpp | Gwenio/synafis | 37176e965318ae555fdc542fc87ffb79866f770f | [
"ISC"
] | null | null | null |
/*
ISC License (ISC)
Copyright 2018-2019 Adam Armstrong
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 "general.hpp"
#ifndef SYNAFIS_CONFIG_GC_HPP
#define SYNAFIS_CONFIG_GC_HPP
#pragma once
#include <cstddef>
/** \file src/config/gc.hpp
* \brief Configures the garbage collector.
*/
// Set default configurations for those not specified.
/** \def SYNAFIS_CONFIG_GUARD_PAGES
* \brief The value for config::guard_pages.
* \note Define this value in the compiler commandline.
* \see config::guard_pages
*/
#ifndef SYNAFIS_CONFIG_GUARD_PAGES
#define SYNAFIS_CONFIG_GUARD_PAGES (config::debug)
#endif
/** \def SYNAFIS_CONFIG_MIN_POOL
* \brief The value for config::min_pool.
* \note Define this value in the compiler commandline.
* \see config::min_pool
*/
#ifndef SYNAFIS_CONFIG_MIN_POOL
#define SYNAFIS_CONFIG_MIN_POOL (sizeof(std::size_t) * 8)
#endif
/** \def SYNAFIS_CONFIG_MAX_POOL
* \brief The value for config::max_pool.
* \note Define this value in the compiler commandline.
* \see config::max_pool
*/
#ifndef SYNAFIS_CONFIG_MAX_POOL
#define SYNAFIS_CONFIG_MAX_POOL (sizeof(std::size_t) * 8)
#endif
/** \def SYNAFIS_CONFIG_GC_PERIOD
* \brief The value for config::gc_period.
* \note Define this value in the compiler commandline.
* \see config::gc_period
*/
#ifndef SYNAFIS_CONFIG_GC_PERIOD
#define SYNAFIS_CONFIG_GC_PERIOD 1000
#endif
/** \def SYNAFIS_CONFIG_GC_DEBUG_MUTEX
* \brief The value for config::gc_debug_mutex.
* \note Define this value in the compiler commandline.
* \see config::gc_debug_mutex
*/
#ifndef SYNAFIS_CONFIG_GC_DEBUG_MUTEX
#define SYNAFIS_CONFIG_GC_DEBUG_MUTEX config::debug
#endif
/** \def SYNAFIS_CONFIG_INIT_TRACKING
* \brief The value for config::init_tracking.
* \note Define this value in the compiler commandline.
* \see config::gc_debug_mutex
*/
#ifndef SYNAFIS_CONFIG_INIT_TRACKING
#define SYNAFIS_CONFIG_INIT_TRACKING config::debug
#endif
namespace config {
/** \var guard_pages
* \brief Controls the presence and number of guard pages for blocks of virtual memory.
* \details Set to the preprocessor definition SYNAFIS_CONFIG_GUARD_PAGE.
* \details
* \details Guard pages are page(s) of inaccessible memory separating
* \details accessible regions.
* \details
* \details This detects some memory issues as an error will occur
* \details if the program touches a guard page.
* \details Due to how virtual memory is used in the collector, the detection
* \details provided by this alone is limited.
*/
inline constexpr bool const guard_pages = SYNAFIS_CONFIG_GUARD_PAGES;
/** \var min_pool
* \brief The minimum number of objects a pool can hold.
* \details Set to the preprocessor definition SYNAFIS_CONFIG_MIN_POOL.
*/
inline constexpr std::size_t const min_pool = SYNAFIS_CONFIG_MIN_POOL;
/** \var max_pool
* \brief The maximum number of pages to use for objects in a pool.
* \details Set to the preprocessor definition SYNAFIS_CONFIG_MAX_PAGE.
* \details
* \details The variable min_pool takes priority if min_pool objects
* \details need more space than max_pool pages.
*/
inline constexpr std::size_t const max_pool = SYNAFIS_CONFIG_MAX_POOL;
/** \var gc_period
* \brief The default time to wait between unforced GC cycles.
* \details The value is the number of miliseconds between cycles.
* \details If zero, then collection cycles will only run when forced.
* \see gc::set_period()
*/
inline constexpr std::size_t const gc_period = SYNAFIS_CONFIG_GC_PERIOD;
/** \var gc_debug_mutex
* \brief When true gc::debug_mutex will be used; otherwise, gc::basic_mutex will be used.
* \see gc::mutex
*/
inline constexpr bool const gc_debug_mutex = SYNAFIS_CONFIG_GC_DEBUG_MUTEX;
/** \var init_tracking
* \brief When true allocators will always track if allocated memory is initialized.
*/
inline constexpr bool const init_tracking = SYNAFIS_CONFIG_INIT_TRACKING;
//! TODO At this time config::init_tracking does nothing, as initialization is always tracked.
}
// Remove preprocessor definitions that are no longer needed.
#undef SYNAFIS_CONFIG_GUARD_PAGES
#undef SYNAFIS_CONFIG_MIN_POOL
#undef SYNAFIS_CONFIG_MAX_POOL
#undef SYNAFIS_CONFIG_GC_PERIOD
#undef SYNAFIS_CONFIG_GC_DEBUG_MUTEX
#undef SYNAFIS_CONFIG_INIT_TRACKING
#endif
| 32.7 | 94 | 0.782671 | Gwenio |
960f083afdc553cd111f7655aaefb683c6361e00 | 2,138 | cpp | C++ | libkram/etc2comp/EtcBlock4x4Encoding_RG11.cpp | yanivams/kramUMK | 04d841720cf45b1e7005112643c23177b34ebb84 | [
"MIT"
] | 53 | 2020-11-12T03:29:10.000Z | 2022-03-13T19:00:52.000Z | libkram/etc2comp/EtcBlock4x4Encoding_RG11.cpp | yanivams/kramUMK | 04d841720cf45b1e7005112643c23177b34ebb84 | [
"MIT"
] | 10 | 2020-11-11T16:45:46.000Z | 2022-03-19T18:45:30.000Z | libkram/etc2comp/EtcBlock4x4Encoding_RG11.cpp | yanivams/kramUMK | 04d841720cf45b1e7005112643c23177b34ebb84 | [
"MIT"
] | 3 | 2021-09-29T05:44:18.000Z | 2022-02-28T11:26:34.000Z | /*
* Copyright 2015 The Etc2Comp Authors.
*
* 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.
*/
/*
EtcBlock4x4Encoding_RG11.cpp
Block4x4Encoding_RG11 is the encoder to use when targetting file format RG11 and SRG11 (signed RG11).
*/
#include "EtcConfig.h"
#include "EtcBlock4x4Encoding_RG11.h"
namespace Etc
{
Block4x4Encoding_RG11::Block4x4Encoding_RG11(void)
{
}
Block4x4Encoding_RG11::~Block4x4Encoding_RG11(void) {}
void Block4x4Encoding_RG11::Encode(
const float *sourcePixels, uint8_t *encodingBits, bool isSnorm)
{
m_red.Encode(sourcePixels + 0, encodingBits, isSnorm);
m_green.Encode(sourcePixels + 1, encodingBits + 8, isSnorm);
}
void Block4x4Encoding_RG11::Decode(
unsigned char *encodingBits, const float *sourcePixels, bool isSnorm,
uint16_t lastIteration)
{
m_red.Decode(encodingBits, sourcePixels, isSnorm, (lastIteration >> 0) & 0xFF);
m_green.Decode(encodingBits + 8, sourcePixels + 1, isSnorm, (lastIteration >> 8) & 0xFF);
}
void Block4x4Encoding_RG11::DecodeOnly(
const uint8_t *encodingBits, float *decodedPixels, bool isSnorm)
{
m_red.DecodeOnly(encodingBits, decodedPixels, isSnorm);
m_green.DecodeOnly(encodingBits + 8, decodedPixels + 1, isSnorm);
}
void Block4x4Encoding_RG11::PerformIteration(float a_fEffort)
{
m_red.PerformIteration(a_fEffort);
m_green.PerformIteration(a_fEffort);
}
void Block4x4Encoding_RG11::SetEncodingBits(void)
{
m_red.SetEncodingBits();
m_green.SetEncodingBits();
}
}
| 30.985507 | 102 | 0.703929 | yanivams |
96137485aca19dee42154adb80eb2367a79b611a | 3,481 | cpp | C++ | src/red4ext.loader/Main.cpp | ADawesomeguy/RED4ext | fec0e216b27c30fca66b31a38b850f814b5a48d6 | [
"MIT",
"BSD-3-Clause"
] | null | null | null | src/red4ext.loader/Main.cpp | ADawesomeguy/RED4ext | fec0e216b27c30fca66b31a38b850f814b5a48d6 | [
"MIT",
"BSD-3-Clause"
] | null | null | null | src/red4ext.loader/Main.cpp | ADawesomeguy/RED4ext | fec0e216b27c30fca66b31a38b850f814b5a48d6 | [
"MIT",
"BSD-3-Clause"
] | null | null | null | #include "stdafx.hpp"
#include "pwrprof.hpp"
BOOL APIENTRY DllMain(HMODULE aModule, DWORD aReason, LPVOID aReserved)
{
switch (aReason)
{
case DLL_PROCESS_ATTACH:
{
DisableThreadLibraryCalls(aModule);
try
{
if (!LoadOriginal())
{
return FALSE;
}
constexpr auto msgCaption = L"RED4ext";
constexpr auto dir = L"red4ext";
constexpr auto dll = L"RED4ext.dll";
std::wstring fileName;
auto hr = wil::GetModuleFileNameW(nullptr, fileName);
if (FAILED(hr))
{
wil::unique_hlocal_ptr<wchar_t> buffer;
auto errorCode = GetLastError();
FormatMessage(FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM |
FORMAT_MESSAGE_IGNORE_INSERTS,
nullptr, errorCode, LANG_USER_DEFAULT, wil::out_param_ptr<LPWSTR>(buffer), 0, nullptr);
auto caption = fmt::format(L"{} (error {})", msgCaption, errorCode);
auto message = fmt::format(L"{}\nCould not get the file name.", buffer.get());
MessageBox(nullptr, message.c_str(), caption.c_str(), MB_ICONERROR | MB_OK);
return TRUE;
}
std::error_code fsErr;
std::filesystem::path exePath = fileName;
auto rootPath = exePath
.parent_path() // Resolve to "x64" directory.
.parent_path() // Resolve to "bin" directory.
.parent_path(); // Resolve to game root directory.
auto modPath = rootPath / dir;
if (std::filesystem::exists(modPath, fsErr))
{
auto dllPath = modPath / dll;
if (!LoadLibrary(dllPath.c_str()))
{
wil::unique_hlocal_ptr<wchar_t> buffer;
auto errorCode = GetLastError();
FormatMessage(
FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS,
nullptr, errorCode, LANG_USER_DEFAULT, wil::out_param_ptr<LPWSTR>(buffer), 0, nullptr);
auto caption = fmt::format(L"{} (error {})", msgCaption, errorCode);
auto message =
fmt::format(L"{}\n{}\n\nRED4ext could not be loaded.", buffer.get(), dllPath.c_str());
MessageBox(nullptr, message.c_str(), caption.c_str(), MB_ICONERROR | MB_OK);
}
}
else if (fsErr)
{
auto message =
fmt::format(L"RED4ext could not be loaded because of a filesystem error ({}).", fsErr.value());
MessageBox(nullptr, message.c_str(), msgCaption, MB_ICONERROR | MB_OK);
}
}
catch (const std::exception& e)
{
auto message = fmt::format("An exception occured in RED4ext's loader.\n\n{}", e.what());
MessageBoxA(nullptr, message.c_str(), "RED4ext", MB_ICONERROR | MB_OK);
}
catch (...)
{
MessageBox(nullptr, L"An unknown exception occured in RED4ext's loader.", L"RED4ext", MB_ICONERROR | MB_OK);
}
break;
}
case DLL_PROCESS_DETACH:
{
break;
}
}
return TRUE;
}
| 37.031915 | 120 | 0.520827 | ADawesomeguy |
9615a0237f2635883c350f01e691db9eda49f79d | 1,853 | cpp | C++ | masterui/main.cpp | rickfoosusa/dnp | ec17eb20817db32cc6356139afd2daaa1803576f | [
"BSD-2-Clause-FreeBSD"
] | 1 | 2017-09-19T16:37:59.000Z | 2017-09-19T16:37:59.000Z | masterui/main.cpp | rickfoosusa/dnp | ec17eb20817db32cc6356139afd2daaa1803576f | [
"BSD-2-Clause-FreeBSD"
] | null | null | null | masterui/main.cpp | rickfoosusa/dnp | ec17eb20817db32cc6356139afd2daaa1803576f | [
"BSD-2-Clause-FreeBSD"
] | null | null | null | //
// $Id$
//
// Copyright (C) 2007 Turner Technolgoies Inc. http://www.turner.ca
//
// 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 <QtGui>
#include <QThread>
#include "main_window.hpp"
#include "_test_lpdu.hpp"
#include "_test_master.hpp"
#include "_test_security.hpp"
int main(int argc, char *argv[])
{
QApplication app(argc, argv);
// execute all unit tests
TestLpdu* testLpdu = new TestLpdu();
QTest::qExec(testLpdu);
delete testLpdu;
TestMaster* testMaster = new TestMaster();
QTest::qExec(testMaster);
delete testMaster;
TestSecurity* testSecurity = new TestSecurity();
QTest::qExec(testSecurity);
delete testSecurity;
MainWindow mainWindow;
mainWindow.show();
app.exec();
return 1;
}
| 30.883333 | 68 | 0.706962 | rickfoosusa |
961a790274bac6b16f5fd35135542689ac090d23 | 1,170 | cpp | C++ | codechef/CHEFCOUN/Wrong Answer (3).cpp | kzvd4729/Problem-Solving | 13b105e725a4c2f8db7fecc5d7a8f932b9fef4ab | [
"MIT"
] | 1 | 2022-02-11T16:55:36.000Z | 2022-02-11T16:55:36.000Z | codechef/CHEFCOUN/Wrong Answer (3).cpp | kzvd4729/Problem-Solving | 13b105e725a4c2f8db7fecc5d7a8f932b9fef4ab | [
"MIT"
] | null | null | null | codechef/CHEFCOUN/Wrong Answer (3).cpp | kzvd4729/Problem-Solving | 13b105e725a4c2f8db7fecc5d7a8f932b9fef4ab | [
"MIT"
] | null | null | null | /****************************************************************************************
* @author: kzvd4729 created: 06-10-2017 16:39:17
* solution_verdict: Wrong Answer language: C++14
* run_time: 0.00 sec memory_used: 0M
* problem: https://www.codechef.com/OCT17/problems/CHEFCOUN
****************************************************************************************/
#include<bits/stdc++.h>
#define long long long
using namespace std;
long t,n;
int main()
{
ios_base::sync_with_stdio(0);
cin.tie(0);
cout.tie(0);
cin>>t;
while(t--)
{
cin>>n;
for(long i=1;i<n;i++)
{
if(i==10)cout<<999<<" ";
else if(i==45)cout<<991<<" ";
else if(i==50)cout<<100000<<" ";
else if(i==57)cout<<991<<" ";
else if(i==100)cout<<999<<" ";
else if(i==200)cout<<100000<<" ";
else cout<<9999<<" ";
}
cout<<9999<<endl;
}
return 0;
} | 35.454545 | 111 | 0.347863 | kzvd4729 |
961aa56c24a00f05dca64939859d74b637135eb8 | 2,150 | cpp | C++ | test/btunittest/Agent/EmployeeParTestAgent.cpp | pjkui/behaviac-1 | 426fbac954d7c1db00eb842d6e0b9390fda82dd3 | [
"BSD-3-Clause"
] | 2 | 2016-12-11T09:40:43.000Z | 2021-07-09T22:55:38.000Z | test/btunittest/Agent/EmployeeParTestAgent.cpp | BantamJoe/behaviac-1 | 426fbac954d7c1db00eb842d6e0b9390fda82dd3 | [
"BSD-3-Clause"
] | null | null | null | test/btunittest/Agent/EmployeeParTestAgent.cpp | BantamJoe/behaviac-1 | 426fbac954d7c1db00eb842d6e0b9390fda82dd3 | [
"BSD-3-Clause"
] | 10 | 2016-11-29T12:04:07.000Z | 2018-09-04T06:13:30.000Z | /////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// Tencent is pleased to support the open source community by making behaviac available.
//
// Copyright (C) 2015 THL A29 Limited, a Tencent company. All rights reserved.
//
// Licensed under the BSD 3-Clause License (the "License"); you may not use this file except in compliance with
// the License. You may obtain a copy of the License at http://opensource.org/licenses/BSD-3-Clause
//
// 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 "EmployeeParTestAgent.h"
float EmployeeParTestAgent::STV_F_0 = 0.0f;
behaviac::string EmployeeParTestAgent::STV_STR_0 = "";
behaviac::Agent* EmployeeParTestAgent::STV_AGENT_0 = NULL;
behaviac::vector<float> EmployeeParTestAgent::STV_LIST_F_0;
behaviac::vector<behaviac::string> EmployeeParTestAgent::STV_LIST_STR_0;
behaviac::vector<behaviac::Agent*> EmployeeParTestAgent::STV_LIST_AGENT_0;
EmployeeParTestAgent::EmployeeParTestAgent()
{
TV_UINT_0 = 0;
TV_ULONG_0 = 0L;
TV_LL_0 = 0L;
TV_ULL_0 = 0L;
TV_F_0 = 0.0f;
TV_D_0 = 0.0;
TV_STR_0 = "";
TV_AGENT_0 = NULL;
TV_CSZSTR_0 = 0;
TV_SZSTR_0 = 0;
}
EmployeeParTestAgent::~EmployeeParTestAgent()
{
}
void EmployeeParTestAgent::resetProperties()
{
super::resetProperties();
TV_UINT_0 = 0;
TV_ULONG_0 = 0L;
TV_F_0 = 0.0f;
STV_F_0 = 0.0f;
TV_D_0 = 0.0;
TV_LL_0 = 0L;
TV_ULL_0 = 0L;
TV_STR_0 = "";
TV_SZSTR_0 = NULL;
TV_CSZSTR_0 = "TV_CSZSTR_0";
STV_STR_0 = "";
TV_AGENT_0 = NULL;
STV_AGENT_0 = NULL;
TV_LIST_F_0.clear();
STV_LIST_F_0.clear();
TV_LIST_STR_0.clear();
STV_LIST_STR_0.clear();
TV_LIST_AGENT_0.clear();
STV_LIST_AGENT_0.clear();
}
| 32.089552 | 113 | 0.640465 | pjkui |
961bbf250f7721ddd5d8fba573dcef81b1436d73 | 304 | cpp | C++ | Point.cpp | argorain/dtw | f863bf38882a36accc6da80101b1201c43cd3261 | [
"MIT"
] | null | null | null | Point.cpp | argorain/dtw | f863bf38882a36accc6da80101b1201c43cd3261 | [
"MIT"
] | null | null | null | Point.cpp | argorain/dtw | f863bf38882a36accc6da80101b1201c43cd3261 | [
"MIT"
] | null | null | null | //
// Created by rain on 27.5.15.
//
#include "Point.h"
Point::Point() {
x=y=0;
}
Point::Point(int x, int y) {
this->x=x;
this->y=y;
}
int Point::getX() { return x; }
int Point::getY() { return y; }
void Point::setX(const int x) { this->x=x; }
void Point::setY(const int y) { this->y=y; } | 16 | 44 | 0.559211 | argorain |
962da2035184e223c3aabb2569c6565c254aa433 | 1,948 | cpp | C++ | Parse/PFManager.cpp | sourada/Parse-Qt-SDK | 32bb10a37ddebc71bae4e648438efb3bd9fdd48b | [
"BSD-2-Clause-FreeBSD"
] | null | null | null | Parse/PFManager.cpp | sourada/Parse-Qt-SDK | 32bb10a37ddebc71bae4e648438efb3bd9fdd48b | [
"BSD-2-Clause-FreeBSD"
] | null | null | null | Parse/PFManager.cpp | sourada/Parse-Qt-SDK | 32bb10a37ddebc71bae4e648438efb3bd9fdd48b | [
"BSD-2-Clause-FreeBSD"
] | null | null | null | //
// PFManager.cpp
// Parse
//
// Created by Christian Noon on 11/5/13.
// Copyright (c) 2013 Christian Noon. All rights reserved.
//
// Parse headers
#include "PFManager.h"
// Qt headers
#include <QMutex>
#include <QMutexLocker>
namespace parse {
// Static Globals
static QMutex gPFManagerMutex;
#ifdef __APPLE__
#pragma mark - Memory Management Methods
#endif
PFManager::PFManager() :
_applicationId(""),
_restApiKey(""),
_masterKey(""),
_cacheDirectory(""),
_networkAccessManager()
{
// Define the default cache directory as $$TMPDIR/Parse
_cacheDirectory = QDir::temp();
_cacheDirectory.mkdir("Parse");
_cacheDirectory.cd("Parse");
qDebug() << "Cache directory:" << _cacheDirectory.absolutePath();
}
PFManager::~PFManager()
{
// No-op
}
#ifdef __APPLE__
#pragma mark - Creation Methods
#endif
PFManager* PFManager::sharedManager()
{
QMutexLocker lock(&gPFManagerMutex);
static PFManager manager;
return &manager;
}
#ifdef __APPLE__
#pragma mark - User API
#endif
void PFManager::setApplicationIdAndRestApiKey(const QString& applicationId, const QString& restApiKey)
{
_applicationId = applicationId;
_restApiKey = restApiKey;
}
void PFManager::setMasterKey(const QString& masterKey)
{
_masterKey = masterKey;
}
const QString& PFManager::applicationId()
{
return _applicationId;
}
const QString& PFManager::restApiKey()
{
return _restApiKey;
}
const QString& PFManager::masterKey()
{
return _masterKey;
}
#ifdef __APPLE__
#pragma mark - Backend API - Caching and Network Methods
#endif
QNetworkAccessManager* PFManager::networkAccessManager()
{
return &_networkAccessManager;
}
void PFManager::setCacheDirectory(const QDir& cacheDirectory)
{
_cacheDirectory = cacheDirectory;
}
QDir& PFManager::cacheDirectory()
{
return _cacheDirectory;
}
void PFManager::clearCache()
{
_cacheDirectory.removeRecursively();
_cacheDirectory.mkpath(_cacheDirectory.absolutePath());
}
} // End of parse namespace
| 17.54955 | 102 | 0.747433 | sourada |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.