blob_id stringlengths 40 40 | directory_id stringlengths 40 40 | path stringlengths 3 264 | content_id stringlengths 40 40 | detected_licenses listlengths 0 85 | license_type stringclasses 2
values | repo_name stringlengths 5 140 | snapshot_id stringlengths 40 40 | revision_id stringlengths 40 40 | branch_name stringclasses 986
values | visit_date timestamp[us] | revision_date timestamp[us] | committer_date timestamp[us] | github_id int64 3.89k 681M ⌀ | star_events_count int64 0 209k | fork_events_count int64 0 110k | gha_license_id stringclasses 23
values | gha_event_created_at timestamp[us] | gha_created_at timestamp[us] | gha_language stringclasses 145
values | src_encoding stringclasses 34
values | language stringclasses 1
value | is_vendor bool 1
class | is_generated bool 2
classes | length_bytes int64 3 10.4M | extension stringclasses 122
values | content stringlengths 3 10.4M | authors listlengths 1 1 | author_id stringlengths 0 158 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
c305e963e9580d32b45ec2862f7043010e500aa5 | 406ce23771eda2a64efcf41cce28a31e6c7ecd87 | /BOJ/1012.cpp | fd86a4dffedbddf8cfe02cc6dc0719bcc1c6bb47 | [] | no_license | ypd01018/Algorithm | 53d22c9f30e9025af25401718066c73200a6bcb2 | 8382f3adb6f84620d929fcac128cc49fba2f7b6e | refs/heads/master | 2023-06-08T14:25:19.104589 | 2021-06-30T23:19:58 | 2021-06-30T23:19:58 | 324,764,846 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,562 | cpp | #include<bits/stdc++.h>
#define f first
#define s second
using namespace std;
int T,M,N,K,dx[4]={-1,0,1,0},dy[4]={0,1,0,-1},n;
stack<pair<int,int>> stk;
queue<pair<int,int>> q;
pair<bool,bool> mat[60][60];
void input()
{
int x,y;
cin >> M >> N >> K;
for(int i = 0 ; i < N ;i++)
{
for(int j = 0 ; j < M ;j++)
{
mat[i][j].first=0;
mat[i][j].second=0;
}
}
for(int i = 0 ; i <K; i++)
{
cin >> x >> y;
mat[y][x].first=1;
}
}
void sol()
{
for(int i = 0 ; i < N ;i++)
{
for(int j=0 ; j<M ;j++)
{
if(mat[i][j].f == 0 || mat[i][j].s == 1) continue; //배추지역이 아니거나(0) 이미 간곳이면(1) continue
n++;
q.push(make_pair(i,j));
mat[i][j].s=1;
while(!q.empty())
{
auto cur = q.front();
q.pop();
for(int dir=0 ; dir<4;dir++)
{
int nx = cur.s + dx[dir], ny = cur.f + dy[dir];
if(nx < 0 || nx >= M || ny < 0 || ny >=N ) continue;
if(mat[ny][nx].f == 0 || mat[ny][nx].s == 1) continue;
mat[ny][nx].s = 1;
q.push(make_pair(ny,nx));
//cout << "important:" << q.size() << endl;
}
}
}
}
}
int main()
{
cin >> T;
for(int i = 0 ; i < T;i++)
{
n=0;
input();
sol();
cout << n << endl;
}
}
| [
"ypd01018@naver.com"
] | ypd01018@naver.com |
8b936fdde655462343005273550c31ada8bc705d | 1bd2698bde9265ab4741358c2b8e1bec1901e7f9 | /Tonb0.1/AutLib/Geom/Merge/Point/Merge_Pnt.hxx | 22b2e2974082aec71e55569618dd3549debbcb1c | [] | no_license | amir5200fx/Tonb0.1 | 150f9843ce3ad02da2ef18f409a100964c08983a | 7b17c6d2b3ddeca8e6b2900967b9599b0b1d61ed | refs/heads/master | 2022-01-17T09:47:25.291502 | 2019-06-14T13:27:39 | 2019-06-14T13:27:39 | 169,406,796 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 12,232 | hxx | #pragma once
#ifndef _Merge_Pnt_Header
#define _Merge_Pnt_Header
#include <Global_Macros.hxx>
#include <Standard_TypeDef.hxx>
#include <Traits.hxx>
#include <error.hxx>
#include <OSstream.hxx>
#include <memory>
#include <vector>
#include <algorithm>
namespace AutLib
{
class Merge_Info
{
/*Private Data*/
Standard_Real theResolution_;
Standard_Real theRadius_;
protected:
Merge_Info();
Merge_Info
(
const Standard_Real theRes,
const Standard_Real theRadius
)
: theResolution_(theRes)
, theRadius_(theRadius)
{}
public:
// Static data members
static const Standard_Real DEFAULT_RESOLUTION;
static const Standard_Real DEFAULT_RADIUS;
Standard_Real Resolution() const
{
return theRadius_;
}
Standard_Real Radius() const
{
return theRadius_;
}
void SetResolution
(
const Standard_Real theRes
)
{
theResolution_ = theRes;
}
void SetRadius
(
const Standard_Real theRadius
)
{
theRadius_ = theRadius;
}
};
template<class Point>
class Merge_Params
{
/*Private Data*/
Point thePmin_;
Point thePmax_;
Standard_Real theDelta_;
Standard_Integer theMaxIndex_;
protected:
Merge_Params()
: theDelta_(0)
, theMaxIndex_(0)
{}
void SetPmin
(
const Point& theCoord
)
{
thePmin_ = theCoord;
}
void SetPmax
(
const Point& theCoord
)
{
thePmax_ = theCoord;
}
void SetDelta
(
const Standard_Real Value
)
{
theDelta_ = Value;
}
void SetMaxIndex
(
const Standard_Integer Value
)
{
theMaxIndex_ = Value;
}
public:
const Point& Pmin() const
{
return thePmin_;
}
Point& Pmin()
{
return thePmin_;
}
const Point& Pmax() const
{
return thePmax_;
}
Point& Pmax()
{
return thePmax_;
}
Standard_Real Delta() const
{
return theDelta_;
}
Standard_Integer MaxIndex() const
{
return theMaxIndex_;
}
};
template<int Dim> struct Merge_StaticMemory
{
protected: static std::vector<Standard_Integer> keys;
};
template<> std::vector<Standard_Integer> Merge_StaticMemory<2>::keys(9);
template<> std::vector<Standard_Integer> Merge_StaticMemory<3>::keys(27);
enum Merge_PntAlg
{
Merge_PntAlg_Mean,
Merge_PntAlg_Substitude
};
template
<
class Point,
template<class> class NodeVector,
Merge_PntAlg Alg = Merge_PntAlg_Mean
>
class Merge_Pnt
: public Merge_Info
, public Merge_Params<Point>
, public Merge_StaticMemory<Point::dim>
{
public:
//typedef typename remove_pointer<Point>::type Point;
typedef Merge_Params<Point> Params;
typedef Merge_StaticMemory<Point::dim> memory;
typedef Merge_Info Base;
template< bool cond, typename U >
using resolvedType = typename std::enable_if< cond, U >::type;
struct node
{
//- coordinate of the node
Point Coord;
//- index of the node
Standard_Integer Index;
};
typedef std::shared_ptr<std::vector<std::shared_ptr<node>>>
nodeListPtr;
template<class Point>
using Merge_NodeTable = std::vector<nodeListPtr>;
typedef Merge_NodeTable<std::shared_ptr<node>> nodeTable;
typedef std::vector<std::shared_ptr<node>> nodeList;
typedef std::vector<Standard_Integer> indexList;
private:
/*Private Data*/
const NodeVector<Point>* theCoords_;
nodeList theNodes_;
Standard_Boolean IsDone_;
/*Private functions and operators*/
Standard_Integer Round
(
const Standard_Real x
) const
{
return (Standard_Integer)floor(x + 0.5);
}
Standard_Integer Key
(
const Point& theCoord
) const
{
Standard_Integer key = 0;
for (Standard_Integer i = 1; i <= Point::nbCmpts; i++)
key += Round
(
MAX(theCoord.Coord(i) - Params::Pmin().Coord(i),
(Standard_Real)0.) / Params::Delta()
);
return key;
}
template<class U = void>
resolvedType
<
is_two_dimension<(int)Point::dim>::value, U
>
Keys
(
const Standard_Real d,
const Point& theCoord
) const
{
Standard_Real Xo = theCoord.X();
Standard_Real Yo = theCoord.Y();
memory::keys[0] = Key(Point(Xo - d, Yo - d));
memory::keys[1] = Key(Point(Xo, Yo - d));
memory::keys[2] = Key(Point(Xo + d, Yo - d));
memory::keys[3] = Key(Point(Xo - d, Yo));
memory::keys[4] = Key(theCoord);
memory::keys[5] = Key(Point(Xo + d, Yo));
memory::keys[6] = Key(Point(Xo - d, Yo + d));
memory::keys[7] = Key(Point(Xo, Yo + d));
memory::keys[8] = Key(Point(Xo + d, Yo + d));
}
template<class U = void>
resolvedType
<
is_three_dimension<(int)Point::dim>::value, U
>
Keys
(
const Standard_Real d,
const Point& theCoord
) const
{
Standard_Real Xo = theCoord.X();
Standard_Real Yo = theCoord.Y();
Standard_Real Zo = theCoord.Z();
memory::keys[0] = Key(Point(Xo - d, Yo - d, Zo - d));
memory::keys[1] = Key(Point(Xo, Yo - d, Zo - d));
memory::keys[2] = Key(Point(Xo + d, Yo - d, Zo - d));
memory::keys[3] = Key(Point(Xo - d, Yo, Zo - d));
memory::keys[4] = Key(Point(Xo, Yo, Zo - d));
memory::keys[5] = Key(Point(Xo + d, Yo, Zo - d));
memory::keys[6] = Key(Point(Xo - d, Yo + d, Zo - d));
memory::keys[7] = Key(Point(Xo, Yo + d, Zo - d));
memory::keys[8] = Key(Point(Xo + d, Yo + d, Zo - d));
memory::keys[9] = Key(Point(Xo - d, Yo - d, Zo));
memory::keys[10] = Key(Point(Xo, Yo - d, Zo));
memory::keys[11] = Key(Point(Xo + d, Yo - d, Zo));
memory::keys[12] = Key(Point(Xo - d, Yo, Zo));
memory::keys[13] = Key(theCoord);
memory::keys[14] = Key(Point(Xo + d, Yo, Zo));
memory::keys[15] = Key(Point(Xo - d, Yo + d, Zo));
memory::keys[16] = Key(Point(Xo, Yo + d, Zo));
memory::keys[17] = Key(Point(Xo + d, Yo + d, Zo));
memory::keys[18] = Key(Point(Xo - d, Yo - d, Zo + d));
memory::keys[19] = Key(Point(Xo, Yo - d, Zo + d));
memory::keys[20] = Key(Point(Xo + d, Yo - d, Zo + d));
memory::keys[21] = Key(Point(Xo - d, Yo, Zo + d));
memory::keys[22] = Key(Point(Xo, Yo, Zo + d));
memory::keys[23] = Key(Point(Xo + d, Yo, Zo + d));
memory::keys[24] = Key(Point(Xo - d, Yo + d, Zo + d));
memory::keys[25] = Key(Point(Xo, Yo + d, Zo + d));
memory::keys[26] = Key(Point(Xo + d, Yo + d, Zo + d));
}
nodeList Search
(
const Point& theCoord,
const nodeTable& theTable
) const
{
Standard_Real d = 0.499*Params::Delta();
Keys(d, theCoord);
std::sort(memory::keys.begin(), memory::keys.end());
Standard_Integer perKey = -IntegerLast();
nodeList nodes;
for (const auto& key : memory::keys)
{
if (key <= perKey) continue;
const nodeListPtr& listPtr =
theTable[key];
if (listPtr)
{
for (const auto& item : *listPtr)
{
nodes.push_back(item);
}
}
perKey = key;
}
return std::move(nodes);
}
static nodeList GetNodes
(
const NodeVector<Point>& Coords
)
{
nodeList nodeList(Coords.size());
Standard_Integer K = 0;
for (auto& x : nodeList)
{
x = std::make_shared<node>();
x->Index = K + 1;
x->Coord = Coords[K];
K++;
}
return std::move(nodeList);
}
void FindMinMax
(
const std::vector<Point>& theCoord
)
{
Params::Pmin() = Params::Pmax() = *theCoord.begin();
auto& pMin = Params::Pmin();
auto& pMax = Params::Pmax();
for (const auto& x : theCoord)
{
for (int i = 1; i <= Point::nbCmpts; i++)
{
if (x.Coord(i) < pMin.Coord(i))
pMin.SetCoord(i, x.Coord(i));
if (x.Coord(i) > pMax.Coord(i))
pMax.SetCoord(i, x.Coord(i));
}
}
}
void CalcResolution()
{
FindMinMax(*theCoords_);
Standard_Real D = (Standard_Real)0.;
for (Standard_Integer coord = 1; coord <= Point::nbCmpts; coord++)
{
Standard_Real d =
Params::Pmax().Coord(coord) - Params::Pmin().Coord(coord);
if (d > D) D = d;
}
if (D <= (Standard_Real)0.)
{
FatalErrorIn(FunctionSIG)
<< "Singularity domain size"
<< abort(FatalError);
}
Params::SetDelta(2.0*Resolution()*D);
if (Params::Delta() < Radius()) Params::SetDelta(Radius() + EPS6 * D);
Params::SetPmin(Params::Pmin() - 2.0*Params::Delta());
Params::SetMaxIndex(Key(Params::Pmax() + 2.0*Params::Delta()));
if (Params::MaxIndex() <= 0)
{
FatalErrorIn(FunctionSIG)
<< "Singularity domain size"
<< abort(FatalError);
}
}
template<int Alg> void UpdateNode(node& inode, node& item) const;
template<>
void UpdateNode<Merge_PntAlg_Mean>
(
node& inode,
node& item
) const
{
inode.Index = item.Index;
inode.Coord = item.Coord = MEAN(inode.Coord, item.Coord);
}
template<>
void UpdateNode<Merge_PntAlg_Substitude>
(
node& inode,
node& item
) const
{
inode.Index = item.Index;
}
void Merge()
{
nodeTable table(Params::MaxIndex() + 1);
Standard_Integer
key,
Flag;
for (const auto& inode : theNodes_)
{
const auto& Pt = inode->Coord;
nodeList Found = Search(Pt, table);
Flag = 0;
for (const auto& item : Found)
{
if (Pt.Distance(item->Coord) <= Base::Radius())
{
Flag = 1;
UpdateNode<Alg>(*inode, *item);
break;
}
}
if (!Flag)
{
key = Key(Pt);
if (!table[key])
{
table[key] = std::make_shared<nodeList>();
}
table[key]->push_back(inode);
}
}
}
Standard_Boolean& IsDone()
{
return IsDone_;
}
public:
Merge_Pnt()
: theCoords_(nullptr)
, IsDone_(Standard_False)
{}
Merge_Pnt
(
const Standard_Real theRes,
const Standard_Real theRadius
)
: Merge_Info(theRes, theRadius)
, theCoords_(nullptr)
, IsDone_(Standard_False)
{}
Merge_Pnt
(
const NodeVector<Point>& theCoords
)
: theCoords_(&theCoords)
, IsDone_(Standard_False)
{}
Merge_Pnt
(
const NodeVector<Point>& theCoords,
const Standard_Real theRes,
const Standard_Real theRadius
)
: Merge_Info(theRes, theRadius)
, theCoords_(&theCoords)
, IsDone_(Standard_False)
{}
Standard_Boolean IsDone() const
{
return IsDone_;
}
void SetCoords
(
const NodeVector<Point>& theCoords
)
{
theCoords_ = &theCoords;
}
std::vector<Point> CompactPoints() const
{
if (NOT IsDone())
{
FatalErrorIn(FunctionSIG)
<< "Merging Points is not performed!"
<< abort(FatalError);
}
if (IsNULL(theCoords_))
{
FatalErrorIn(FunctionSIG)
<< "no points have been imported"
<< abort(FatalError);
}
std::vector<Point> mergedList;
int K = 0;
for (const auto& pt : theNodes_)
{
if (pt->Index IS_EQUAL K + 1)
mergedList.push_back(pt->Coord);
K++;
}
return std::move(mergedList);
}
indexList CompactIndices() const
{
if (NOT IsDone())
{
FatalErrorIn(FunctionSIG)
<< "Merging Points is not performed!"
<< abort(FatalError);
}
if (IsNULL(theCoords_))
{
FatalErrorIn(FunctionSIG)
<< "no points have been imported"
<< abort(FatalError);
}
indexList compactVector(theNodes_.size());
Standard_Integer K = 0;
for (const auto& x : theNodes_)
{
if (x->Index IS_EQUAL K + 1) compactVector[K] = -1;
else compactVector[K] = x->Index;
K++;
}
K = 0;
for (auto& x : compactVector)
if (x < 0) x = ++K;
forThose(Index, 0, compactVector.size() - 1)
{
if (theNodes_[Index]->Index NOT_EQUAL Index + 1)
{
compactVector[Index] = compactVector[compactVector[Index] - 1];
}
}
return std::move(compactVector);
}
const nodeList& Nodes() const
{
return theNodes_;
}
void Perform()
{
if (IsNULL(theCoords_))
{
FatalErrorIn(FunctionSIG)
<< " No Point Lists detected"
<< abort(FatalError);
}
if (NOT theCoords_->size())
{
FatalErrorIn(FunctionSIG)
<< " Point Lists is empty"
<< abort(FatalError);
}
theNodes_.resize(theCoords_->size());
if (theCoords_->size() IS_EQUAL 1)
{
theNodes_[0] = std::make_shared<node>();
theNodes_[0]->Index = 1;
theNodes_[0]->Coord = (*theCoords_)[0];
return;
}
CalcResolution();
theNodes_ = GetNodes(*theCoords_);
Merge();
IsDone() = Standard_True;
}
};
}
#endif // !_Merge_Pnt_Header
| [
"ma.yaaghoubi@gmail.com"
] | ma.yaaghoubi@gmail.com |
e0268d7a324d85eade450757b3c123d55918fa1d | 001bff3a9254779345f2fc22a02786decafe4678 | /11/debian-10/postgresql-repmgr-11.11.0-15-linux-amd64-debian-10/files/postgresql/include/geos/operation/buffer/OffsetSegmentGenerator.h | 6f461dd7418f629b623ef9fa9764c28e1817a4db | [
"GPL-2.0-only",
"MIT",
"Zlib",
"Apache-2.0",
"LicenseRef-scancode-unknown-license-reference"
] | permissive | radondb-pg/radondb-postgresql-kubernetes | 33fe153b2b2148486e9ae3020c6b9664bc603e39 | e7a308cb4fd4c31e76b80d4aaabc9463a912c8fd | refs/heads/main | 2023-07-11T16:10:30.562439 | 2021-08-19T11:42:11 | 2021-08-19T11:42:11 | 370,936,467 | 0 | 0 | Apache-2.0 | 2021-05-26T06:56:52 | 2021-05-26T06:56:51 | null | UTF-8 | C++ | false | false | 11,294 | h | /**********************************************************************
*
* GEOS - Geometry Engine Open Source
* http://geos.osgeo.org
*
* Copyright (C) 2011 Sandro Santilli <strk@kbt.io>
*
* This is free software; you can redistribute and/or modify it under
* the terms of the GNU Lesser General Public Licence as published
* by the Free Software Foundation.
* See the COPYING file for more information.
*
**********************************************************************
*
* Last port: operation/buffer/OffsetSegmentGenerator.java r378 (JTS-1.12)
*
**********************************************************************/
#ifndef GEOS_OP_BUFFER_OFFSETSEGMENTGENERATOR_H
#define GEOS_OP_BUFFER_OFFSETSEGMENTGENERATOR_H
#include <geos/export.h>
#include <vector>
#include <geos/algorithm/LineIntersector.h> // for composition
#include <geos/geom/Coordinate.h> // for composition
#include <geos/geom/LineSegment.h> // for composition
#include <geos/operation/buffer/BufferParameters.h> // for composition
#include <geos/operation/buffer/OffsetSegmentString.h> // for composition
#ifdef _MSC_VER
#pragma warning(push)
#pragma warning(disable: 4251) // warning C4251: needs to have dll-interface to be used by clients of class
#endif
// Forward declarations
namespace geos {
namespace geom {
class CoordinateSequence;
class PrecisionModel;
}
}
namespace geos {
namespace operation { // geos.operation
namespace buffer { // geos.operation.buffer
/**
* Generates segments which form an offset curve.
* Supports all end cap and join options
* provided for buffering.
* Implements various heuristics to
* produce smoother, simpler curves which are
* still within a reasonable tolerance of the
* true curve.
*
* @author Martin Davis
*
*/
class GEOS_DLL OffsetSegmentGenerator {
public:
/*
* @param nBufParams buffer parameters, this object will
* keep a reference to the passed parameters
* so caller must make sure the object is
* kept alive for the whole lifetime of
* the buffer builder.
*/
OffsetSegmentGenerator(const geom::PrecisionModel* newPrecisionModel,
const BufferParameters& bufParams, double distance);
/**
* Tests whether the input has a narrow concave angle
* (relative to the offset distance).
* In this case the generated offset curve will contain self-intersections
* and heuristic closing segments.
* This is expected behaviour in the case of buffer curves.
* For pure offset curves,
* the output needs to be further treated
* before it can be used.
*
* @return true if the input has a narrow concave angle
*/
bool
hasNarrowConcaveAngle() const
{
return _hasNarrowConcaveAngle;
}
void initSideSegments(const geom::Coordinate& nS1,
const geom::Coordinate& nS2, int nSide);
/// Get coordinates by taking ownership of them
//
/// After this call, the coordinates reference in
/// this object are dropped. Calling twice will
/// segfault...
///
/// FIXME: refactor memory management of this
///
void
getCoordinates(std::vector<geom::CoordinateSequence*>& to)
{
to.push_back(segList.getCoordinates());
}
void
closeRing()
{
segList.closeRing();
}
/// Adds a CW circle around a point
void createCircle(const geom::Coordinate& p, double distance);
/// Adds a CW square around a point
void createSquare(const geom::Coordinate& p, double distance);
/// Add first offset point
void
addFirstSegment()
{
segList.addPt(offset1.p0);
}
/// Add last offset point
void
addLastSegment()
{
segList.addPt(offset1.p1);
}
void addNextSegment(const geom::Coordinate& p, bool addStartPoint);
/// \brief
/// Add an end cap around point p1, terminating a line segment
/// coming from p0
void addLineEndCap(const geom::Coordinate& p0,
const geom::Coordinate& p1);
void
addSegments(const geom::CoordinateSequence& pts, bool isForward)
{
segList.addPts(pts, isForward);
}
private:
/**
* Factor which controls how close offset segments can be to
* skip adding a filler or mitre.
*/
static const double OFFSET_SEGMENT_SEPARATION_FACTOR; // 1.0E-3;
/**
* Factor which controls how close curve vertices on inside turns
* can be to be snapped
*/
static const double INSIDE_TURN_VERTEX_SNAP_DISTANCE_FACTOR; // 1.0E-3;
/**
* Factor which controls how close curve vertices can be to be snapped
*/
static const double CURVE_VERTEX_SNAP_DISTANCE_FACTOR; // 1.0E-6;
/**
* Factor which determines how short closing segs can be for round buffers
*/
static const int MAX_CLOSING_SEG_LEN_FACTOR = 80;
/** \brief
* the max error of approximation (distance) between a quad segment and
* the true fillet curve
*/
double maxCurveSegmentError; // 0.0
/** \brief
* The angle quantum with which to approximate a fillet curve
* (based on the input # of quadrant segments)
*/
double filletAngleQuantum;
/// The Closing Segment Factor controls how long "closing
/// segments" are. Closing segments are added at the middle of
/// inside corners to ensure a smoother boundary for the buffer
/// offset curve. In some cases (particularly for round joins
/// with default-or-better quantization) the closing segments
/// can be made quite short. This substantially improves
/// performance (due to fewer intersections being created).
///
/// A closingSegFactor of 0 results in lines to the corner vertex.
/// A closingSegFactor of 1 results in lines halfway
/// to the corner vertex.
/// A closingSegFactor of 80 results in lines 1/81 of the way
/// to the corner vertex (this option is reasonable for the very
/// common default situation of round joins and quadrantSegs >= 8).
///
/// The default is 1.
///
int closingSegLengthFactor; // 1;
/// Owned by this object, destroyed by dtor
//
/// This actually gets created multiple times
/// and each of the old versions is pushed
/// to the ptLists std::vector to ensure all
/// created CoordinateSequences are properly
/// destroyed.
///
OffsetSegmentString segList;
double distance;
const geom::PrecisionModel* precisionModel;
const BufferParameters& bufParams;
algorithm::LineIntersector li;
geom::Coordinate s0, s1, s2;
geom::LineSegment seg0;
geom::LineSegment seg1;
geom::LineSegment offset0;
geom::LineSegment offset1;
int side;
bool _hasNarrowConcaveAngle; // =false
void addCollinear(bool addStartPoint);
/// The mitre will be beveled if it exceeds the mitre ratio limit.
//
/// @param offset0 the first offset segment
/// @param offset1 the second offset segment
/// @param distance the offset distance
///
void addMitreJoin(const geom::Coordinate& p,
const geom::LineSegment& offset0,
const geom::LineSegment& offset1,
double distance);
/// Adds a limited mitre join connecting the two reflex offset segments.
//
/// A limited mitre is a mitre which is beveled at the distance
/// determined by the mitre ratio limit.
///
/// @param offset0 the first offset segment
/// @param offset1 the second offset segment
/// @param distance the offset distance
/// @param mitreLimit the mitre limit ratio
///
void addLimitedMitreJoin(
const geom::LineSegment& offset0,
const geom::LineSegment& offset1,
double distance, double mitreLimit);
/// \brief
/// Adds a bevel join connecting the two offset segments
/// around a reflex corner.
//
/// @param offset0 the first offset segment
/// @param offset1 the second offset segment
///
void addBevelJoin(const geom::LineSegment& offset0,
const geom::LineSegment& offset1);
static const double PI; // 3.14159265358979
// Not in JTS, used for single-sided buffers
int endCapIndex;
void init(double newDistance);
/**
* Use a value which results in a potential distance error which is
* significantly less than the error due to
* the quadrant segment discretization.
* For QS = 8 a value of 100 is reasonable.
* This should produce a maximum of 1% distance error.
*/
static const double SIMPLIFY_FACTOR; // 100.0;
/// Adds the offset points for an outside (convex) turn
//
/// @param orientation
/// @param addStartPoint
///
void addOutsideTurn(int orientation, bool addStartPoint);
/// Adds the offset points for an inside (concave) turn
//
/// @param orientation
/// @param addStartPoint
///
void addInsideTurn(int orientation, bool addStartPoint);
/** \brief
* Compute an offset segment for an input segment on a given
* side and at a given distance.
*
* The offset points are computed in full double precision,
* for accuracy.
*
* @param seg the segment to offset
* @param side the side of the segment the offset lies on
* @param distance the offset distance
* @param offset the points computed for the offset segment
*/
void computeOffsetSegment(const geom::LineSegment& seg,
int side, double distance,
geom::LineSegment& offset);
/**
* Adds points for a circular fillet around a reflex corner.
*
* Adds the start and end points
*
* @param p base point of curve
* @param p0 start point of fillet curve
* @param p1 endpoint of fillet curve
* @param direction the orientation of the fillet
* @param radius the radius of the fillet
*/
void addDirectedFillet(const geom::Coordinate& p, const geom::Coordinate& p0,
const geom::Coordinate& p1,
int direction, double radius);
/**
* Adds points for a circular fillet arc between two specified angles.
*
* The start and end point for the fillet are not added -
* the caller must add them if required.
*
* @param direction is -1 for a CW angle, 1 for a CCW angle
* @param radius the radius of the fillet
*/
void addDirectedFillet(const geom::Coordinate& p, double startAngle,
double endAngle, int direction, double radius);
private:
// An OffsetSegmentGenerator cannot be copied because of member "const BufferParameters& bufParams"
// Not declaring these functions triggers MSVC warning C4512: "assignment operator could not be generated"
OffsetSegmentGenerator(const OffsetSegmentGenerator&);
void operator=(const OffsetSegmentGenerator&);
};
} // namespace geos::operation::buffer
} // namespace geos::operation
} // namespace geos
#ifdef _MSC_VER
#pragma warning(pop)
#endif
#endif // ndef GEOS_OP_BUFFER_OFFSETSEGMENTGENERATOR_H
| [
"hualongzhong@yunify.com"
] | hualongzhong@yunify.com |
a37761e5b4cbaa9e20c16ec0d45fd33c514806cf | 99b53c56031760912f7dc1d8438252101963c8ec | /radial_clock/radial_clock.h | 6406ff2a41dc0d8cc427e799326ee3b54cdd2285 | [] | no_license | bhill74/QtWidgets | f65ca38b1f692e74a1e806b63c36d289c6ab5613 | d044400cb3cbcb077702aa8d07028f72810f05fd | refs/heads/master | 2020-03-17T07:07:54.420298 | 2018-05-25T14:41:44 | 2018-05-25T14:41:44 | 133,384,953 | 0 | 2 | null | null | null | null | UTF-8 | C++ | false | false | 6,711 | h | /****************************************************************************
**
** Copyright (C) 2018 Brian Hill
** All rights reserved.
**
** License Agreement
**
** 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 3 of the License, or
** 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.
**
** Software Author: Brian Hill <brian.hill@glowfish.ca>
**
** Summary: Header for the radial clock widget
**
****************************************************************************/
#ifndef RADIAL_CLOCK_H
#define RADIAL_CLOCK_H
#include <QWidget>
#include <QToolTip>
#include <map>
#include <QtDesigner/QDesignerExportWidget>
class QDESIGNER_WIDGET_EXPORT RadialClock : public QWidget
{
Q_OBJECT
Q_PROPERTY(bool blip READ blip WRITE setBlip);
Q_PROPERTY(bool seconds READ seconds WRITE setSeconds);
Q_PROPERTY(bool minutes READ minutes WRITE setMinutes);
Q_PROPERTY(bool hours READ hours WRITE setHours);
Q_PROPERTY(bool weekDays READ weekDays WRITE setWeekDays);
Q_PROPERTY(bool monthDays READ monthDays WRITE setMonthDays);
Q_PROPERTY(bool yearDays READ yearDays WRITE setYearDays);
Q_PROPERTY(bool months READ months WRITE setMonths);
Q_PROPERTY(QColor outerColor READ outerColor WRITE setOuterColor);
Q_PROPERTY(QColor innerColor READ innerColor WRITE setInnerColor);
Q_PROPERTY(bool rainbow READ rainbow WRITE setRainbow);
public:
explicit RadialClock(QWidget *parent = 0);
~RadialClock();
/************************************************************************
** Encapsulated Properties
** - blip -- Whether to precursor a tick of the clock with a slight back-tick.
** - seconds -- Whether to show the seconds counting down
** - minutes -- Whether to show the minutes counting down
** - hours -- Whether to show the hours counting down
** - weekDays -- Whether to show the days of the week counting down
** - monthDays -- Whether to show the days of the month counting down
** - yearDays -- Whether to show the days of the year counting down
** - months -- Whether to show the months of the year counting down
** - innerColor -- The color of the inner ring
** - outerColor -- The color of the outer ring
** Note: all in-between rings will be colored on a gradient between INNER and OUTER
** - rainbow -- An override to color the rings based on the colors of the rainbow
************************************************************************/
bool blip() const { return m_blip; }
void setBlip(bool b) { m_blip = b; }
bool seconds() const { return m_seconds; }
void setSeconds(bool s) { m_seconds = s; }
bool minutes() const { return m_minutes; }
void setMinutes(bool m) { m_minutes = m; }
bool hours() const { return m_hours; }
void setHours(bool h) { m_hours = h; }
bool weekDays() const { return m_weekDays; }
void setWeekDays(bool d) { m_weekDays = d; }
bool monthDays() const { return m_monthDays; }
void setMonthDays(bool d) { m_monthDays = d; }
bool yearDays() const { return m_yearDays; }
void setYearDays(bool d) { m_yearDays = d; }
bool months() const { return m_months; }
void setMonths(bool m) { m_months = m; }
QColor outerColor() const { return m_outer_color; }
void setOuterColor(const QColor &c) { m_outer_color = c;
m_colors.clear(); }
QColor innerColor() const { return m_inner_color; }
void setInnerColor(const QColor &c) { m_inner_color = c;
m_colors.clear(); }
bool rainbow() const { return m_rainbow; }
void setRainbow(bool r) { m_rainbow = r; }
QString describe() const;
/************************************************************************
** TimeCode - An enumerated type to differentiate the different rings
** of the clock face.
************************************************************************/
enum TimeCode {
SecondOfMinute = 0,
MinuteOfHour = 1,
HourOfDay = 2,
DayOfWeek = 3,
DayOfMonth = 4,
DayOfYear = 5,
MonthOfYear = 6,
InvalidTimeCode = 7
};
static const QString cTimeCodes[InvalidTimeCode];
static bool isDay(const TimeCode &tc);
static void related(const TimeCode &tc, std::vector<TimeCode> &family);
static TimeCode relatedTo(const TimeCode &tc);
int stages() const;
bool display(const TimeCode &tc) const;
static int value(const QDateTime &dtime, const TimeCode &tc);
static int limit(const QDateTime &dtime, const TimeCode &tc);
static int blipLimit(const QDateTime &dtime, const TimeCode &tc);
void blips(const QDateTime &dtime, std::map<TimeCode, bool> &blips) const;
/************************************************************************
** Color Processing.
************************************************************************/
static const QColor cBlack;
void processColors();
const QColor &getColor(TimeCode tc) const;
void getColors(const std::vector<QColor> &reference, int s, std::vector<QColor> &colors);
protected:
/************************************************************************
** Widget Callbacks
************************************************************************/
void paintEvent(QPaintEvent *);
void mousePressEvent(QMouseEvent *);
private:
typedef std::vector<std::pair<TimeCode, int> > angleVector;
/************************************************************************
** Internal Variables.
************************************************************************/
QTimer *m_timer;
bool m_blip;
bool m_seconds;
bool m_minutes;
bool m_hours;
bool m_weekDays;
bool m_monthDays;
bool m_yearDays;
bool m_months;
QColor m_outer_color;
QColor m_inner_color;
bool m_rainbow;
std::map<TimeCode, QColor> m_colors;
std::map<int, TimeCode> m_regions;
void addAngle(angleVector &angles, TimeCode tc, int value, int ref, bool blip = false);
void paintRing(QPainter &painter, const QColor &clr, int x, int y, int r, int t, int a);
void paintRings(QPainter &painter, int x, int y, int t, int s, int b, const angleVector &angles);
signals:
public slots:
};
#endif // RADIAL_CLOCK_H
| [
"pi@chickaletta.pawpatrol.home"
] | pi@chickaletta.pawpatrol.home |
3ab9de8b6aaa8ac440a4584f195ca4f5dc1db860 | dcdf0e29d02a6adafa3d2db9dc7cf443e65bf1c5 | /src/Linked_List.cpp | 126489552833baa838c382c6e82c011f782b628c | [] | no_license | hungthanh95/Linked_List_Cpp | 3bb0281ccc5eec87787bf45efc67f8a4dfce15ff | 94d397ee013a30ace3a1ceb080ed7b9374e8bf37 | refs/heads/main | 2023-02-15T09:36:47.238231 | 2021-01-09T13:54:35 | 2021-01-09T13:54:35 | 328,165,074 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 4,381 | cpp | /*
* Linked_List.cpp
*
* Created on: Jun 12, 2019
* Author: ThanhLH
*/
#include <iostream>
#include <fstream>
#include "Linked_List.hpp"
#include "iomanip"
using namespace std;
void Linked_List::add(Node * newNode) {
/*If head = null newNode is head */
if (head == nullptr) {
head = newNode;
return;
}
Node * temp = head;
while (temp->next != nullptr) {
temp = temp->next;
}
temp->next = newNode;
return;
}
void Linked_List::printList() {
Node * temp = head;
for(int i = 0 ; temp != nullptr; i++) {
cout<<"---------------Node "<<i<<"-----------------"<<endl;
temp->m_employee.printEmployee();
temp = temp->next;
}
}
Node *Linked_List::getTail(){
Node * temp = head;
while(temp != NULL && temp->next != NULL) {
temp = temp->next;
}
return temp;
}
void Linked_List::swap(Node * node1, Node * node2) {
Employee temp = node1->m_employee;
node1->m_employee = node2->m_employee;
node2->m_employee = temp;
}
void Linked_List::bubbleSort() {
int swapped;
Node * node1;
Node * node2 = nullptr;
/* Check for empty list */
if(head == nullptr)
return;
do
{
swapped = 0;
node1 = head;
while(node1->next != node2)
{
if(node1->m_employee.m_level > node1->next->m_employee.m_level)
{
swap(node1, node1->next);
swapped = 1;
}
node1 = node1->next;
}
node2 = node1;
} while (swapped);
}
void Linked_List::addAndSort(Node * newNode) {
add(newNode);
bubbleSort();
}
/* Given a reference (pointer to pointer) to the head of a list
and a key, deletes the first occurrence of key in linked list */
int Linked_List::deleteNode(string name)
{
// Store head node
struct Node* temp = head, *prev;
// If head node itself holds the key to be deleted
if (temp != NULL && temp->m_employee.m_name == name)
{
head = temp->next; // Changed head
free(temp); // free old head
return 1;
}
// Search for the key to be deleted, keep track of the
// previous node as we need to change 'prev->next'
while (temp != NULL && temp->m_employee.m_name != name)
{
prev = temp;
temp = temp->next;
}
// If key was not present in linked list
if (temp == NULL) return 0;
// Unlink the node from linked list
prev->next = temp->next;
free(temp); // Free memory
return 1;
}
void Linked_List::deleteNodes(string name) {
int flag =1;
while(flag) {
flag = deleteNode(name);
}
}
void Linked_List::printList(string name) {
Node * temp = head;
for(int i = 0 ; temp != nullptr; i++) {
if (temp->m_employee.m_name == name)
{
cout<<"---------------Node "<<i<<"-----------------"<<endl;
temp->m_employee.printEmployee();
}
temp = temp->next;
}
}
int Linked_List::countNode(void) {
Node * temp = head;
int count = 0;
while(temp != nullptr) {
count++;
temp = temp->next;
}
return count;
}
void Linked_List::import_Linked_List(string path)
{
// Open file
// ifstream ip("C:\\Users\\ThanhLH\\Desktop\\employees.csv");
ifstream ip(path);
if(!ip.is_open()) cout <<"ERROR: File open"<<'\n';
int idx = 0;
string level_str;
while(ip.good()) {
Node *newNode = new Node();
// Read the Data from the file
getline(ip, newNode->m_employee.m_name, ',');
getline(ip, newNode->m_employee.m_position, ',');
getline(ip, newNode->m_employee.m_dateOfBirth, ',');
getline(ip, level_str, '\n');
/* convert value from string to float */
newNode->m_employee.m_level = std::stof(level_str.c_str());
/* assign Node to Linked List*/
add(newNode);
idx++;
}
numOfNodes = idx;
}
void Linked_List::export_Linked_List(string path) {
//file pointer
fstream fs;
//open file
//fs.open("C:\\Users\\ThanhLH\\Desktop\\employees_export.csv",ios::out);
fs.open(path,ios::out);
cout << "Export data to file csv....." << endl;
// Write the data
Node * temp = head;
fs <<left<<setw(25)<<"Ten"<<setw(25)<<"Chuc vu"<<setw(25)<<"Ngay thang nam sinh"<<setw(25)<<"He so luong"<<endl;
for(int i = 0 ; temp != nullptr; i++) {
// Insert the data to file
fs <<left<<setw(25)<< temp->m_employee.m_name
<<setw(25)<< temp->m_employee.m_position
<<setw(25)<< temp->m_employee.m_dateOfBirth
<<setw(25)<< temp->m_employee.m_level << "\n";
temp = temp->next;
}
fs.close();
}
| [
"hungthanh95@gmail.com"
] | hungthanh95@gmail.com |
e3ac4c1ffc412457652351509d61952a1098271f | 65fc30f0eecea65bed6a640ade8fe751f26f9326 | /Lunaway_Code/Runaway/BoardManager.cpp | 7475cee7d38e5693f94df9d0d36475de4eaaea73 | [] | no_license | kmk013/Project_OpenGL_Lunaway | cf143e6063e0be9670c1cda4dba874ae2cb44e63 | a56189080c871d0dfbc5ddd696ccfd9c982d8d39 | refs/heads/master | 2020-04-07T13:48:24.536126 | 2018-11-20T16:50:56 | 2018-11-20T16:50:56 | 158,422,397 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,095 | cpp | #include "stdafx.h"
#include "BoardManager.h"
BoardManager::BoardManager() : phase(1)
{
currentLine = 0;
}
BoardManager::~BoardManager()
{
}
void BoardManager::Update()
{
if ((int)p->pos.z > (int)(pos.z + 16.0f)) {
pos.z += 16.0f;
for (int i = 0; i < 6; i++) {
if(!boards[i][currentLine]->useModel)
boards[i][currentLine]->useModel = true;
if (boards[i][currentLine]->isBreak)
boards[i][currentLine]->isBreak = false;
if (boards[i][currentLine]->myCol)
boards[i][currentLine]->myCol->Destroy();
boards[i][currentLine]->pos.z += 40.0f * 16.0f;
}
currentLine++;
if (currentLine >= 40)
currentLine = 0;
}
}
void BoardManager::PhaseChange(int phase)
{
if (phase == 1) {
for (int i = 0; i < 6; i++) {
for (int j = 0; j < 40; j++) {
boards[i][j]->myModel = model1;
}
}
}
if (phase == 2) {
for (int i = 0; i < 6; i++) {
for (int j = 0; j < 40; j++) {
boards[i][j]->myModel = model2;
}
}
}
if (phase == 3) {
for (int i = 0; i < 6; i++) {
for (int j = 0; j < 40; j++) {
boards[i][j]->myModel = model3;
}
}
}
}
| [
"kmk013@naver.com"
] | kmk013@naver.com |
2ad6a255d1846c8e4d839f3ab0676d69fbb189f2 | 936ff533e5a4a130f629fe596a377ab1122121f3 | /3RDPARTY/OpenTissue/OpenTissue/utility/gl/gl_draw_bone.h | 7d541b9aa1b833f94469425936a3f47bcff4d559 | [
"MIT"
] | permissive | misztal/GRIT | e9eb7671b215c3995a765581655d6a7c3096471f | 6850fec967c9de7c6c501f5067d021ef5288b88e | refs/heads/master | 2021-10-08T11:43:53.580211 | 2018-12-11T21:46:13 | 2018-12-11T21:46:13 | 105,385,278 | 5 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 7,682 | h | #ifndef OPENTISSUE_UTILITY_GL_GL_DRAW_BONE_H
#define OPENTISSUE_UTILITY_GL_GL_DRAW_BONE_H
//
// OpenTissue Template Library
// - A generic toolbox for physics-based modeling and simulation.
// Copyright (C) 2008 Department of Computer Science, University of Copenhagen.
//
// OTTL is licensed under zlib: http://opensource.org/licenses/zlib-license.php
//
#include <OpenTissue/configuration.h>
#include <OpenTissue/utility/gl/gl_util.h>
#include <OpenTissue/core/math/math_constants.h>
#include <cassert>
namespace OpenTissue
{
namespace gl
{
/**
* Draw Bone.
* Orientations and translations are simply drawn as arrows and coordinate frames.
*
* @param bone A reference to the bone that should be drawn.
*/
template<typename bone_type>
inline void DrawBone(bone_type const & bone)
{
glPushMatrix();
if(!bone.is_root())
{
Transform(bone.parent()->absolute());
}
DrawVector(bone.relative().T());
DrawFrame(bone.relative());
glPopMatrix();
}
/**
* Draw Bone.
* Mimics Maya's bone visualization. Translations are drawn
* as pyramids and orientaions as circular arcs on a sphere.
*
* Observe that the pyramid for the root bone is not drawn. This
* may cause one to think that a bone consist of a ``sphere-pyramid''
* pairing. This is however misleadning the true pairing that match
* the underlying bone transform is ``pyramid-sphere''.
*
*
* @param bone A reference to the bone that should be drawn.
*/
template<typename bone_type>
inline void DrawFancyBone(bone_type const & bone)
{
using std::sqrt;
using std::acos;
using std::cos;
using std::sin;
typedef typename bone_type::math_types math_types;
typedef typename math_types::real_type real_type;
typedef typename math_types::vector3_type vector3_type;
typedef typename math_types::quaternion_type quaternion_type;
typedef typename math_types::value_traits value_traits;
vector3_type const & T = bone.relative().T();
quaternion_type Q;
Q = bone.relative().Q();
real_type length = sqrt( dot(T,T) );
real_type radius = 0.075 * length;
glPushMatrix();
if(!bone.is_root())
{
Transform(bone.convert(bone.parent()->absolute()));
}
{
glPushMatrix();
Transform(T,Q);
int const N = 24;
real_type delta_theta = 2*value_traits::pi()/N;
real_type theta = 0;
ColorPicker(1,0,0,1);
glBegin(GL_LINE_LOOP);
for(int i=0;i<N;++i)
{
glNormal3f(1,0,0);
glVertex3f( 0, radius*cos(theta),radius*sin(theta));
theta += delta_theta;
}
glEnd();
theta = 0;
ColorPicker(0,1,0,1);
glBegin(GL_LINE_LOOP);
for(int i=0;i<N;++i)
{
glNormal3f(0,1,0);
glVertex3f( radius*cos(theta),0,radius*sin(theta));
theta += delta_theta;
}
glEnd();
theta = 0;
ColorPicker(0,0,1,1);
glBegin(GL_LINE_LOOP);
for(int i=0;i<N;++i)
{
glNormal3f(0,1,0);
glVertex3f( radius*cos(theta), radius*sin(theta), 0);
theta += delta_theta;
}
glEnd();
glPopMatrix();
}
{
if(!bone.is_root())
{
GLfloat angle = 0;
GLfloat x = 1;
GLfloat y = 0;
GLfloat z = 0;
if ( ( T(0) == 0 ) && ( T(1) == 0 ) )
{
if ( T(2) > 0 )
{
angle = 0;
}
else
{
angle = 180;
}
}
else
{
vector3_type v_unit;
vector3_type axis;
v_unit = unit( T );
axis = unit( cross( T, vector3_type(0,0,1 ) ) );
angle = acos( dot(v_unit , vector3_type(0,0,1 ) ) );
angle = -180.0 * angle / value_traits::pi();
x = axis(0);
y = axis(1);
z = axis(2);
}
glPushMatrix();
glRotatef( angle, x, y, z );
glRotatef( 45, 0, 0, 1 );
real_type base = radius / 2.0;
ColorPicker(0,0,.5,1);
glBegin(GL_LINE_LOOP);
glNormal3f(0,0,-1);
glVertex3f( -base, -base, radius);
glNormal3f(0,0,-1);
glVertex3f( -base, base, radius);
glNormal3f(0,0,-1);
glVertex3f( base, base, radius);
glNormal3f(0,0,-1);
glVertex3f( base, -base, radius);
glEnd();
glBegin(GL_LINE_LOOP);
glNormal3f(0,-1,0);
glVertex3f( -base, -base, radius);
glNormal3f(0,-1,0);
glVertex3f( base, -base, radius);
glNormal3f(0,-1,0);
glVertex3f( 0, 0, length-radius);
glEnd();
glBegin(GL_LINE_LOOP);
glNormal3f(1,0,0);
glVertex3f( base, -base, radius);
glNormal3f(1,0,0);
glVertex3f( base, base, radius);
glNormal3f(1,0,0);
glVertex3f( 0, 0, length-radius);
glEnd();
glBegin(GL_LINE_LOOP);
glNormal3f(0,1,0);
glVertex3f( base, base, radius);
glNormal3f(0,1,0);
glVertex3f( -base, base, radius);
glNormal3f(0,1,0);
glVertex3f( 0, 0, length-radius);
glEnd();
glBegin(GL_LINE_LOOP);
glNormal3f(-1,0,0);
glVertex3f( -base, base, radius);
glNormal3f(-1,0,0);
glVertex3f( -base, -base, radius);
glNormal3f(-1,0,0);
glVertex3f( 0,0, length-radius);
glEnd();
glPopMatrix();
}
}
glPopMatrix();
}
/**
* Draw Stick Bone.
* Orientations and translations are simply drawn as arrows and coordinate frames.
*
* @param bone A reference to the bone that should be drawn.
*/
template<typename bone_type>
inline void DrawStickBone(bone_type const & bone ,float red = 0.7,float green = 0.7,float blue = 0.7)
{
ColorPicker(red,green,blue,1.0);
glPushMatrix();
if(!bone.is_root())
{
Transform(bone.parent()->absolute());
}
DrawVector(bone.relative().T());
glPopMatrix();
}
/**
* Draw Fat Bone.
* the bone is drawn as a capsule the color can be chosen or left at the default light grey.
*
* @param bone A reference to the bone that should be drawn.
*/
template<typename bone_type,typename capsule_type >
inline void DrawFatBone(bone_type const & bone ,capsule_type capsule,float red = 0.7,float green = 0.7,float blue = 0.7,float thickness = 0.2)
{
typedef typename bone_type::math_types math_types;
typedef typename math_types::vector3_type V;
typedef typename math_types::real_type T;
typedef typename math_types::value_traits value_traits;
V const zero = V(value_traits::zero(), value_traits::zero(), value_traits::zero());
glPushMatrix();
if(!bone.is_root())
{
Transform(bone.parent()->absolute());
ColorPicker(red,green,blue,1.0);
//T thickness = 0.2;
if(length(bone.relative().T()) < 0.001)
thickness = 0.3;
capsule.set(zero, bone.relative().T(), thickness);
DrawCapsule(capsule);
//DrawVector(bone.relative().T());
}
glPopMatrix();
}
} // namespace gl
} // namespace OpenTissue
//OPENTISSUE_UTILITY_GL_GL_DRAW_BONE_H
#endif
| [
"marek.misztal@gmail.com"
] | marek.misztal@gmail.com |
cdf4d51e457fb56f62dd739160e521500a23d1fd | 3507431d0802a6fd7a4eb21f6a1566e9c33cd6d1 | /src/Logging/StreamLogger.h | 64e5017ba8abc2779756da19d3e406c281ae8800 | [
"MIT"
] | permissive | akaneoit/alloy | 7cf75f67226f142712ae4889522db2b52c8cc7f5 | 451d5455663a6b647631b6c87da62a2c3856f0a0 | refs/heads/master | 2021-05-13T21:59:22.454510 | 2018-01-06T01:25:14 | 2018-01-06T01:25:14 | 116,477,678 | 2 | 0 | null | 2018-01-06T11:32:03 | 2018-01-06T11:32:03 | null | UTF-8 | C++ | false | false | 622 | h | // Copyright (c) 2017-2018, The Alloy Developers.
// Distributed under the MIT/X11 software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#pragma once
#include <mutex>
#include "CommonLogger.h"
namespace Logging {
class StreamLogger : public CommonLogger {
public:
StreamLogger(Level level = DEBUGGING);
StreamLogger(std::ostream& stream, Level level = DEBUGGING);
void attachToStream(std::ostream& stream);
protected:
virtual void doLogString(const std::string& message) override;
protected:
std::ostream* stream;
private:
std::mutex mutex;
};
}
| [
"alloycashproject@gmail.com"
] | alloycashproject@gmail.com |
49fd169d768ce1cd9faf2a9f29d45ab474ea1303 | 6a40151ff39a43f15f8bc1037f665863c7ddf7b3 | /Game/include/Entity.h | edf5c912e14d2de496aa5419a80945f62534c64c | [] | no_license | larinius/2d_RPG_demo | 978ecfec142075edc1103acebc6564e4b8715b63 | 48d18ae4188ee6b0769b5276f8b7c8fecdf53656 | refs/heads/main | 2023-07-09T00:08:21.201234 | 2021-08-21T23:23:38 | 2021-08-21T23:23:38 | 398,671,160 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,883 | h | #pragma once
#include "precompiled.h"
#include "Components/Component.h"
#include "CommandQueue.h"
#include "ActorController.h"
namespace rpg {
class Entity : public sf::Transformable, public rpg::CommandListener {
public:
explicit Entity(int id, std::string name);
Entity(const Entity &) = delete;
Entity &operator=(const Entity &) = delete;
~Entity() {onDestroy();}
// Common API
void draw(sf::RenderWindow *window);
virtual void update(sf::Time dt);
virtual void handleEvent(const sf::Event &event);
// Event API
void setActive(bool);
// API for <Component>
void addComponent(int id) { components_.push_back(id); }
void removeComponent(int id);
std::vector<int> components() { return components_; }
std::vector<int> componentsByTag(int id);
// Component& getComponent(std::string name);
// Attachments API <Entity>
void addChild(int id) { attachments_.push_back(id); }
void removeChild(int id);
std::vector<int> attachments() { return attachments_; };
std::vector<int> get_attachments_by_tag(int id);
// Getters and setters
int id() const { return id_; }
std::string name() { return name_; }
bool isActive() const { return active_; }
void setSize(int size){size_ = size;}
int getSize(){return size_;}
void setTag(int id) { tags_.push_back(id); }
void removeTag(int id);
std::vector<int> getTags();
void onCommand(Command command) override;
protected:
void onActivate();
void onDestroy();
protected:
const int id_;
int ownerId_{0};
int parentId_{0};
const std::string name_;
std::vector<int> attachments_; //ids of attached Entities
std::vector<int> components_; //ids of attached Components
std::vector<int> tags_; //ids of asigned Tags
//Init me after spawn
bool active_;
Entity *owner_{nullptr};
sf::RenderWindow *window_;
int size_{static_cast<int>(GRID)};
};
}
| [
"dmitry.grunt@protonmail.com"
] | dmitry.grunt@protonmail.com |
5a16a547cf5b72c0792e58382569df701547c010 | 976a68b4b8441352b5f775a946335328db88783c | /src/parser/lexer/tokens/r_instr_tok.cpp | a021e3189a19bf8aba3b63dc3d31ed265f997605 | [
"MIT"
] | permissive | maddnias/EzMIPS | 08f4b75d0c2529e6817175c09492712f648ec52d | 01b1a96528d2293faebc363a4004f8c03cf82f42 | refs/heads/master | 2021-05-31T07:02:45.852827 | 2016-05-03T12:25:22 | 2016-05-03T12:25:22 | 57,319,750 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 250 | cpp | #include "r_instr_tok.h"
r_instr_tok::r_instr_tok(INSTRUCTION_CODE code, INSTRUCTION_TYPE type, unsigned int tok_row,
unsigned int tok_col):
instr_base_tok(code, INSTRUCTION_R, tok_row, tok_col)
{
}
r_instr_tok::~r_instr_tok(void)
{
}
| [
"imthetuffguy@gmail.com"
] | imthetuffguy@gmail.com |
a977991d8705ceeedcb376529313734e42e9ecaa | 6aab4199ab2cab0b15d9af390a251f37802366ab | /modules/desktop_capture/mouse_cursor_monitor_win.cc | bf0d8534e31137cfc14ccab2ac28fa5eecbc4bcf | [
"BSD-3-Clause",
"LicenseRef-scancode-unknown-license-reference",
"LicenseRef-scancode-google-patent-license-webrtc",
"LicenseRef-scancode-google-patent-license-webm"
] | permissive | adwpc/webrtc | f288a600332e5883b2ca44492e02bea81e45b4fa | a30eb44013b8472ea6a042d7ed2909eb7346f9a8 | refs/heads/master | 2021-05-24T13:18:44.227242 | 2021-02-01T14:54:12 | 2021-02-01T14:54:12 | 174,692,051 | 0 | 0 | MIT | 2019-03-09T12:32:13 | 2019-03-09T12:32:13 | null | UTF-8 | C++ | false | false | 7,006 | cc | /*
* Copyright (c) 2013 The WebRTC project authors. All Rights Reserved.
*
* Use of this source code is governed by a BSD-style license
* that can be found in the LICENSE file in the root of the source
* tree. An additional intellectual property rights grant can be found
* in the file PATENTS. All contributing project authors may
* be found in the AUTHORS file in the root of the source tree.
*/
#include <assert.h>
#include <string.h>
#include <memory>
#include "modules/desktop_capture/desktop_capture_types.h"
#include "modules/desktop_capture/desktop_frame.h"
#include "modules/desktop_capture/desktop_geometry.h"
#include "modules/desktop_capture/mouse_cursor.h"
#include "modules/desktop_capture/mouse_cursor_monitor.h"
#include "modules/desktop_capture/win/cursor.h"
#include "modules/desktop_capture/win/screen_capture_utils.h"
#include "modules/desktop_capture/win/window_capture_utils.h"
#include "rtc_base/logging.h"
namespace webrtc {
namespace {
bool IsSameCursorShape(const CURSORINFO& left, const CURSORINFO& right) {
// If the cursors are not showing, we do not care the hCursor handle.
return left.flags == right.flags &&
(left.flags != CURSOR_SHOWING || left.hCursor == right.hCursor);
}
} // namespace
class MouseCursorMonitorWin : public MouseCursorMonitor {
public:
explicit MouseCursorMonitorWin(HWND window);
explicit MouseCursorMonitorWin(ScreenId screen);
~MouseCursorMonitorWin() override;
void Init(Callback* callback, Mode mode) override;
void Capture() override;
private:
// Get the rect of the currently selected screen, relative to the primary
// display's top-left. If the screen is disabled or disconnected, or any error
// happens, an empty rect is returned.
DesktopRect GetScreenRect();
HWND window_;
ScreenId screen_;
Callback* callback_;
Mode mode_;
HDC desktop_dc_;
// The last CURSORINFO (converted to MouseCursor) we have sent to the client.
CURSORINFO last_cursor_;
};
MouseCursorMonitorWin::MouseCursorMonitorWin(HWND window)
: window_(window),
screen_(kInvalidScreenId),
callback_(NULL),
mode_(SHAPE_AND_POSITION),
desktop_dc_(NULL) {
memset(&last_cursor_, 0, sizeof(CURSORINFO));
}
MouseCursorMonitorWin::MouseCursorMonitorWin(ScreenId screen)
: window_(NULL),
screen_(screen),
callback_(NULL),
mode_(SHAPE_AND_POSITION),
desktop_dc_(NULL) {
assert(screen >= kFullDesktopScreenId);
memset(&last_cursor_, 0, sizeof(CURSORINFO));
}
MouseCursorMonitorWin::~MouseCursorMonitorWin() {
if (desktop_dc_)
ReleaseDC(NULL, desktop_dc_);
}
void MouseCursorMonitorWin::Init(Callback* callback, Mode mode) {
assert(!callback_);
assert(callback);
callback_ = callback;
mode_ = mode;
desktop_dc_ = GetDC(NULL);
}
void MouseCursorMonitorWin::Capture() {
assert(callback_);
CURSORINFO cursor_info;
cursor_info.cbSize = sizeof(CURSORINFO);
if (!GetCursorInfo(&cursor_info)) {
RTC_LOG_F(LS_ERROR) << "Unable to get cursor info. Error = "
<< GetLastError();
return;
}
if (!IsSameCursorShape(cursor_info, last_cursor_)) {
if (cursor_info.flags == CURSOR_SUPPRESSED) {
// The cursor is intentionally hidden now, send an empty bitmap.
last_cursor_ = cursor_info;
callback_->OnMouseCursor(new MouseCursor(
new BasicDesktopFrame(DesktopSize()), DesktopVector()));
} else {
// According to MSDN https://goo.gl/u6gyuC, HCURSOR instances returned by
// functions other than CreateCursor do not need to be actively destroyed.
// And CloseHandle function (https://goo.gl/ja5ycW) does not close a
// cursor, so assume a HCURSOR does not need to be closed.
if (cursor_info.flags == 0) {
// Host machine does not have a hardware mouse attached, we will send a
// default one instead.
// Note, Windows automatically caches cursor resource, so we do not need
// to cache the result of LoadCursor.
cursor_info.hCursor = LoadCursor(nullptr, IDC_ARROW);
}
std::unique_ptr<MouseCursor> cursor(
CreateMouseCursorFromHCursor(desktop_dc_, cursor_info.hCursor));
if (cursor) {
last_cursor_ = cursor_info;
callback_->OnMouseCursor(cursor.release());
}
}
}
if (mode_ != SHAPE_AND_POSITION)
return;
// CURSORINFO::ptScreenPos is in full desktop coordinate.
DesktopVector position(cursor_info.ptScreenPos.x, cursor_info.ptScreenPos.y);
bool inside = cursor_info.flags == CURSOR_SHOWING;
if (window_) {
DesktopRect original_rect;
DesktopRect cropped_rect;
if (!GetCroppedWindowRect(window_, /*avoid_cropping_border*/ false,
&cropped_rect, &original_rect)) {
position.set(0, 0);
inside = false;
} else {
if (inside) {
HWND windowUnderCursor = WindowFromPoint(cursor_info.ptScreenPos);
inside = windowUnderCursor
? (window_ == GetAncestor(windowUnderCursor, GA_ROOT))
: false;
}
position = position.subtract(cropped_rect.top_left());
}
} else {
assert(screen_ != kInvalidScreenId);
DesktopRect rect = GetScreenRect();
if (inside)
inside = rect.Contains(position);
position = position.subtract(rect.top_left());
}
callback_->OnMouseCursorPosition(position);
}
DesktopRect MouseCursorMonitorWin::GetScreenRect() {
assert(screen_ != kInvalidScreenId);
if (screen_ == kFullDesktopScreenId) {
return DesktopRect::MakeXYWH(GetSystemMetrics(SM_XVIRTUALSCREEN),
GetSystemMetrics(SM_YVIRTUALSCREEN),
GetSystemMetrics(SM_CXVIRTUALSCREEN),
GetSystemMetrics(SM_CYVIRTUALSCREEN));
}
DISPLAY_DEVICE device;
device.cb = sizeof(device);
BOOL result = EnumDisplayDevices(NULL, screen_, &device, 0);
if (!result)
return DesktopRect();
DEVMODE device_mode;
device_mode.dmSize = sizeof(device_mode);
device_mode.dmDriverExtra = 0;
result = EnumDisplaySettingsEx(device.DeviceName, ENUM_CURRENT_SETTINGS,
&device_mode, 0);
if (!result)
return DesktopRect();
return DesktopRect::MakeXYWH(
device_mode.dmPosition.x, device_mode.dmPosition.y,
device_mode.dmPelsWidth, device_mode.dmPelsHeight);
}
MouseCursorMonitor* MouseCursorMonitor::CreateForWindow(
const DesktopCaptureOptions& options,
WindowId window) {
return new MouseCursorMonitorWin(reinterpret_cast<HWND>(window));
}
MouseCursorMonitor* MouseCursorMonitor::CreateForScreen(
const DesktopCaptureOptions& options,
ScreenId screen) {
return new MouseCursorMonitorWin(screen);
}
std::unique_ptr<MouseCursorMonitor> MouseCursorMonitor::Create(
const DesktopCaptureOptions& options) {
return std::unique_ptr<MouseCursorMonitor>(
CreateForScreen(options, kFullDesktopScreenId));
}
} // namespace webrtc
| [
"adwpc@hotmail.com"
] | adwpc@hotmail.com |
0026da428a0b4eb7d2d66f9dd100cf646a8bcc99 | c3d5d7433ab1391cac0c2e24ff55f852198eca34 | /Starter/test/LinkedList_test.h | 33ec5e975364fdbc6811a7316b46c87742f041c2 | [
"Apache-2.0"
] | permissive | masterpiece2014/Starter | 6b65125c29fc3da0a00671b40ec2dedde4799b82 | 2f2ac47636b961b797df0101e3307c95c3b1bb5e | refs/heads/master | 2021-01-14T12:31:33.533204 | 2014-04-25T16:43:40 | 2014-04-25T16:43:40 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 14,846 | h | ///////////////////////////////////////////////////////////////////////////////
//// Copyright 2012 2013 CaiBowen
//// All rights reserved.
////
//// Author: Cai Bowen
//// contact/bug report/get new version
//// at
//// feedback2bowen@outlook.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 "CycList.h"
#include "CycList.h"
using namespace Starter;
//template<typename T>
////using = CycList<T, std::allocator<T>>;
//typedef typename template CycList<T> CycList<T>;
//
//
//typedef typename _Alloc::template rebind<_Tp>::other _Tp_alloc_type;
//
//
#include <cassert>
int test_LinkedList() {
double db[LOOP];
for (size_t i = 0; i != LOOP; i++) {
db[i] = rand();
}
CycList<double> ls;
for (size_t i = 0; i != LOOP; i++) {
ls.push_back(db[i]);
cout << db[i] << endl;
}
cout << "front and back " << ls.front() << " " << ls.back() << endl;
auto iiiter = ls.begin();
auto bter = iiiter;
--iiiter; // at end() pointless node
--iiiter; // at back() last node
cout << " begin " << *bter << " " << *iiiter << endl;
cout << " iiiter[3] " << iiiter[3] << endl;
// iter += 3;
// iter -= 3;
// while (iter != ls.end()) {
// cout << *iter << endl;
// iter++;
// }
ls.pop();
ls.pop_front();
ls.insert_at(4, 11111.1111);
ls.insert_at(5, 55555);
cout << "size " << ls.size() << endl;
for(const auto& item : ls) {
cout << item << endl;
}
return 0;
}
struct Friendy {
Friendy () : Friendy(0.0) {}
Friendy(double mkk): mk(mkk){
id = ++ ct;
// cout << id << "Morning!" << mk << " ";
}
void greet() const {
cout << id<<" " << mk << endl;
}
~Friendy() {
// cout << id<< " Dtor\n" ;
}
int fillerr[100];
double mk;
int id;
static int ct;
};
int Friendy::ct = 0;
struct FriendyAgain :public Friendy{
FriendyAgain(){
// cout << "Zhaoshanghao!" << endl;
}
FriendyAgain(double mkk) : Friendy(mkk){}
void greet() {
cout << "ChiFanMei!" << endl;
}
~FriendyAgain() {
// cout << "WanAn!" << endl;
}
int filler[100];
};
#include <limits>
int test1_LinkedList() {
CycList<Friendy> lss, laa;
// list<Friendy> lss, laa;
// vector<Friendy> lss, laa;
Friendy* ptr = (Friendy*)::operator new (LOOP * sizeof(Friendy));
for(size_t i = 0; i != LOOP; ++i) {
new((void*)(ptr + i))Friendy(rand());
lss.push_back(*(ptr + i));
}
// for (auto& i : lss) {
// i.greet();
// }
// laa.push_back(*lss.begin());
laa.push_back(*lss.begin());
laa.push_back(*lss.begin());
cout << "size and greet()" << laa.size() <<endl;
(++laa.begin())->greet();
laa = lss;
cout << "end" << endl;
::operator delete(ptr);
return 0;
}
int test2_LinkedList() {
CycList<Friendy> lss, lbb;
// list<Friendy> lss;
cout << "\n\n size" << lss.size()<< "" << "" <<endl;
lss.clear();
cout << "\n\n after cleaning size" << lss.size()<< "" << "" <<endl;
Friendy* ptr = (Friendy*)::operator new (LOOP * sizeof(Friendy));
for(size_t i = 0; i != LOOP; ++i) {
new((void*)(ptr + i))Friendy(rand());
lss.push_back(*(ptr + i));
}
lss.splice(lss.end(), {Friendy(1111111.2222222), Friendy(3333333.4444), Friendy(5555.66666)});
cout << "Greetings " << lss.size()<< endl;
for(auto& i : lss) {
i.greet();
}
// lss = lbb; // test if operator= will call corresponding Dtor
cout << lss.size() << " size ----- this is the end\n";
// cout << std::distance(lss.begin(), lss.end()) << endl;
// auto iter = lss.begin();
// auto iter6 = iter + 6;
// cout << "\nto be erased\n";
// iter->greet();
// iter6->greet();
// lss.pop();
// lss.popFront();
// lss.erase(iter,iter6);
// lss.insertAt(5, Friendy(111.333));
// lss.insert(iter6, Friendy(111.333));
// cout << "\n" << lss.size() << " done\n";
//for(auto& i : lss) {
// for(auto& i : lss) {
// i.greet();
// }
// auto xx = lss.begin();
// ++xx;
// ++xx;
// cout << "\n iters\n";
// xx->greet();
// lss.reverse();
// cout << "\n" << lss.size() << " reversing done\n\n";
// for(auto& i : lss) {
// i.greet();
// }
// cout << "\n iters \n";
// // while(xx != lss.end()) {
// xx->greet();
// ++xx;
// xx->greet();
// // }
// cout<< "\n\n\t TEST " << ""<<"";
//
::operator delete(ptr);
return 0;
}
template<typename T>
struct Pred
{ bool operator()(T a, T b) { return true; }
};
int test3_LinkedList() {
// CycList<Friendy> lss;
//
// std::vector<double> lss;
// lss.push_back(1.1);
// lss.push_back(2.2);
// lss.push_back(3.1);
// lss.push_back(6.2);
// lss.push_back(1.1);
// lss.push_back(2.2);
// lss.push_back(3.1);
// lss.push_back(6.2);
// CycList<double> laa;
// laa.transplant(laa.begin(), lss.begin(), lss.end());
// for(auto a : laa) {
// cout << a << endl;
// }
// cout << laa.end() - laa.begin() << " " << laa.size() << endl;
// cout << laa.begin() - laa.end() << " " << laa.size() << endl;
// CycList<double> ltt(lss);
// ltt.splice(ltt.begin(), lss);
// CycList<double> ltt{99999.9, 8888.88, 77777.77};
// std::list<double> lss = {1.1, 2.2, 3.3, 4.4, 5.5, 6.6};
// for(auto& i : ltt) {
// cout << i << endl;
// }
CycList<Friendy> laa{Friendy(1.111), Friendy(2.222), Friendy(3.333), Friendy(44.44)};
std::vector<Friendy> vec{Friendy(55.55), Friendy(66.66), Friendy(77.77)};
// test M_transplant
// std::vector<FriendyAgain> vec{FriendyAgain(44545), FriendyAgain(456), FriendyAgain(7845)};
laa.splice(laa.begin(), {Friendy(8888.66), Friendy(99.9999)});
laa.splice(laa.begin() + 2, vec.begin(), vec.end());
// laa.transplant(laa.begin() + 2, vecx.begin(), vecx.end());
//9 8 5 6 7 1 2 3 4
//8 9 5 6 7 1 2 3 4
// 8 9 5 6 7 1 2 3 4
cout << "\n size " << laa.size() << endl;
// CycList<Friendy> lbb(vecx.begin(), vecx.end());
for(auto& i : laa) {
i.greet();
}
auto vecx = laa.to_array();
cout << "\nvecx" << endl;
for(size_t i = 0; i != laa.size(); ++i) {
(vecx + i)->greet();
}
::operator delete(vecx);
cout << "\n laa" << endl;
for(const auto& i : laa) {
i.greet();
}
cout << "const \n";
laa.begin()->greet();
laa = {Friendy(8888.66), Friendy(99.9999)};
for(const auto& i : laa) {
i.greet();
}
// laa.cBegin()->greet();
/*
cout << "\n laa[2].greet();" << endl;
laa[2].greet();
// std::sort(laa.begin(), laa.end(), [](const Friendy& a, const Friendy& b)->bool{return a.mk > b.mk;});
cout << "compare " << std::boolalpha;
cout << (laa.begin() - laa.end() ) << " " << (laa.end() - laa.begin() ) <<endl;
cout<< (laa.begin() < laa.end() ) << endl;
cout << "\n after std::sort" << endl;
for(auto& i : laa) {
i.greet();
}
static_assert(std::is_same<CycList<Friendy>::Iter, decltype(laa.begin())>::value, "" );
int* pint= nullptr;
uint64_t* puint_64_t = nullptr;
cout << sizeof(puint_64_t) << endl;
cout << typeid(puint_64_t).name() << endl;
*/
//assert(1 != 1);
// cout << std::is_same<CycList<Friendy>::Iter, decltype(laa.begin())>::value << endl;
// cout << "\ntest sort" << endl;
// CycList<double> lbb{1.1, 2.2, 4.4, 99.9, 88.88, 55.12, 19.45, 66.15};
// for(auto& i : lbb) {
// cout << i << endl;
// }
// cout << "\ntest size" << lbb.size() << endl;
// auto yeah = [](double i)->bool{cout << i << " in lambda"<< endl; return true;};
//
// lbb.removeIf(yeah);
//
// std::function<bool(double, double)> dd = [](double i, double j)->bool{return true;};
// lbb.merge(lxx, dd);
// Pred<bool> ppp;
// lbb.merge(lxx, ppp);
// cout << lbb.end() - lbb.begin() << " size: " << lbb.size()<< endl;
// // std::sort(lbb.begin(), lbb.end());
// // cout << "\ntest sort" << endl;
// for(auto& i : lbb) {
// cout << i << endl;
// }
// for(int i = 0; i != LOOP; ++i) {
// lss.push_back(Friendy(rand()));
// }
// for(auto& i : lss) {
// i.greet();
// }
// lss.removeAt(6);
// cout << " removeAt 6" << lss.size() << endl;
// for(auto& i : lss) {
// i.greet();
// }
// cout << " At 6" << lss.size() << endl;
// lss[6].greet();
//typedef Friendy alis;
//Friendy ad;
//if(std::is_same<decltype(ad), alis>::value) { cout << "ok ok" << endl;}
return 0;
}
void test_4() {
CycList<Friendy> laa{Friendy(1.111), Friendy(2.222), Friendy(3.333), Friendy(44.44)};
std::vector<Friendy> vec{Friendy(55.55), Friendy(66.66), Friendy(77.77)};
laa.splice(laa.begin(), {Friendy(8888.66), Friendy(99.9999)});
laa.splice(laa.begin() + 2, vec.begin(), vec.end());
for(auto & i : laa) {
i.greet();
}
}
void test_5_LinkedList() {
// CycList<int> l1{5, 9, 0, 1, 3};
//// for(auto & i : l1) {
//// cout << i << " ";
//// }
//// cout << endl;
// CycList<int> l2{8, 7, 2, 16, 4};
//// // l1.merge(l2, [](int a, int b)->bool{return a > b;});
// cout << "\nfirst" << l1.size() << endl;
// l1.merge(l2);
//// for(auto & i : l1) {
//// cout << i << " ";
//// }
// // l1.splice(l1.begin(), {11, 11, 33, 33, 55, 55, 88, 88});
// // cout << "\nfirst" << l1.size() << endl;
// // for(auto & i : l1) {
// // cout << i << " ";
// // }
// // l1.unique();
// cout << "\nunique"<< l1.size() << endl;
// for(auto & i : l1) {
// cout << i << " ";
// }
// CycList<int> ls{0, 1, 35, 9, 44, 51, 28};
CycList<Friendy> ls;
CycList<Friendy> lt;
for(int i = 0; i != 16; ++i) {
ls.push_back(Friendy(rand()));
lt.push_back(Friendy(rand()));
}
cout << "\n\t original " << ls.size() << endl;
for(auto & i : ls) {
// cout << i << endl;
i.greet();
}
cout << "\n\t sorting " << ls.size() << endl;
ls.sort([](const Friendy& a, const Friendy& b)->bool{return a.mk < b.mk;});
lt = ls;
cout << "\n\t sorted " << lt.size() << endl;
for(auto & i : lt) {
// cout << i << endl;
i.greet();
}
}
void test_hash() {
CycList<Friendy> ls{Friendy(55.55), Friendy(66.66), Friendy(77.77), Friendy(8888.66), Friendy(99.9999)};
CycList<Friendy> lt(ls);
// CycList<double> ls;
// for(int i = 0; i != 256; ++i) {
// ls.push_back(Friendy(rand()));
// // ls.push_back(rand());
// }
// ls.sort();
// ls.sort([](const Friendy& a, const Friendy& b)->bool{return a.mk < b.mk;});
// for(auto i : ls) {
// // cout << i << " ";
// i.greet();
// }
cout << "\n\n hash " << ls.hash_code()<< endl;
cout << " hash " << lt.hash_code()<< endl;
}
inline uint32_t jenkins_rev_mix32(uint32_t key) {
key += (key << 12); // key *= (1 + (1 << 12))
key ^= (key >> 22);
key += (key << 4); // key *= (1 + (1 << 4))
key ^= (key >> 9);
key += (key << 10); // key *= (1 + (1 << 10))
key ^= (key >> 2);
// key *= (1 + (1 << 7)) * (1 + (1 << 12))
key += (key << 7);
key += (key << 12);
return key;
}
/*
* Inverse of jenkins_rev_mix32
*
* Note that jenkinks_rev_unmix32 is significantly slower than
* jenkins_rev_mix32.
*/
inline uint32_t
jenkins_rev_unmix32(uint32_t key) {
// These are the modular multiplicative inverses (in Z_2^32) of the
// multiplication factors in jenkins_rev_mix32, in reverse order. They were
// computed using the Extended Euclidean algorithm, see
// http://en.wikipedia.org/wiki/Modular_multiplicative_inverse
key *= 2364026753U;
// The inverse of a ^= (a >> n) is
// b = a
// for (int i = n; i < 32; i += n) {
// b ^= (a >> i);
// }
key ^=
(key >> 2) ^ (key >> 4) ^ (key >> 6) ^ (key >> 8) ^
(key >> 10) ^ (key >> 12) ^ (key >> 14) ^ (key >> 16) ^
(key >> 18) ^ (key >> 20) ^ (key >> 22) ^ (key >> 24) ^
(key >> 26) ^ (key >> 28) ^ (key >> 30);
key *= 3222273025U;
key ^= (key >> 9) ^ (key >> 18) ^ (key >> 27);
key *= 4042322161U;
key ^= (key >> 22);
key *= 16773121U;
return key;
}
const uint32_t FNV_32_HASH_START = 216613626UL;
const uint64_t FNV_64_HASH_START = 14695981039346656037ULL;
inline uint32_t fnv32(const char* s,
uint32_t hash = FNV_32_HASH_START) {
for (; *s; ++s) {
hash += (hash << 1) + (hash << 4) + (hash << 7) +
(hash << 8) + (hash << 24);
hash ^= *s;
}
return hash;
}
inline uint32_t fnv32_buf(const void* buf,
int n,
uint32_t hash = FNV_32_HASH_START) {
const char* char_buf = reinterpret_cast<const char*>(buf);
for (int i = 0; i < n; ++i) {
hash += (hash << 1) + (hash << 4) + (hash << 7) +
(hash << 8) + (hash << 24);
hash ^= char_buf[i];
}
return hash;
}
inline uint32_t fnv32(const std::string& str,
uint64_t hash = FNV_32_HASH_START) {
return fnv32_buf(str.data(), str.size(), hash);
}
int test_hash_funcs() {
uint32_t key = 20130126;
cout << jenkins_rev_mix32(jenkins_rev_unmix32(key)) << endl;
cout << jenkins_rev_unmix32(key) << endl;
cout << jenkins_rev_unmix32 ( jenkins_rev_mix32(key) ) << endl;
std::string str = "20130126xsdnfndaklhvopekwpqowdajsfqw";
std::hash<std::string> stringHasher;
cout << str << endl;
// assert( reinterpret_cast<size_t>(str.data()) == stringHasher(str) );
cout << fnv32(str) << endl;
cout << stringHasher(str) << endl;
return 0;
}
// Friendy* ptr = (Friendy*)::operator new (LOOP * sizeof(Friendy));
// Friendy* ptr1 = ptr + 1;
// new((void*)ptr1) Friendy();
// ptr1->~Friendy();
// ::operator delete(ptr);
// ptr = (Friendy*)::operator new (128 * sizeof(Friendy)); ::operator delete(ptr);
// ptr = (Friendy*)::operator new (128 * sizeof(Friendy)); ::operator delete(ptr);
// ptr = (Friendy*)::operator new (128 * sizeof(Friendy)); ::operator delete(ptr);
// ptr1->greet();
| [
"xcommando@outlook.com"
] | xcommando@outlook.com |
5c8c69ca203e954a6f7c33672f75bcb319fb30f5 | 66165dc042ba505d7137a5baf27aac1ec5ffa033 | /dia005/lst05-04.cxx | 1a26ef5d97503ccc504af608c507590533f348b7 | [] | no_license | ricardo-rios/programacionii | 92a3e7069a71eecb4eb5601455f8f8b55f1d3dc2 | 6af5857f5fd877a8188743db6e46b81f76010948 | refs/heads/master | 2020-12-30T09:27:24.746166 | 2018-08-27T20:42:31 | 2018-08-27T20:42:31 | 100,416,756 | 0 | 0 | null | 2017-08-15T20:41:55 | 2017-08-15T20:28:31 | null | UTF-8 | C++ | false | false | 484 | cxx | #include <iostream>
using namespace std;
void myFunc();
int main()
{
int x = 5;
cout << "\nIn main x is: " << x;
myFunc();
cout << "\nBack in main, x is: " << x << endl;
return 0;
}
void myFunc()
{
int x = 8;
cout << "\nIn myFunc, local x: " << x << endl;
{
cout << "\nIn block in myFunc, x is: " << x;
int x = 9;
cout << "\nVery local x: " << x;
}
cout << "\nOut of block, in myFunc, x: " << x << endl;
}
| [
"ricardo.rios.sv@gmail.com"
] | ricardo.rios.sv@gmail.com |
ec73ef2631a115c06be8b27d9501c88da6f2be30 | cc327a4880fa7e4c9f699b634e17ca5242c06bc0 | /doc/snippets/MagnumDebugTools-gl.cpp | 83d2160fe1e35a6ac78f5788ea633908187ead72 | [
"MIT"
] | permissive | xqms/magnum | 7cd3f2416dfbb6b305956173c5342bca8461a7cc | cef34e32db6f1fd6617870fd0f92492bbdafdf32 | refs/heads/master | 2021-06-19T13:19:18.729043 | 2019-02-07T08:02:51 | 2019-02-07T08:02:51 | 169,609,455 | 0 | 0 | NOASSERTION | 2019-02-07T17:09:32 | 2019-02-07T17:09:32 | null | UTF-8 | C++ | false | false | 4,667 | cpp | /*
This file is part of Magnum.
Copyright © 2010, 2011, 2012, 2013, 2014, 2015, 2016, 2017, 2018, 2019
Vladimír Vondruš <mosra@centrum.cz>
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 <Corrade/TestSuite/Tester.h>
#include "Magnum/Image.h"
#include "Magnum/PixelFormat.h"
#include "Magnum/DebugTools/ForceRenderer.h"
#include "Magnum/DebugTools/ResourceManager.h"
#include "Magnum/DebugTools/ObjectRenderer.h"
#include "Magnum/DebugTools/TextureImage.h"
#include "Magnum/GL/CubeMapTexture.h"
#include "Magnum/GL/Texture.h"
#include "Magnum/Math/Range.h"
#include "Magnum/SceneGraph/Drawable.h"
#include "Magnum/SceneGraph/Object.h"
#include "Magnum/SceneGraph/MatrixTransformation3D.h"
#ifndef MAGNUM_TARGET_GLES2
#include "Magnum/GL/BufferImage.h"
#endif
using namespace Magnum;
using namespace Magnum::Math::Literals;
int main() {
{
SceneGraph::Object<SceneGraph::MatrixTransformation3D>* object{};
/* [debug-tools-renderers] */
// Global instance of debug resource manager, drawable group for the renderers
DebugTools::ResourceManager manager;
SceneGraph::DrawableGroup3D debugDrawables;
// Create renderer options which will be referenced later by "my" resource key
DebugTools::ResourceManager::instance().set("my",
DebugTools::ObjectRendererOptions{}.setSize(0.3f));
// Create debug renderer for given object, use "my" options for it. The
// renderer is automatically added to the object features and also to
// specified drawable group.
new DebugTools::ObjectRenderer3D{*object, "my", &debugDrawables};
/* [debug-tools-renderers] */
}
{
SceneGraph::Object<SceneGraph::MatrixTransformation3D>* object{};
SceneGraph::DrawableGroup3D debugDrawables;
/* [ForceRenderer] */
DebugTools::ResourceManager::instance().set("my",
DebugTools::ForceRendererOptions{}
.setSize(5.0f)
.setColor(Color3::fromHsv(120.0_degf, 1.0f, 0.7f)));
// Create debug renderer for given object, use "my" options for it
Vector3 force;
new DebugTools::ForceRenderer3D(*object, {0.3f, 1.5f, -0.7f}, force, "my",
&debugDrawables);
/* [ForceRenderer] */
}
{
SceneGraph::Object<SceneGraph::MatrixTransformation3D>* object{};
SceneGraph::DrawableGroup3D debugDrawables;
/* [ObjectRenderer] */
// Create some options
DebugTools::ResourceManager::instance().set("my",
DebugTools::ObjectRendererOptions{}.setSize(0.3f));
// Create debug renderer for given object, use "my" options for it
new DebugTools::ObjectRenderer3D(*object, "my", &debugDrawables);
/* [ObjectRenderer] */
}
{
GL::Texture2D texture;
Range2Di rect;
/* [textureSubImage-2D-rvalue] */
Image2D image = DebugTools::textureSubImage(texture, 0, rect,
{PixelFormat::RGBA8Unorm});
/* [textureSubImage-2D-rvalue] */
}
#ifndef MAGNUM_TARGET_GLES2
{
GL::Texture2D texture;
Range2Di rect;
/* [textureSubImage-2D-rvalue-buffer] */
GL::BufferImage2D image = DebugTools::textureSubImage(texture, 0, rect,
{PixelFormat::RGBA8Unorm}, GL::BufferUsage::StaticRead);
/* [textureSubImage-2D-rvalue-buffer] */
}
#endif
{
GL::CubeMapTexture texture;
Range2Di rect;
/* [textureSubImage-cubemap-rvalue] */
Image2D image = DebugTools::textureSubImage(texture,
GL::CubeMapCoordinate::PositiveX, 0, rect, {PixelFormat::RGBA8Unorm});
/* [textureSubImage-cubemap-rvalue] */
}
#ifndef MAGNUM_TARGET_GLES2
{
GL::CubeMapTexture texture;
Range2Di rect;
/* [textureSubImage-cubemap-rvalue-buffer] */
GL::BufferImage2D image = DebugTools::textureSubImage(texture,
GL::CubeMapCoordinate::PositiveX, 0, rect, {PixelFormat::RGBA8Unorm},
GL::BufferUsage::StaticRead);
/* [textureSubImage-cubemap-rvalue-buffer] */
}
#endif
}
| [
"mosra@centrum.cz"
] | mosra@centrum.cz |
b20e00dcda3431c1f64d2346ab532131e4a6716a | c700154ce860a5d4981ea00890eae706047008ba | /codepatch/autopatch.h | ff3c615ab9131aa294cf02dc6aa3a7894d37353c | [] | no_license | KyleSanderson/left4downtown2 | 392529c8c843fa15a42117159a2e9cc84eac0c26 | 920592613c68c9b9fc4ed6313c2d9b7de2bd4121 | refs/heads/master | 2021-01-01T10:36:02.848425 | 2014-03-02T18:39:11 | 2014-03-02T18:39:11 | 33,843,330 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,438 | h | /**
* vim: set ts=4 :
* =============================================================================
* Left 4 Downtown SourceMod Extension
* Copyright (C) 2009 Igor "Downtown1" Smirnov.
* =============================================================================
*
* This program is free software; you can redistribute it and/or modify it under
* the terms of the GNU General Public License, version 3.0, as published by the
* Free Software Foundation.
*
* This program is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
* FOR A PARTICULAR PURPOSE. See the GNU General Public License for more
* details.
*
* You should have received a copy of the GNU General Public License along with
* this program. If not, see <http://www.gnu.org/licenses/>.
*
* As a special exception, AlliedModders LLC gives you permission to link the
* code of this program (as well as its derivative works) to "Half-Life 2," the
* "Source Engine," the "SourcePawn JIT," and any Game MODs that run on software
* by the Valve Corporation. You must obey the GNU General Public License in
* all respects for all other code used. Additionally, AlliedModders LLC grants
* this exception to all derivative works. AlliedModders LLC defines further
* exceptions, found in LICENSE.txt (as of this writing, version JULY-31-2007),
* or <http://www.sourcemod.net/license.php>.
*
* Version: $Id$
*/
#ifndef _INCLUDE_SOURCEMOD_AUTOPATCH_H_
#define _INCLUDE_SOURCEMOD_AUTOPATCH_H_
/*
use this class to automatically construct a codepatch and then have it call patch
*/
template <typename TPatchable>
class AutoPatch : public ICodePatch
{
public:
AutoPatch() : codePatch()
{
//L4D_DEBUG_LOG("AutoPatch constructor");
Patch(); //note: codePatch.Unpatch() is called automatically by its own destructor.. if it wants to
}
~AutoPatch()
{
L4D_DEBUG_LOG("AutoPatch destructor");
}
/*
patch the code memory
*/
void Patch()
{
codePatch.Patch();
}
/*
unpatch the code memory, restoring it to its original state
*/
void Unpatch()
{
codePatch.Unpatch();
}
/*
get the underlying ICodePatch if we need to access it directly for some reason
*/
TPatchable &GetCodePatch()
{
return codePatch;
}
private:
TPatchable codePatch;
};
#endif
| [
"dcx2gecko@gmail.com"
] | dcx2gecko@gmail.com |
4ba28716314541e468e9eed22cde6396dc4390ae | f5fb39010aec616f37ac24427f6af61dcdfd3756 | /Pokemon_Mystery_Dungeon/Team.h | 8d023af6487d61f4b808cc2ce313bb82e31d6734 | [] | no_license | JinKyong/Pokemon_Dungeon | 08df9ce02362a239525730aaa06aaa46c4bfbc0e | c595cdcb92f822b54e99e1a366f797712ad69475 | refs/heads/main | 2023-07-31T05:01:27.372424 | 2021-10-03T13:00:52 | 2021-10-03T13:00:52 | 384,614,340 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 148 | h | #pragma once
#include "Player.h"
class Team : public Player
{
public:
virtual HRESULT init(int pokemonNum, int level);
virtual int input();
};
| [
"sjk900700@gmail.com"
] | sjk900700@gmail.com |
22277d5fa3e2cb2d2b38d11aa72261441e4bd3bc | a9faa8b67818ec8dbb2a38b5041f4bc9ddaba430 | /ExRoadDesigner/Histogram.h | f8b3cb055c51bc1862ec2310d5b72009e09dbd88 | [] | no_license | QLwin/ExRoadDesigner | a219b33ff2da9dae13e739f99b758fb4e2445ad8 | cfabb8f3175babb1006f4ac9a5f26e96dac930aa | refs/heads/master | 2021-12-05T10:48:18.295989 | 2015-06-12T15:17:28 | 2015-06-12T15:17:28 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 255 | h | #pragma once
#include <QMap>
#include <vector>
class Histogram {
public:
int start;
int end;
int step;
std::vector<int> bins;
public:
Histogram(int start, int end, int step);
~Histogram() {}
void clear();
void add(int value);
int size();
};
| [
"gnishida@purdue.edu"
] | gnishida@purdue.edu |
74487c8a95b958e87573b7ba5d97881a09d4813f | b3a693cb2c15f95133876f74a640ec585b7a0f62 | /Hackerrank/ArushiUppal.cpp | a1006146c409369a63d102195d6bd5dcf7e98b1c | [] | no_license | singhsanket143/CppCompetitiveRepository | 1a7651553ef69fa407d85d789c7c342f9a4bd8e9 | 6e69599ff57e3c9dce4c4d35e60c744f8837c516 | refs/heads/master | 2022-06-23T01:42:38.811581 | 2022-06-16T13:17:15 | 2022-06-16T13:17:15 | 138,698,312 | 349 | 148 | null | 2021-03-06T18:46:58 | 2018-06-26T07:06:16 | C++ | UTF-8 | C++ | false | false | 1,277 | cpp | #include <bits/stdc++.h>
using namespace std;
int solution(int *arr, int n) {
int result = 0;
for(int j=0;j<n;j++) {
int jump = 0;
int min[10005] = {0};
int max[10005] = {0};
for(int i=0;i<n-1;i++) {
int max_el = INT_MAX;
int max_el_idx = i;
for(int j=i+1;j<n;j++) {
if(arr[j]>arr[i] and arr[i]<INT_MAX) {
max_el = arr[j];
max_el_idx = j;
}
}
if(max_el != INT_MAX) {
max[i]=max_el_idx;
}
}
for(int i=0;i<n-1;i++) {
int min_el = INT_MIN;
int min_el_idx = i;
for(int j=i+1;j<n;j++) {
if(arr[j]<arr[i] and arr[i]>min_el) {
min_el = arr[j];
min_el_idx = j;
}
}
if(min_el != INT_MIN) {
min[i]=min_el_idx;
}
}
int traversal = 0;
for(int i=0;i<n;i++){
traversal = i;
int jump=1;
while(traversal < n) {
if(jump%2==0) { // odd jump
int temp = traversal;
traversal = max[traversal];
if(traversal==temp) {
break;
}
} else {
int temp = traversal;
traversal = min[traversal];
if(traversal==temp) {
break;
}
}
if(traversal == n-1) {
result++;
}
}
}
}
return result;
}
int main(int argc, char const *argv[])
{
/* code */
int sol[5] = {10,13,12,14,15};
cout<<solution(sol, 5);
return 0;
}
| [
"singhsanket143@gmail.com"
] | singhsanket143@gmail.com |
39ee0eae9935106eaad933ef607a313627378803 | 70e98218d0c491bcb4e483eaad3d2ccc98882990 | /Tyle/FieldIterator.cpp | 3c02bb6102613881ae3371ff1f362d8b7fabaefe | [] | no_license | drachluch/karcassonne-z | 3aed973ba344202f07f32b5203a6c1ac5a5eee5b | db70c1b338185c543e2d938a241c3529e9c2d7ea | refs/heads/master | 2020-03-28T07:55:05.926096 | 2019-12-11T09:09:14 | 2019-12-11T09:09:14 | 147,933,159 | 0 | 0 | null | 2018-09-08T13:28:47 | 2018-09-08T12:53:56 | C++ | UTF-8 | C++ | false | false | 26 | cpp | #include "FieldIterator.h" | [
"simon.moulard@laposte.net"
] | simon.moulard@laposte.net |
2ab0a63edd4cbf682ad57e8c18ad396bb585e3c4 | 559207eb5beae4ba9fd638d19bd3009cbe3a6d11 | /src/net/instaweb/util/public/md5_hasher.h | efdb0212071e40238bd0c353c2f827293556971e | [
"Apache-2.0"
] | permissive | voku/mod-spdy | 2a8989668fe0c0f0de48c0b7ecd85b5b5b554ed1 | bcfb388cbc5415ee660c2b5dbcf61f6f43c2a5ca | refs/heads/master | 2023-04-05T09:50:46.847114 | 2015-03-19T17:58:09 | 2015-03-19T17:58:09 | 32,537,692 | 0 | 0 | NOASSERTION | 2023-04-04T01:40:41 | 2015-03-19T17:56:26 | C++ | UTF-8 | C++ | false | false | 1,451 | h | // Copyright 2010 Google 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.
//
// Authors: sligocki@google.com (Shawn Ligocki),
// lsong@google.com (Libo Song)
#ifndef NET_INSTAWEB_UTIL_PUBLIC_MD5_HASHER_H_
#define NET_INSTAWEB_UTIL_PUBLIC_MD5_HASHER_H_
#include "net/instaweb/util/public/basictypes.h"
#include "net/instaweb/util/public/hasher.h"
#include "net/instaweb/util/public/string.h"
#include "net/instaweb/util/public/string_util.h"
namespace net_instaweb {
class MD5Hasher : public Hasher {
public:
static const int kDefaultHashSize = 10;
MD5Hasher() : Hasher(kDefaultHashSize) {}
explicit MD5Hasher(int hash_size) : Hasher(hash_size) { }
virtual ~MD5Hasher();
virtual GoogleString RawHash(const StringPiece& content) const;
virtual int RawHashSizeInBytes() const;
private:
DISALLOW_COPY_AND_ASSIGN(MD5Hasher);
};
} // namespace net_instaweb
#endif // NET_INSTAWEB_UTIL_PUBLIC_MD5_HASHER_H_
| [
"ptrck@blck.io"
] | ptrck@blck.io |
7f63c1db518ea138a5d4afd4bc662f60f8f28806 | b3a86f9abffb5a6d581af1b40e08695c105e0681 | /src/fslview/src/fslview/vtkpropertydialog.h | 0f5bc299fa0a5b09f4dfcc80f7f567122124781d | [] | no_license | fithisux/FSL | 60e3e0f90430db343b3170f25a6e8b77811e6bdf | 7aa2932949129f5c61af912ea677d4dbda843895 | refs/heads/fsl-5.0.9 | 2020-12-30T16:16:32.812486 | 2016-01-29T18:52:06 | 2016-01-29T18:52:06 | 90,979,243 | 9 | 1 | null | 2017-05-11T12:56:41 | 2017-05-11T12:56:41 | null | UTF-8 | C++ | false | false | 778 | h | /* FSLView - 2D/3D Interactive Image Viewer
Authors: Rama Aravind Vorray
James Saunders
David Flitney
Mark Jenkinson
Stephen Smith
FMRIB Image Analysis Group
Copyright (C) 2002-2003 University of Oxford */
/* CCOPYRIGHT */
#if !defined(VTKPROPERTYDIALOG_H)
#define VTKPROPERTYDIALOG_H
#include "vtkpropertydialogbase.h"
class VTKProperties;
class VTKPropertyDialog: public VTKPropertyDialogBase
{
public:
VTKPropertyDialog(QWidget* parent, VTKProperties& props);
VTKPropertyDialog(const VTKPropertyDialog& options);
VTKProperties& operator=(const VTKProperties& rhs);
virtual ~VTKPropertyDialog() {}
VTKProperties& getProperties();
private:
VTKProperties& m_props;
private slots:
void selectColor();
void help();
};
#endif
| [
"methodscorehelp@umich.edu"
] | methodscorehelp@umich.edu |
cc9d363f797238aacf1ba3865e826af1b6324055 | fc30e5491e74cd090f860c0f461fb4079f6d1544 | /src/refractive_test.cpp | bbe423eaf4e36fdd64dd292e697454ec56db7a08 | [
"Unlicense"
] | permissive | PeterZhizhin/RayTracerCpp | f257adf3f3608d555accc036a59450be2be4865c | e3fcd9c19c84e51a7b16aec46406656e7c3878c7 | refs/heads/master | 2022-12-04T02:23:48.097754 | 2020-08-14T15:40:51 | 2020-08-14T15:40:51 | 274,872,550 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,955 | cpp | #define CATCH_CONFIG_MAIN // This tells the catch header to generate a main
#include <catch2/catch.hpp>
#include <cmath>
#include "hittable.h"
#include "random.h"
#include "ray.h"
#include "refractive.h"
#include "vec3.h"
using ray_tracer::geometry::Hittable;
using ray_tracer::material::RefractiveMaterial;
using ray_tracer::random::Random;
using ray_tracer::ray::Ray;
using ray_tracer::vector::Color3;
using ray_tracer::vector::Point3;
using ray_tracer::vector::Vec3;
namespace {
constexpr float deg2rad(float deg) {
return deg * static_cast<float>(M_PI / 180.0);
}
// For 45 degree angle, it reflected at least once with prob = (1 - 1e-14)
constexpr inline size_t number_of_runs = 300;
}
TEST_CASE("When material 2.0 ref index, hit at 45 degree angle, returns normalized vector", "[refractive]") {
Random rand;
RefractiveMaterial material(2.0, rand);
Ray in_ray{Point3{0.0f, 1.0f, 0.0f}, Vec3{1.0f, -1.0f, 0.0f}};
Hittable::HitRecord record{Point3{1.0f, 0.0f, 0.0f}, in_ray, 1.0f, Vec3{0.0f, 1.0f, 0.0f}};
// As it's randomly either refracts or reflects, we make
for (size_t i = 0; i != number_of_runs; ++i) {
auto scatter_info = material.scatter(in_ray, record);
REQUIRE(scatter_info.has_value());
auto scattered_ray_direction = scatter_info->ray.direction();
REQUIRE(scattered_ray_direction.length2() == Approx(1.0f));
}
}
TEST_CASE("When material 2.0 ref index, hit at 45 degree angle, refracts at asin(0.5 * sin(45deg))", "[refractive]") {
Random rand;
RefractiveMaterial material(2.0, rand);
Ray in_ray{Point3{0.0f, 1.0f, 0.0f}, Vec3{1.0f, -1.0f, 0.0f}};
Hittable::HitRecord record{Point3{1.0f, 0.0f, 0.0f}, in_ray, 1.0f, Vec3{0.0f, 1.0f, 0.0f}};
for (size_t i = 0; i != number_of_runs; ++i) {
auto scatter_info = material.scatter(in_ray, record);
REQUIRE(scatter_info.has_value());
auto scattered_ray_direction = scatter_info->ray.direction();
// Reflection will have the positive y coordinate.
if (scattered_ray_direction.y() > 0) {
// Discard reflection.
continue;
}
// To get sin, we should get the x coordinate of scattered_ray_direction
auto expected_sin_angle = 0.5f * std::sin(deg2rad(45.0f));
REQUIRE(scattered_ray_direction.x() == expected_sin_angle);
break;
// Test refracted ray only once.
}
}
TEST_CASE("When material 0.5 ref index, hit at 45 degree angle, it reflects", "[refractive]") {
Random rand;
RefractiveMaterial material(0.5, rand);
Ray in_ray{Point3{0.0f, 1.0f, 0.0f}, Vec3{1.0f, -1.0f, 0.0f}};
Hittable::HitRecord record{Point3{1.0f, 0.0f, 0.0f}, in_ray, 1.0f, Vec3{0.0f, 1.0f, 0.0f}};
for (size_t i = 0; i != number_of_runs; ++i) {
auto scatter_info = material.scatter(in_ray, record);
REQUIRE(scatter_info.has_value());
auto scattered_ray_direction = scatter_info->ray.direction();
REQUIRE(scattered_ray_direction == Vec3{1.0f, 1.0f, 0.0f}.unit());
}
}
TEST_CASE("When material 2.0 ref index, hit almost parallel to the surface, almost always refracts", "[refractive]") {
Random rand;
RefractiveMaterial material(2.0, rand);
Ray in_ray{Point3{0.0f, 1.0f, 0.0f}, Vec3{1.0f, -1e-6f, 0.0f}};
Hittable::HitRecord record{Point3{1.0f, 0.0f, 0.0f}, in_ray, 1.0f, Vec3{0.0f, 1.0f, 0.0f}};
size_t number_of_refractions = 0;
for (size_t i = 0; i != number_of_runs; ++i) {
auto scatter_info = material.scatter(in_ray, record);
REQUIRE(scatter_info.has_value());
auto scattered_ray_direction = scatter_info->ray.direction();
if (scattered_ray_direction.y() < 0) {
// refracted here
++number_of_refractions;
continue;
}
REQUIRE(scattered_ray_direction == Vec3{1.0f, 1e-6f, 0.0f}.unit());
}
REQUIRE(number_of_refractions < 3);
}
| [
"piter.zh@gmail.com"
] | piter.zh@gmail.com |
ed3b32c97a95dc31236ef527aa2617d7b7ff99fa | 9384a0dc5c52d3bf8a3307c1c5710acd103276f9 | /GeeksForGeeks/Graphs/NumberOfIslands.cpp | 205639666af5b968014832f1c97803c7048ad98e | [] | no_license | codeboy47/Competitive-Programming | c80deab0dc66b55de083a7faaab92f90577665fa | b1a8f3a5d3170f256d970e3103315e56fe4c3e45 | refs/heads/master | 2021-09-11T00:22:45.949158 | 2018-04-05T02:09:26 | 2018-04-05T02:09:26 | 76,561,517 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,732 | cpp | // Given a boolean 2D matrix, find the number of islands. A group of connected 1s forms an island.
#include <iostream>
using namespace std;
void dfsHelper(int x, int y, int arr[][1000], int r, int c){
arr[x][y] = 2;
// top-right
if(x != 0 && y != c-1 && arr[x-1][y+1] == 1){
dfsHelper(x-1,y+1,arr,r,c);
}
// right
if(y != c-1 && arr[x][y+1] == 1){
dfsHelper(x,y+1,arr,r,c);
}
// down-right
if(x != r-1 && y != c-1 && arr[x+1][y+1] == 1){
dfsHelper(x+1,y+1,arr,r,c);
}
//down
if(x != r-1 && arr[x+1][y] == 1){
dfsHelper(x+1,y,arr,r,c);
}
// down-left
if(x != r-1 && y != 0 && arr[x+1][y-1] == 1){
dfsHelper(x+1,y-1,arr,r,c);
}
//left
if(y != 0 && arr[x][y-1] == 1){
dfsHelper(x,y-1,arr,r,c);
}
// top-left
if(x != 0 && y != 0 && arr[x-1][y-1] == 1){
dfsHelper(x-1,y-1,arr,r,c);
}
// top
if(x != 0 && arr[x-1][y] == 1){
dfsHelper(x-1,y,arr,r,c);
}
}
int countIslands(int arr[][1000], int r, int c){
int count = 0;
for(int i = 0; i < r; i++){
for(int j = 0; j < c; j++){
if(arr[i][j] == 1){
dfsHelper(i,j,arr,r,c);
count++;
}
}
}
return count;
}
int main(){
int t;
int arr[1000][1000];
cin>>t;
while(t--){
int row,col;
cin>>row>>col;
for(int i = 0; i < row; i++){
for(int j = 0; j < col; j++){
cin>>arr[i][j];
}
}
cout<<countIslands(arr,row,col)<<endl;
}
return 0;
}
| [
"noreply@github.com"
] | codeboy47.noreply@github.com |
847cbeee04d421f289eb6fa7ac14eb3932aae25e | aa3d6a8a6e8e75d968786ed1900564baaad1bb62 | /AOJ/V1/117.cpp | b30cd6e55a64df793549a52d4af54dc5702ff6ae | [] | no_license | Halksel/Competition | 418b18981d4eb30572e6f24401f53968c5e9c354 | ce9ea74410a63ad2c4de23dee33698d23afb01b1 | refs/heads/master | 2021-01-23T21:46:52.925976 | 2019-08-25T13:07:44 | 2019-08-25T13:07:44 | 59,487,622 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,362 | cpp | #include <bits/stdc++.h>
using namespace std ;
#define pb(n) push_back(n)
#define fi first
#define se second
#define all(r) (r).begin(),(r).end()
#define gsort(st,en) sort((st),(en),greater<int>())
#define vmax(ary) *max_element(all(ary))
#define vmin(ary) *min_element(all(ary))
#define debug(x) cout<<#x<<": "<<x<<endl
#define fcout(n) cout<<fixed<<setprecision((n))
#define scout(n) cout<<setw(n)
#define vary(type,name,size,init) vector< type> name(size,init)
#define rep(i,n) for(int i = 0; i < (int)(n);++i)
#define REP(i,a,b) for(int i = (a);i < (int)(b);++i)
#define repi(it,array) for(auto it = array.begin(),end = array.end(); it != end;++it)
#define repa(n,array) for(auto &n :(array))
using ll = long long;
using vi = vector<int>;
using vl = vector<ll>;
using dict = map<string,int>;
using pii = pair<int,int> ;
constexpr int imax = ((1<<30)-1)*2+1 ;
constexpr int inf = 100000000;
constexpr double PI = acos(-1.0) ;
double eps = 1e-10 ;
const int dy[] = {-1,0,1,0};
const int dx[] = {0,-1,0,1};
inline bool value(int x,int y,int w,int h){
return (x >= 0 && x < w && y >= 0 && y < h);
}
template<typename T>
void Unique(vector<T> &v){
sort(all(v));
v.erase(unique(all(v)),v.end());
}
template<typename T>
T ston(string& str, T n){
istringstream sin(str) ;
T num ;
sin >> num ;
return num ;
}
void Ans(bool f){
if(f) cout << "YES"<<endl;
else cout << "NO"<<endl;
}
struct Edge{
int to;
long long cost;
};
struct NODE{
int pos;
long long cost;
};
bool operator < (const NODE &a,const NODE &b){
return a.cost > b.cost;
}
vector<Edge> g[100000],rg[100000];
int N;
const ll INF = 1e15;
vector<ll> dijkstra(vector<Edge> g[100000],int start){
priority_queue<NODE> Q;
Q.push({start,0});
vector<ll> res(N+1,INF);
while(Q.size()){
NODE q= Q.top();Q.pop();
if(res[q.pos] == INF){
res[q.pos] = q.cost;
}
else{
continue;
}
for(auto n : g[q.pos]){
Q.push({n.to,q.cost+n.cost});
}
}
return res;
}
int main(){
cin.tie(0);
ios::sync_with_stdio(false);
int m,a,b,d,e,x,x2,y,y2;
char c;
cin >>N>>m;
rep(i,m){
cin >> a>>c>>b>>c>>d>>c>>e;
g[a].push_back(Edge{b,d});
g[b].push_back(Edge{a,e});
}
cin >> x >>c>> x2>>c >> y>>c >> y2;
auto res = dijkstra(g,x);
auto res2 = dijkstra(g,x2);
cout << y - res[x2]-res2[x] -y2 << endl;
return 0;
}
| [
"whentheycry0708@gmail.com"
] | whentheycry0708@gmail.com |
5fcf9116d279416f6d883b71766db5291cde4d95 | 3edc478db837a27dbf8df7eded45df909dfe3cf9 | /URI online/1245.cpp | fdf48db2524ceb6a12dcf911f09e8a3ada69a0f1 | [] | no_license | ronistone/Maratonas | b60ebeb9e7e9298399652df88faa83389bd94542 | 8bd0bedd476645081a09b19152a007ca1497fe20 | refs/heads/master | 2021-01-12T10:06:04.016208 | 2018-10-19T02:40:54 | 2018-10-19T02:40:54 | 76,360,276 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 453 | cpp | #include <bits/stdc++.h>
using namespace std;
main(){
int n,i,j,aux;
while(cin >> n){
std::vector<int> v;
char pe[n];
int count =0;
for(i=0;i<n;i++){
cin >> aux >> pe[i];
v.push_back(aux);
}
for(i=0;i<n;i++){
for(j=0;j<n;j++){
if(j!=i && v[i]==v[j] && v[i]!=0 && v[j]!=0 && ((pe[i]=='D' && pe[j]=='E') || (pe[i]=='E' && pe[j]=='D'))){
v[i] = 0;
v[j] = 0;
count++;
}
}
}
cout << count << endl;
}
} | [
"ronistonejunior@gmail.com"
] | ronistonejunior@gmail.com |
90ae7c7f11c921beacc57401ec204a25fd29d815 | 1c7cb3154854a0d5f628c4285aa209affd8d2fc9 | /chaos-ns-3/ns-3.27/src/wifi/model/wifi-mac-trailer.h | 2f5dd8eb4fcc95117216416963054291a1591ada | [
"GPL-2.0-only",
"LicenseRef-scancode-free-unknown",
"MIT"
] | permissive | ErikNatanael/royal-chaos | fac8e5891044490cd2e61b7367f284d99951d0d1 | a8e763d3720cc3e158e98143cabce8106d8de2aa | refs/heads/master | 2022-07-16T12:21:31.494237 | 2020-05-12T12:50:08 | 2020-05-12T12:50:08 | 263,333,134 | 0 | 0 | MIT | 2020-05-12T12:42:08 | 2020-05-12T12:42:08 | null | UTF-8 | C++ | false | false | 1,579 | h | /* -*- Mode:C++; c-file-style:"gnu"; indent-tabs-mode:nil; -*- */
/*
* Copyright (c) 2006 INRIA
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License version 2 as
* published by the Free Software Foundation;
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*
* Author: Mathieu Lacage <mathieu.lacage@sophia.inria.fr>
*/
#ifndef WIFI_MAC_TRAILER_H
#define WIFI_MAC_TRAILER_H
#include "ns3/trailer.h"
namespace ns3 {
/**
* The length in octects of the IEEE 802.11 MAC FCS field
*/
static const uint16_t WIFI_MAC_FCS_LENGTH = 4;
/**
* \ingroup wifi
*
* Implements the IEEE 802.11 MAC trailer
*/
class WifiMacTrailer : public Trailer
{
public:
WifiMacTrailer ();
virtual ~WifiMacTrailer ();
/**
* \brief Get the type ID.
* \return the object TypeId
*/
static TypeId GetTypeId (void);
TypeId GetInstanceTypeId (void) const;
void Print (std::ostream &os) const;
uint32_t GetSerializedSize (void) const;
void Serialize (Buffer::Iterator start) const;
uint32_t Deserialize (Buffer::Iterator start);
};
} //namespace ns3
#endif /* WIFI_MAC_TRAILER_H */
| [
"zhanglong3030@qq.com"
] | zhanglong3030@qq.com |
21f045f81751fe6c3875df7ec4d94d1f05814a1f | 589145a5922edcca9299bb7218ef1e6e8bcc2698 | /BZOJ/BZOJ_3386.cpp | a5187812d9bd8bea735bc7419055949d3c54c3ea | [] | no_license | xyw5vplus1/Algorithm-Contest | 6ced07364c33bc8900ac5d92c67c6c72be5a3a84 | ea26d3460545c5c5c80a1dfc2c9693042b7b911d | refs/heads/master | 2023-03-30T13:29:12.756380 | 2021-03-27T15:05:19 | 2021-03-27T15:05:19 | 255,802,218 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,187 | cpp | /**************************************************************
Problem: 3386
User: xyw5vplus1
Language: C++
Result: Accepted
Time:88 ms
Memory:4812 kb
****************************************************************/
#include<cstdio>
#include<algorithm>
#include<cstring>
#define rep(i,a,b) for (int i=a;i<b;i++)
#define per(i,a,b) for (int i=a;i>b;i--)
using namespace std;
const int INF=0x3f3f3f3f;
const int maxn=1e3+10;
int dist[maxn];
bool vis[maxn];
int a[maxn][maxn];
int m,n,u,v,w;
void dijkstra(int root)
{
rep(i,1,n+1) dist[i]=INF;
memset(vis,false,sizeof(vis));
dist[root]=0;
rep(l,1,n+1) {
int mn=INF,k=-1;
rep(i,1,n+1)
if (!vis[i]&&mn>dist[i]) {
mn=dist[i]; k=i;
}
if (k==-1) break;
vis[k]=true;
rep(i,1,n+1)
if (dist[k]+a[k][i]<dist[i]) dist[i]=dist[k]+a[k][i];
}
}
int main()
{
scanf("%d%d",&m,&n);
rep(i,1,n+1)
rep(j,1,n+1)
if (i!=j) a[i][j]=INF;
rep(i,1,m+1) {
scanf("%d%d%d",&u,&v,&w);
a[u][v]=min(a[u][v],w);
a[v][u]=a[u][v];
}
dijkstra(n);
printf("%d\n",dist[1]);
return 0;
}
| [
"noreply@github.com"
] | xyw5vplus1.noreply@github.com |
da6902797bb2471933ab2e7e15d0676f1d4d20a9 | 7dc042a3f9068bc911c16f9173393660df704dab | /VC2008Samples/MFC/general/Scribble/stdafx.cpp | f0d958b1471f8d16fd62898be2bbfae4b061fa5d | [
"MIT"
] | permissive | pluciro/VCSamples | 5639f953bfbe0ef598af601cc78d5a18012e1792 | 8453972390580ef1bbc8c09ec7a14d3c9111518e | refs/heads/master | 2022-05-10T04:45:11.889276 | 2022-05-06T15:11:50 | 2022-05-06T15:11:50 | 280,199,366 | 0 | 0 | NOASSERTION | 2020-07-16T16:10:32 | 2020-07-16T16:10:32 | null | UTF-8 | C++ | false | false | 605 | cpp | // stdafx.cpp : source file that includes just the standard includes
// Scribble.pch will be the pre-compiled header
// stdafx.obj will contain the pre-compiled type information
//
// This is a part of the Microsoft Foundation Classes C++ library.
// Copyright (c) Microsoft Corporation. All rights reserved.
//
// This source code is only intended as a supplement to the
// Microsoft Foundation Classes Reference and related
// electronic documentation provided with the library.
// See these sources for detailed information regarding the
// Microsoft Foundation Classes product.
#include "stdafx.h"
| [
"ericmitt@corp.microsoft.com"
] | ericmitt@corp.microsoft.com |
c60c86cb6833616c58c773ede89f7c325f46d330 | 450f07ade94e73cee336bc05de7b6446b95f4e1e | /hsr_grab_operation/include/hsr_grab_operation.h | 5986edaff1f4f75e3f116676082a42e767b56d8d | [] | no_license | shencanjun/hirop_pickandplace | bf0eb6e0aca3da247ccf2bf9a3513f43ecf4684f | 97741d079c8cc175e6b9e5ff41a195d456e80b3a | refs/heads/master | 2020-06-04T12:53:19.345839 | 2019-06-15T07:06:31 | 2019-06-15T07:06:31 | 183,205,951 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,720 | h | #include "igrab_operation.h"
#include <ros/ros.h>
#include <serial/serial.h>
#include "hsr_gripper_driver/serial_open_srv.h"
#include "hsr_gripper_driver/close_srv.h"
#include "hsr_gripper_driver/open_srv.h"
#include "hsr_gripper_driver/stop_srv.h"
#include "hsr_gripper_driver/open_size_srv.h"
#include "hsr_gripper_driver/read_open_size_srv.h"
#include "../3rd/include/hpluginloader.h"
using namespace hirop_pickPlace;
class hsr_grab_operation:public IGrabOperation{
public:
/**
* @brief 构造函数
*/
hsr_grab_operation();
/**
* @brief 夹爪初始化
* @return
*/
int gripper_init();
/**
* @brief 夹爪打开
* @return 0,成功 -1,失败
*/
int gripper_open();
/**
* @brief 夹爪关闭
* @return
*/
int gripper_close();
/**
* @brief 初始化
* @param n 节点句柄
*/
void grab_init(ros::NodeHandle n);
private:
/**
* @brief 串口打开
* @param serialNo
* @param baudrate
* @return
*/
int serial_open(std::string serialNo,int baudrate);
/**
* @brief 夹爪打开
* @param speed
* @return
*/
int _gripper_open(int speed);
/**
* @brief 夹爪关闭
* @param speed
* @param force
* @return
*/
int _gripper_close(int speed, int force);
private:
//节点句柄
ros::NodeHandle n_gripper;
//串口打开服务客户端
ros::ServiceClient client_serialOpen;
//夹爪打开打开服务客户端
ros::ServiceClient client_gripperOpen;
//夹爪关闭打开服务客户端
ros::ServiceClient client_gripperClose;
};
H_DECLARE_PLUGIN(hirop_pickPlace::IGrabOperation)
| [
"1252773119@qq.com"
] | 1252773119@qq.com |
870fe70cb366434e9934fd2fc7fa2bf23a980203 | d827fb10cdea587dcaf4e8d7d4034324c6aaf96e | /DiscreteRemeshing/Examples/AnisotropicRemeshingQ.cxx | b018fa3b8fc4cbe7149444e2067638b4a1f6d36a | [
"LicenseRef-scancode-cecill-b-en",
"BSD-3-Clause",
"CECILL-B"
] | permissive | kayarre/ACVD | cf94635a94538dced381f83ddd59269375bbee8f | 83f7c05a7b3ccf0445708cea918b4b11325fb229 | refs/heads/master | 2022-01-01T06:20:50.424338 | 2021-11-12T12:54:26 | 2021-11-12T12:54:26 | 144,194,466 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 6,877 | cxx | /*=========================================================================
Program: Aproximated Centroidal Voronoi Diagrams
Module: ACVD.cxx
Language: C++
Date: 2003/11
Auteur: Sebastien Valette,
=========================================================================*/
// .NAME AnisotropicRemeshingQ
// .SECTION Description
#include <sstream>
#include <vtkPLYWriter.h>
#include <vtkSTLWriter.h>
#include <vtkCellData.h>
#include "vtkDiscreteRemeshing.h"
#include "vtkIsotropicMetricForClustering.h"
#include "vtkQuadricAnisotropicMetricForClustering.h"
#include "vtkQEMetricForClustering.h"
#include "vtkTrianglesProcessing.h"
#include "vtkVerticesProcessing.h"
//#include "vtkSubdivisionRemeshing.h"
/////////////////////////////////////////////////////////////////////////////////////////
//
// Adaptive coarsening of triangular meshes
// This program should be run with 3 arguments:
// run: "acvd file nvertices gradation [options]"
// arg1 is the name of the mesh file to read
// arg2 is the desired number of vertices (note: if the number of input
// arg3 is the gradation parameter (0 is uniform, higher values give more and more importance
// to regions with high curvature)
//
// Additionnal options :
// -d x : sets the graphics display (0 : no display. 1: display. 2 :iterative display)
// default value : 0
//
// -s x : sets the subsampling threshold (Higher values give better results but the input
// mesh will be subdivided more times)
// default value : 10
// -np x : sets the number of wanted processes (useful only with multi-processors machines)
//
//////////////////////////////////////////////////////////////////////////////////////////
int main( int argc, char *argv[] )
{
//******************************************************************************************
// Inside input parameters:
int Display=0; // defines whether there will be a graphic
// display (0: No, 1: yes)
int NumberOfSamples=200; // the number of desired vertices
double Gradation=0; // the gamma parameter for simplification
// (if gamma=0: uniform)
// other appropriates values range between 0 and 2
int SubsamplingThreshold=10;
char* OutputDirectory=0; // the output directory
//*******************************************************************************************
char filename[500];
vtkSurface *Mesh=vtkSurface::New();
typedef vtkDiscreteRemeshing<vtkIsotropicMetricForClustering> IsotropicRemeshing;
typedef vtkDiscreteRemeshing<vtkQEMetricForClustering> QEMRemeshing;
// typedef vtkDiscreteRemeshing<vtkL21MetricForClustering> L21Remeshing;
typedef vtkDiscreteRemeshing<vtkQuadricAnisotropicMetricForClustering> QuadricAnisotropicRemeshing;
vtkVerticesProcessing<QuadricAnisotropicRemeshing> *Remesh=
vtkVerticesProcessing<QuadricAnisotropicRemeshing>::New();
if(argc>1)
{
cout <<"load : "<<argv[1]<<endl;
strcpy(filename,argv[1]);
}
else
{
cout<<"Usage : AnisotropicRemeshingQ file nvertices gradation [options]"<<endl;
cout<<"nvertices is the desired number of vertices"<<endl;
cout<<"gradation defines the influence of local curvature (0=uniform meshing)"<<endl;
cout<<endl<<"Optionnal arguments : "<<endl;
cout << "-b 0/1 : sets mesh boundary fixing off/on (default : 0)" << endl;
cout<<"-d 0/1/2 : enables display (default : 0)"<<endl;
cout << "-l ratio : split the edges longer than ( averageLength * ratio )" << endl;
cout << "-b 0/1 : sets mesh boundary fixing off/on (default : 0)" << endl;
cout << "-q 1/2/3 : qets number of eigenvalues used for quadric-based vertex relocation to 0/1/2 (default : 3)"<< endl;
return (0);
}
Mesh->CreateFromFile(filename);
Mesh->GetCellData()->Initialize();
Mesh->GetPointData()->Initialize();
Mesh->DisplayMeshProperties();
if (0)
{
vtkPLYWriter *plyWriter=vtkPLYWriter::New();
plyWriter->SetInputData(Mesh);
plyWriter->SetFileName("input.ply");
plyWriter->Write();
plyWriter->Delete();
}
// get mandatory arguments
if(argc>2)
{
NumberOfSamples=atoi(argv[2]);
}
else
{
NumberOfSamples=3000;
cout<<"Number of vertices ? ";
cin>>NumberOfSamples;
}
if(argc>3)
{
Gradation=atof(argv[3]);
}
else
{
cout<<"Gradation ? ";
cin>>Gradation;
}
// Parse optionnal arguments
int ArgumentsIndex=4;
cout<<argc<<" Arguments"<<endl;
while (ArgumentsIndex<argc)
{
if (strcmp(argv[ArgumentsIndex],"-s")==0)
{
SubsamplingThreshold=atoi(argv[ArgumentsIndex+1]);
cout<<"Subsampling Threshold="<<SubsamplingThreshold<<endl;
}
if (strcmp(argv[ArgumentsIndex],"-d")==0)
{
Display=atoi(argv[ArgumentsIndex+1]);
cout<<"Display="<<Display<<endl;
}
#ifdef DOmultithread
if (strcmp(argv[ArgumentsIndex],"-np")==0)
{
int NumberOfThreads=atoi(argv[ArgumentsIndex+1]);
cout<<"Number of threads="<<NumberOfThreads<<endl;
Remesh->SetNumberOfThreads(NumberOfThreads);
}
#endif
if (strcmp(argv[ArgumentsIndex],"-o")==0)
{
OutputDirectory=argv[ArgumentsIndex+1];
cout<<"OutputDirectory: "<<OutputDirectory<<endl;
}
if (strcmp(argv[ArgumentsIndex],"-l")==0)
{
Mesh->SplitLongEdges(atof(argv[ArgumentsIndex+1]));
cout<<"Splitting edges longer than "
<<atof(argv[ArgumentsIndex+1])<<" times the average edge length"<<endl;
}
if (strcmp(argv[ArgumentsIndex],"-q")==0)
{
cout<<"Setting number of eigenvalues for quadrics to "<<atoi(argv[ArgumentsIndex+1])<<endl;
Remesh->GetMetric()->SetQuadricsOptimizationLevel(atoi(argv[ArgumentsIndex+1]));
}
if (strcmp(argv[ArgumentsIndex], "-b") == 0) {
cout << "Setting boundary fixing to : " << argv[ArgumentsIndex+1] << endl;
Remesh->SetBoundaryFixing(atoi(argv[ArgumentsIndex+1]));
}
ArgumentsIndex+=2;
}
RenderWindow *Window;
if (Display!=0)
{
Window=RenderWindow::New();
vtkPolyData *Visu=vtkPolyData::New();
Visu->ShallowCopy(Mesh);
Window->SetInputData(Visu);
Remesh->SetAnchorRenderWindow(Window);
Window->Render();
Window->SetWindowName(filename);
Window->GetCamera()->Zoom(1.6);
Window->Interact();
}
Remesh->SetInput(Mesh);
Remesh->SetNumberOfClusters(NumberOfSamples);
Remesh->SetConsoleOutput(2);
Remesh->SetSubsamplingThreshold(SubsamplingThreshold);
Remesh->GetMetric()->SetGradation(Gradation);
// Remesh->SetInitialSamplingType(0);
// Remesh->SetDisplayCharacteristicsWindowOn();
// Remesh->SetAlgorithmType(1);
Remesh->SetDisplay(Display);
Remesh->Remesh();
// save the output mesh to .ply format
char REALFILE[500];
if (OutputDirectory)
{
strcpy (REALFILE,OutputDirectory);
strcat (REALFILE,"Remeshing.ply");
cout<<"OutputDirectory: "<<OutputDirectory<<endl;
}
else
strcpy(REALFILE,"Remeshing.ply");
vtkPLYWriter *plyWriter=vtkPLYWriter::New();
plyWriter->SetInputData(Remesh->GetOutput());
plyWriter->SetFileName(REALFILE);
plyWriter->Write();
plyWriter->Delete();
}
| [
"sebastien.valette@creatis.insa-lyon.fr"
] | sebastien.valette@creatis.insa-lyon.fr |
020f0dd501a89b0023ef96c05e216cdb041f9a07 | dd2ad17eacd1e72fd9a351de6b4c95391aca8044 | /deps/openvdb-6.2.0/openvdb/points/AttributeGroup.cc | 68d2858c08bc51d044304a402ba6cf2e91edb160 | [
"Apache-2.0",
"LicenseRef-scancode-unknown-license-reference",
"MPL-1.0",
"MPL-2.0"
] | permissive | drakh/LuxCore | 88aea14db0560ba4744ee6bf6e448f6d18c7582e | 54c26383b93e18506c71fca85f08f8ee8ea11d3c | refs/heads/master | 2021-04-01T22:52:18.732333 | 2020-04-09T12:50:05 | 2020-04-09T12:50:05 | 248,220,647 | 0 | 0 | Apache-2.0 | 2020-03-18T12:05:29 | 2020-03-18T12:05:28 | null | UTF-8 | C++ | false | false | 4,698 | cc | ///////////////////////////////////////////////////////////////////////////
//
// Copyright (c) 2012-2017 DreamWorks Animation LLC
//
// All rights reserved. This software is distributed under the
// Mozilla Public License 2.0 ( http://www.mozilla.org/MPL/2.0/ )
//
// Redistributions of source code must retain the above copyright
// and license notice and the following restrictions and disclaimer.
//
// * Neither the name of DreamWorks Animation 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 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.
// IN NO EVENT SHALL THE COPYRIGHT HOLDERS' AND CONTRIBUTORS' AGGREGATE
// LIABILITY FOR ALL CLAIMS REGARDLESS OF THEIR BASIS EXCEED US$250.00.
//
///////////////////////////////////////////////////////////////////////////
/// @file points/AttributeGroup.cc
#include "AttributeGroup.h"
namespace openvdb {
OPENVDB_USE_VERSION_NAMESPACE
namespace OPENVDB_VERSION_NAME {
namespace points {
////////////////////////////////////////
// GroupHandle implementation
GroupHandle::GroupHandle(const GroupAttributeArray& array, const GroupType& offset)
: mArray(array)
, mBitMask(static_cast<GroupType>(1 << offset))
{
assert(isGroup(mArray));
// load data if delay-loaded
mArray.loadData();
// if array is compressed and preserve compression is true, copy and decompress
// into a local copy that is destroyed with handle to maintain thread-safety
if (mArray.isCompressed()) {
const_cast<GroupAttributeArray&>(mArray).decompress();
}
}
GroupHandle::GroupHandle(const GroupAttributeArray& array, const GroupType& bitMask,
BitMask)
: mArray(array)
, mBitMask(bitMask)
{
assert(isGroup(mArray));
// load data if delay-loaded
mArray.loadData();
// if array is compressed and preserve compression is true, copy and decompress
// into a local copy that is destroyed with handle to maintain thread-safety
if (mArray.isCompressed()) {
const_cast<GroupAttributeArray&>(mArray).decompress();
}
}
bool GroupHandle::get(Index n) const
{
return (mArray.get(n) & mBitMask) == mBitMask;
}
bool GroupHandle::getUnsafe(Index n) const
{
return (mArray.getUnsafe(n) & mBitMask) == mBitMask;
}
////////////////////////////////////////
// GroupWriteHandle implementation
GroupWriteHandle::GroupWriteHandle(GroupAttributeArray& array, const GroupType& offset)
: GroupHandle(array, offset)
{
assert(isGroup(mArray));
}
void GroupWriteHandle::set(Index n, bool on)
{
const GroupType& value = mArray.get(n);
GroupAttributeArray& array(const_cast<GroupAttributeArray&>(mArray));
if (on) array.set(n, value | mBitMask);
else array.set(n, value & ~mBitMask);
}
bool GroupWriteHandle::collapse(bool on)
{
using ValueT = GroupAttributeArray::ValueType;
GroupAttributeArray& array(const_cast<GroupAttributeArray&>(mArray));
array.compact();
if (this->isUniform()) {
if (on) array.collapse(static_cast<ValueT>(array.get(0) | mBitMask));
else array.collapse(static_cast<ValueT>(array.get(0) & ~mBitMask));
return true;
}
for (Index i = 0; i < array.size(); i++) {
if (on) array.set(i, static_cast<ValueT>(array.get(i) | mBitMask));
else array.set(i, static_cast<ValueT>(array.get(i) & ~mBitMask));
}
return false;
}
bool GroupWriteHandle::compact()
{
GroupAttributeArray& array(const_cast<GroupAttributeArray&>(mArray));
return array.compact();
}
////////////////////////////////////////
} // namespace points
} // namespace OPENVDB_VERSION_NAME
} // namespace openvdb
// Copyright (c) 2012-2017 DreamWorks Animation LLC
// All rights reserved. This software is distributed under the
// Mozilla Public License 2.0 ( http://www.mozilla.org/MPL/2.0/ )
| [
"neo2068@web.de"
] | neo2068@web.de |
0a2144a4b5185fc74282c45fdd3654346b991844 | 99e44f844d78de330391f2b17bbf2e293bf24b1b | /pytorch/caffe2/operators/dataset_ops.cc | 78fe0032da04247742ec26870cb0728f480375a9 | [
"MIT",
"BSD-3-Clause",
"LicenseRef-scancode-generic-cla",
"Apache-2.0",
"BSD-2-Clause"
] | permissive | raghavnauhria/whatmt | be10d57bcd6134dd5714d0c4058abd56a1b35a13 | c20483a437c82936cb0fb8080925e37b9c4bba87 | refs/heads/master | 2022-12-04T05:39:24.601698 | 2019-07-22T09:43:30 | 2019-07-22T09:43:30 | 193,026,689 | 0 | 1 | MIT | 2022-11-28T17:50:19 | 2019-06-21T03:48:20 | C++ | UTF-8 | C++ | false | false | 50,195 | cc | #include "caffe2/operators/dataset_ops.h"
#include <memory>
#include <mutex>
#include <string>
#include <vector>
#include "caffe2/core/blob_serialization.h"
#include "caffe2/core/operator.h"
#include "caffe2/core/tensor.h"
#include "caffe2/utils/string_utils.h"
namespace caffe2 {
CAFFE_KNOWN_TYPE(std::unique_ptr<dataset_ops::TreeCursor>);
CAFFE_KNOWN_TYPE(dataset_ops::TensorVectorPtr);
CAFFE_KNOWN_TYPE(dataset_ops::SharedTensorVectorPtr);
namespace dataset_ops {
namespace {
const char kDatasetFieldSeparator = ':';
const char* kDatasetLengthField = "lengths";
// how much percent to grow the dataset when needed
const int kDatasetGrowthPct = 40;
} // namespace
TreeIterator::TreeIterator(const std::vector<std::string>& fields) {
// populate field vector and split field names
fields_.resize(fields.size());
std::vector<std::vector<std::string>> nameParts(fields_.size());
for (size_t i = 0; i < fields.size(); ++i) {
auto& field = fields_.at(i);
field.name = fields[i];
field.id = i;
field.lengthFieldId = -1;
nameParts.at(i) = split(kDatasetFieldSeparator, field.name);
}
// populate lengthFields
for (const auto& field : fields_) {
const auto& parts = nameParts.at(field.id);
if (!parts.empty() && parts.back() == kDatasetLengthField) {
lengthFieldIds_.push_back(field.id);
}
}
// find length-field with maximum prefix matching for each field
for (auto& field : fields_) {
// by default, we are matching against the root domain
size_t maxMatchLevel = 1;
int maxMatchLengthFieldId = -1;
for (int j = 0; j < numLengthFields(); ++j) {
const auto& lenField = lengthField(j);
// a length field can't have itself as its length field
if (field.id == lenField.id) {
continue;
}
auto lf = nameParts.at(lenField.id);
auto lfEnd = lf.end() - 1;
// check whether this lengthField is a prefix for this field name
if (std::mismatch(lf.begin(), lfEnd, nameParts.at(field.id).begin())
.first != lfEnd) {
continue;
}
if (lf.size() > maxMatchLevel) {
maxMatchLevel = lf.size();
maxMatchLengthFieldId = j;
}
}
field.lengthFieldId = maxMatchLengthFieldId;
}
// check that fields are topologically sorted
// (no length field depends on a length defined afterwards)
for (const auto& field : fields_) {
const auto* lengthField = lengthFieldFor(field);
CAFFE_ENFORCE(
(lengthField == nullptr) || (lengthField->id < field.id),
"Error: Field ",
field.id,
" (",
field.name,
") ",
"depends on a field defined afterwards: ",
lengthField->id,
" (",
lengthField->name,
").");
}
}
void TreeIterator::advance(
const std::vector<const TLength*>& lengths,
std::vector<TOffset>& offsets,
std::vector<TOffset>& sizes,
std::vector<TOffset>& limits,
TOffset num) {
std::vector<TOffset> newOffsets;
CAFFE_ENFORCE_EQ(lengths.size(), numLengthFields());
CAFFE_ENFORCE_EQ(offsets.size(), numOffsetFields());
sizes.resize(offsets.size());
newOffsets.resize(offsets.size());
// first index, top level
{
auto limit = limits[0];
auto offset = offsets[0];
CAFFE_ENFORCE(limit >= offset, "Tried to advance past end of cursor.");
TOffset total = std::min(limit - offset, num);
sizes[0] = total;
newOffsets[0] = offset + total;
}
// child indices
for (int j = 1; j < numOffsetFields(); ++j) {
TOffset total = 0;
int parentOffsetId = offsetFieldIdFor(lengthField(j - 1));
const TLength* length = lengths[j - 1] + offsets[parentOffsetId];
for (int k = 0; k < sizes[parentOffsetId]; ++k) {
total += *(length++);
}
auto offset = offsets[j];
CAFFE_ENFORCE(
offset + total <= limits[j],
"Inconsistent field length: ",
"tried to advance past the end of field ",
j);
sizes[j] = total;
newOffsets[j] = offset + total;
}
offsets = newOffsets;
}
TreeWalker::TreeWalker(const vector<const Blob*>& inputs, TreeCursor& cursor)
: inputs_(inputs), cursor_(cursor), sizes_(cursor.it.numOffsetFields()) {
CAFFE_ENFORCE_EQ(inputs.size(), cursor.it.fields().size());
if (cursor.offsets.empty()) {
cursor.offsets.assign(cursor.it.numOffsetFields(), 0);
}
for (int fieldId = 0; fieldId < cursor_.it.fields().size(); ++fieldId) {
fields_.emplace_back(*this, fieldId);
}
gatherLengthData();
gatherSizeLimits();
// The invariant we hold is that we are always one step ahead
advance();
}
void TreeWalker::advance() {
prevOffsets_ = cursor_.offsets;
cursor_.it.advance(lengths_, cursor_.offsets, sizes_, limits_, 1);
}
std::vector<int64_t> TreeWalker::fieldDim(int fieldId) const {
auto tensorDim = input(fieldId).sizes().vec();
tensorDim[0] = sizes_[lengthIdx(fieldId)];
return tensorDim;
}
void* TreeWalker::fieldPtr(int fieldId) const {
auto& in = input(fieldId);
return (char*)in.raw_data() +
offset(fieldId) * in.size_from_dim(1) * in.dtype().itemsize();
}
void TreeWalker::gatherLengthData() {
static const TLength lenZero = 0;
lengths_.resize(cursor_.it.numLengthFields());
for (int i = 0; i < lengths_.size(); ++i) {
auto& in = input(cursor_.it.lengthField(i).id);
if (in.numel() > 0) {
lengths_[i] = in.data<int>();
} else {
lengths_[i] = &lenZero;
}
}
}
void TreeWalker::gatherSizeLimits() {
limits_.assign(sizes_.size(), std::numeric_limits<TOffset>::max());
for (auto fieldId = 0; fieldId < cursor_.it.fields().size(); ++fieldId) {
auto lengthFieldIdx = lengthIdx(fieldId);
limits_[lengthFieldIdx] =
std::min(limits_[lengthFieldIdx], (TOffset)input(fieldId).sizes()[0]);
}
}
namespace {
class CreateTreeCursorOp : public Operator<CPUContext> {
public:
template <class... Args>
explicit CreateTreeCursorOp(Args&&... args)
: Operator(std::forward<Args>(args)...),
fields_(OperatorBase::GetRepeatedArgument<std::string>("fields")) {}
bool RunOnDevice() override {
*OperatorBase::Output<std::unique_ptr<TreeCursor>>(0) =
std::unique_ptr<TreeCursor>(new TreeCursor(TreeIterator(fields_)));
return true;
}
private:
std::vector<std::string> fields_;
};
class GetCursorOffsetOp : public Operator<CPUContext> {
public:
template <class... Args>
explicit GetCursorOffsetOp(Args&&... args)
: Operator(std::forward<Args>(args)...) {}
bool RunOnDevice() override {
auto& cursor = OperatorBase::Input<std::unique_ptr<TreeCursor>>(0);
Output(0)->Resize(cursor->offsets.size());
auto* output = Output(0)->template mutable_data<int>();
for (size_t i = 0; i < cursor->offsets.size(); ++i) {
output[i] = cursor->offsets[i];
}
return true;
}
};
class ResetCursorOp : public Operator<CPUContext> {
public:
template <class... Args>
explicit ResetCursorOp(Args&&... args)
: Operator(std::forward<Args>(args)...) {}
bool RunOnDevice() override {
auto& cursor = OperatorBase::Input<std::unique_ptr<TreeCursor>>(0);
std::lock_guard<std::mutex> lock(cursor->mutex_);
cursor->offsets.clear();
return true;
}
};
class CheckDatasetConsistencyOp : public Operator<CPUContext> {
public:
template <class... Args>
explicit CheckDatasetConsistencyOp(Args&&... args)
: Operator(std::forward<Args>(args)...),
iterator_(OperatorBase::GetRepeatedArgument<std::string>("fields")) {}
bool RunOnDevice() override {
std::vector<const TLength*> lengths;
std::vector<TOffset> limits;
std::vector<TOffset> sizes;
std::vector<TOffset> offsets;
CAFFE_ENFORCE(
InputSize() == iterator_.fields().size(),
"Invalid number of fields. Expected ",
iterator_.fields().size(),
", got ",
InputSize());
sizes.resize(iterator_.numOffsetFields());
// gather length data
lengths.resize(iterator_.numLengthFields());
for (size_t i = 0; i < lengths.size(); ++i) {
lengths[i] = Input(iterator_.lengthField(i).id).data<TLength>();
}
// gather size limits
limits.assign(sizes.size(), std::numeric_limits<TOffset>::max());
for (size_t i = 0; i < iterator_.fields().size(); ++i) {
int lengthIdx = iterator_.fields()[i].lengthFieldId + 1;
CAFFE_ENFORCE_GT(Input(i).dim(), 0);
TOffset size = (TOffset)Input(i).sizes()[0];
if (limits[lengthIdx] == std::numeric_limits<TOffset>::max()) {
limits[lengthIdx] = size;
} else {
CAFFE_ENFORCE(
limits[lengthIdx] == size,
"Inconsistent sizes for fields belonging to same domain.",
" Field: ",
i,
" (",
iterator_.fields()[i].name,
"); Length field index: ",
lengthIdx,
"); Previous size: ",
limits[lengthIdx],
"; New size: ",
size);
}
}
// advance to the end
offsets.assign(sizes.size(), 0);
iterator_.advance(lengths, offsets, sizes, limits, limits[0]);
for (size_t i = 0; i < limits.size(); ++i) {
CAFFE_ENFORCE(limits[i] == offsets[i]);
}
return true;
}
private:
TreeIterator iterator_;
};
class PackRecordsOp : public Operator<CPUContext> {
public:
template <class... Args>
explicit PackRecordsOp(Args&&... args)
: Operator(std::forward<Args>(args)...),
fields_(OperatorBase::GetRepeatedArgument<std::string>("fields")) {}
bool RunOnDevice() override {
// There should be one input per field
CAFFE_ENFORCE_EQ(InputSize(), fields_.size());
CAFFE_ENFORCE_EQ(OutputSize(), 1);
TreeCursor cursor((TreeIterator(fields_)));
TreeWalker walker(Inputs(), cursor);
Output(0)->Resize(walker.size());
// Output(0)->raw_mutable_data(TypeMeta::Make<SharedTensorVectorPtr>()));
auto* dst = Output(0)->template mutable_data<SharedTensorVectorPtr>();
for (int batchId = 0; batchId < walker.size(); ++batchId) {
dst[batchId] = std::make_shared<std::vector<TensorCPU>>();
dst[batchId]->reserve(walker.fields().size());
for (const auto& field : walker.fields()) {
dst[batchId]->emplace_back(field.dim(), CPU);
auto& tensor = dst[batchId]->back();
context_.CopyItemsSameDevice(
field.meta(),
tensor.numel(),
field.ptr() /* src */,
tensor.raw_mutable_data(field.meta()) /* dst */);
}
walker.advance();
}
return true;
}
private:
std::vector<std::string> fields_;
};
class UnPackRecordsOp : public Operator<CPUContext> {
public:
template <class... Args>
explicit UnPackRecordsOp(Args&&... args)
: Operator(std::forward<Args>(args)...),
fields_(OperatorBase::GetRepeatedArgument<std::string>("fields")) {}
bool RunOnDevice() override {
const auto* inputs = Input(0).template data<SharedTensorVectorPtr>();
const auto numRows = Input(0).numel();
CAFFE_ENFORCE_GE(numRows, 0);
auto numTensors = OutputSize();
// Precomputer the output sizes to avoid resizing
std::vector<std::vector<int64_t>> outputDims(numTensors);
std::vector<const TypeMeta*> metas(numTensors);
CAFFE_ENFORCE(
numRows > 0 || InputSize() > 1,
"Unpacking empty record without shape will leave output blobs in "
"undefined state.");
if (InputSize() == 1) {
getShapeAndMetaFromInput(outputDims, metas);
} else {
getShapeAndMetaFromPrototypeBlobs(outputDims, metas);
}
for (int i = 0; i < numRows; ++i) {
CAFFE_ENFORCE(inputs[i]);
for (int j = 0; j < inputs[i]->size(); ++j) {
const auto& input = inputs[i]->at(j);
// Checks to ensure that dimensions/sizes match
CAFFE_ENFORCE_EQ(outputDims[j].size(), input.dim());
CAFFE_ENFORCE(*metas[j] == input.dtype());
// We look from first dimension, because we concat on the first.
for (int k = 1; k < input.dim(); ++k) {
CAFFE_ENFORCE_EQ(input.sizes()[k], outputDims[j][k]);
}
outputDims[j][0] += input.size(0);
}
}
// Resize to the final output size
std::vector<void*> destinations(numTensors);
for (int i = 0; i < numTensors; ++i) {
Output(i)->Resize(outputDims[i]);
destinations[i] = Output(i)->raw_mutable_data(*metas[i]);
}
for (int i = 0; i < numRows; ++i) {
for (int j = 0; j < numTensors; ++j) {
const auto& input = inputs[i]->at(j);
context_.CopyItemsSameDevice(
*metas[j],
input.numel(),
input.raw_data() /* src */,
destinations[j] /* dst */
);
destinations[j] =
(char*)destinations[j] + input.numel() * input.itemsize();
}
}
return true;
}
private:
void getShapeAndMetaFromInput(
std::vector<std::vector<int64_t>>& outputDims,
std::vector<const TypeMeta*>& metas) {
const auto* inputs = Input(0).template data<SharedTensorVectorPtr>();
const auto& inputZero = inputs[0];
CAFFE_ENFORCE(inputZero);
const auto numTensors = inputZero->size();
CAFFE_ENFORCE_EQ(numTensors, fields_.size());
CAFFE_ENFORCE_EQ(numTensors, OutputSize());
for (int i = 0; i < numTensors; ++i) {
outputDims[i] = inputZero->at(i).sizes().vec();
outputDims[i][0] = 0;
metas[i] = &inputZero->at(i).dtype();
}
}
void getShapeAndMetaFromPrototypeBlobs(
std::vector<std::vector<int64_t>>& outputDims,
std::vector<const TypeMeta*>& metas) {
const auto numTensors = fields_.size();
CAFFE_ENFORCE_EQ(numTensors, InputSize() - 1);
CAFFE_ENFORCE_EQ(numTensors, OutputSize());
for (int i = 0; i < numTensors; ++i) {
const auto& input = Input(i + 1);
outputDims[i] = input.sizes().vec();
outputDims[i][0] = 0;
metas[i] = &input.dtype();
}
}
std::vector<std::string> fields_;
};
class ReadNextBatchOp : public Operator<CPUContext> {
public:
template <class... Args>
explicit ReadNextBatchOp(Args&&... args)
: Operator(std::forward<Args>(args)...),
batchSize_(OperatorBase::GetSingleArgument<int>("batch_size", 1)),
enforceBatchSize_(OperatorBase::GetSingleArgument<bool>(
"enforce_batch_size",
false)) {}
bool RunOnDevice() override {
auto& cursor = OperatorBase::Input<std::unique_ptr<TreeCursor>>(0);
CAFFE_ENFORCE(InputSize() == cursor->it.fields().size() + 1);
std::vector<const TLength*> lengths;
std::vector<TOffset> limits;
std::vector<TOffset> sizes;
std::vector<TOffset> offsets;
TLength lenZero = 0;
sizes.resize(cursor->it.numOffsetFields());
// gather length data
lengths.resize(cursor->it.numLengthFields());
for (int i = 0; i < lengths.size(); ++i) {
auto& a = Input(cursor->it.lengthField(i).id + 1);
if (a.numel() > 0) {
lengths[i] = a.data<int>();
} else {
lengths[i] = &lenZero;
}
}
// gather size limits
limits.assign(sizes.size(), std::numeric_limits<TOffset>::max());
for (int i = 0; i < cursor->it.fields().size(); ++i) {
int lengthFieldIdx = cursor->it.fields()[i].lengthFieldId + 1;
limits[lengthFieldIdx] =
std::min(limits[lengthFieldIdx], (TOffset)Input(i + 1).sizes()[0]);
}
// advance cursor
{
std::lock_guard<std::mutex> lock(cursor->mutex_);
if (cursor->offsets.empty()) {
cursor->offsets.assign(sizes.size(), 0);
}
offsets = cursor->offsets;
cursor->it.advance(lengths, cursor->offsets, sizes, limits, batchSize_);
if (enforceBatchSize_ && sizes[0] < batchSize_) {
// if we enforce batch_size but don't have enough rows left to
// complete a full batch, return empty for all columns.
// This signals end of dataset to the caller.
sizes.assign(sizes.size(), 0);
}
}
// gather data
std::vector<int64_t> outDim;
for (int i = 0; i < cursor->it.fields().size(); ++i) {
auto lengthIdx = cursor->it.fields()[i].lengthFieldId + 1;
auto size = sizes[lengthIdx];
auto offset = offsets[lengthIdx];
auto& in = Input(i + 1);
auto innerSize = in.size_from_dim(1);
outDim = in.sizes().vec();
outDim[0] = size;
auto* out = Output(i);
out->Resize(outDim);
void* src =
(char*)in.raw_data() + offset * innerSize * in.dtype().itemsize();
void* dst = out->raw_mutable_data(in.dtype()); // create the tensor
if (out->numel() == 0) {
continue;
}
context_.CopyItemsSameDevice(in.dtype(), out->numel(), src, dst);
}
return true;
}
int batchSize_;
bool enforceBatchSize_;
};
class ComputeOffsetOp : public Operator<CPUContext> {
public:
template <class... Args>
explicit ComputeOffsetOp(Args&&... args)
: Operator(std::forward<Args>(args)...) {}
bool RunOnDevice() override {
auto& cursor = OperatorBase::Input<std::unique_ptr<TreeCursor>>(0);
CAFFE_ENFORCE(InputSize() == cursor->it.fields().size() + 1);
auto* out = Output(0);
std::vector<const TLength*> lengths;
std::vector<TOffset> limits;
std::vector<TOffset> sizes;
std::vector<TOffset> offsets;
TLength lenZero = 0;
sizes.resize(cursor->it.numOffsetFields());
// gather length data
lengths.resize(cursor->it.numLengthFields());
for (int i = 0; i < lengths.size(); ++i) {
auto& a = Input(cursor->it.lengthField(i).id + 1);
if (a.numel() > 0) {
lengths[i] = a.data<int>();
} else {
lengths[i] = &lenZero;
}
}
// gather size limits
limits.assign(sizes.size(), std::numeric_limits<TOffset>::max());
for (int i = 0; i < cursor->it.fields().size(); ++i) {
int lengthFieldIdx = cursor->it.fields()[i].lengthFieldId + 1;
limits[lengthFieldIdx] =
std::min(limits[lengthFieldIdx], (TOffset)Input(i + 1).sizes()[0]);
}
out->Resize(limits.at(0) + 1, sizes.size());
auto* out_data = out->template mutable_data<int64_t>();
for (int k = 0; k <= limits.at(0); k++) {
// advance cursor
if (cursor->offsets.empty()) {
cursor->offsets.assign(sizes.size(), 0);
}
// write output
std::copy(cursor->offsets.begin(), cursor->offsets.end(), out_data);
out_data += sizes.size();
cursor->it.advance(lengths, cursor->offsets, sizes, limits, 1);
}
cursor->offsets.assign(sizes.size(), 0); // reSet after getting meta info
return true;
}
};
class SortAndShuffleOp : public Operator<CPUContext> {
public:
template <class... Args>
explicit SortAndShuffleOp(Args&&... args)
: Operator(std::forward<Args>(args)...),
sort_by_field_idx_(
OperatorBase::GetSingleArgument<int>("sort_by_field_idx", 1)),
batch_size_(OperatorBase::GetSingleArgument<int>("batch_size", 1)),
shuffle_size_(OperatorBase::GetSingleArgument<int>("shuffle_size", 1)) {
}
bool RunOnDevice() override {
auto& cursor = OperatorBase::Input<std::unique_ptr<TreeCursor>>(0);
CAFFE_ENFORCE(InputSize() == cursor->it.fields().size() + 1);
CAFFE_ENFORCE(-1 <= sort_by_field_idx_);
CAFFE_ENFORCE(cursor->it.fields().size() - sort_by_field_idx_ > 0);
int size;
if (sort_by_field_idx_ != -1) {
size = Input(sort_by_field_idx_ + 1).sizes()[0];
} else {
size = Input(1).sizes()[0];
}
CAFFE_ENFORCE(
batch_size_ > 0 && shuffle_size_ > 0 &&
0 < batch_size_ * shuffle_size_);
// adjust shuffle_size_ if it is too large
if (batch_size_ * shuffle_size_ > size) {
shuffle_size_ = size / batch_size_;
}
int num_batch = size / batch_size_;
auto* out = Output(0);
out->Resize(size);
auto* out_data = out->template mutable_data<int64_t>();
vector<int> shuffle_idx(size);
iota(shuffle_idx.begin(), shuffle_idx.end(), 0);
if (sort_by_field_idx_ != -1) {
auto& sortblob = Input(sort_by_field_idx_ + 1);
auto* sortdata = sortblob.data<int>();
// must sort by a field at the root level
CAFFE_ENFORCE(
cursor->it.fields()[sort_by_field_idx_].lengthFieldId == -1);
sort(shuffle_idx.begin(), shuffle_idx.end(), [&sortdata](int i1, int i2) {
return sortdata[i1] < sortdata[i2];
});
}
if (batch_size_ * shuffle_size_ > 1) {
int offset = 0;
while (offset + batch_size_ * shuffle_size_ < size) {
std::shuffle(
shuffle_idx.begin() + offset,
shuffle_idx.begin() + offset + batch_size_ * shuffle_size_,
std::default_random_engine());
offset += batch_size_ * shuffle_size_;
}
}
vector<int> batch_idx(num_batch);
iota(batch_idx.begin(), batch_idx.end(), 0);
std::shuffle(
batch_idx.begin(), batch_idx.end(), std::default_random_engine());
for (int i = 0; i < num_batch; i++) {
std::copy(
shuffle_idx.begin() + batch_idx[i] * batch_size_,
shuffle_idx.begin() + (batch_idx[i] + 1) * batch_size_,
out_data);
out_data += batch_size_;
}
std::copy(
shuffle_idx.begin() + num_batch * batch_size_,
shuffle_idx.end(),
out_data);
return true;
}
int sort_by_field_idx_;
int batch_size_;
int shuffle_size_;
};
class ReadRandomBatchOp : public Operator<CPUContext> {
public:
template <class... Args>
explicit ReadRandomBatchOp(Args&&... args)
: Operator(std::forward<Args>(args)...),
batchSize_(OperatorBase::GetSingleArgument<int>("batch_size", 1)),
enforceBatchSize_(
OperatorBase::GetSingleArgument<bool>("enforce_batch_size", false)),
loopOver_(OperatorBase::GetSingleArgument<bool>("loop_over", false)) {}
bool RunOnDevice() override {
auto& cursor = OperatorBase::Input<std::unique_ptr<TreeCursor>>(0);
auto& idxblob = Input(1);
auto& offsetsmat = Input(2);
CAFFE_ENFORCE(InputSize() == cursor->it.fields().size() + 3);
auto idxvec = idxblob.template data<int64_t>();
auto offsetdim = offsetsmat.sizes();
// gather data
std::vector<int64_t> outDim;
int64_t idx;
{
std::lock_guard<std::mutex> lock(cursor->mutex_);
cursor->offsets.resize(1);
idx = cursor->offsets.at(0);
// if we want to enforce batch size but we dont have a complete
// batch, skip the last rows.
if (enforceBatchSize_ && idx + batchSize_ > idxblob.numel()) {
idx = idxblob.numel();
}
if (loopOver_ && idx >= idxblob.numel()) {
cursor->offsets.at(0) = 0;
idx = 0;
}
cursor->offsets.at(0) += batchSize_;
}
for (int i = 0; i < cursor->it.fields().size(); ++i) {
auto lengthIdx = cursor->it.fields()[i].lengthFieldId + 1;
auto& in = Input(i + 3);
outDim = in.sizes().vec();
outDim.at(0) = 0;
auto idxbegin = idx;
for (int j = 0; j < batchSize_; ++j) {
if (idx >= idxblob.numel()) {
break;
}
CAFFE_ENFORCE(
(idxvec[idx] + 1) * offsetdim[1] + lengthIdx < offsetsmat.numel(),
"Out of bound when trying to get elem from offsetsmat");
auto offsetptr = offsetsmat.template data<TOffset>() +
idxvec[idx] * offsetdim[1] + lengthIdx;
auto offset = *offsetptr;
auto size = *(offsetptr + offsetdim[1]) - offset;
outDim.at(0) += size; // accumulate over the batch
idx++;
}
idx = idxbegin; // reSet
auto* out = Output(i);
out->Resize(outDim);
if (out->numel() == 0) {
continue;
}
auto dst = static_cast<char*>(out->raw_mutable_data(in.dtype()));
int block_size = in.numel() / in.size(0);
auto block_bytesize = in.size_from_dim(1) * in.dtype().itemsize();
CAFFE_ENFORCE(
block_bytesize == in.nbytes() / in.size(0),
"block_bytesize should be consistent with data dim");
auto src_base = static_cast<const char*>(in.raw_data());
int start = 0;
for (int j = 0; j < batchSize_; ++j) {
if (idx >= idxblob.numel()) {
break;
}
auto offsetptr = offsetsmat.template data<TOffset>() +
idxvec[idx] * offsetdim[1] + lengthIdx;
auto offset = *offsetptr;
auto size = *(offsetptr + offsetdim[1]) - offset;
// copy data
auto src = src_base + offset * block_bytesize;
context_.CopyItemsSameDevice(
in.dtype(), size * block_size, src, dst + start * block_bytesize);
start += size;
idx++;
}
idx = idxbegin; // reSet
}
return true;
}
int batchSize_;
bool enforceBatchSize_;
bool loopOver_;
};
template <class Context>
class AppendOp final : public Operator<Context> {
public:
USE_OPERATOR_CONTEXT_FUNCTIONS;
template <class... Args>
explicit AppendOp(Args&&... args)
: Operator<Context>(std::forward<Args>(args)...) {}
bool RunOnDevice() override {
auto& a = Input(0);
auto& b = Input(1);
auto* c = Output(0);
CAFFE_ENFORCE(b.dim() >= 1);
if (a.numel() == 0 && a.size(0) == 0) {
c->CopyFrom(b);
return true;
}
CAFFE_ENFORCE(&a == c, "First argument must be in-place.");
CAFFE_ENFORCE(c->dim() == b.dim());
CAFFE_ENFORCE(b.dim() == c->dim());
CAFFE_ENFORCE(a.dtype() == b.dtype());
for (int i = 1; i < a.dim(); ++i) {
CAFFE_ENFORCE(a.sizes()[i] == b.sizes()[i]);
}
auto oldSize = c->numel();
c->Extend(b.sizes()[0], kDatasetGrowthPct);
auto* dst = (char*)c->raw_mutable_data() + oldSize * b.dtype().itemsize();
context_.CopyItemsSameDevice(b.dtype(), b.numel(), b.raw_data(), dst);
return true;
}
};
template <class Context>
class AtomicAppendOp final : public Operator<Context> {
public:
USE_OPERATOR_CONTEXT_FUNCTIONS;
template <class... Args>
explicit AtomicAppendOp(Args&&... args)
: Operator<Context>(std::forward<Args>(args)...) {}
bool RunOnDevice() override {
auto& mutex = OperatorBase::Input<std::unique_ptr<std::mutex>>(0);
const auto numFields = (InputSize() - 1) / 2;
CAFFE_ENFORCE(OutputSize() == numFields);
std::lock_guard<std::mutex> guard(*mutex);
// 1: checks
for (int i = 0; i < numFields; ++i) {
auto& a = Input(1 + i);
auto& b = Input(1 + i + numFields);
auto* c = Output(i);
CAFFE_ENFORCE(b.dim() >= 1);
if (a.numel() == 0) {
continue;
}
CAFFE_ENFORCE(
(void*)&a == (void*)c, "Appended-to arguments must be in-place.");
CAFFE_ENFORCE(c->dim() == b.dim());
CAFFE_ENFORCE(b.dim() == c->dim());
CAFFE_ENFORCE(a.dtype() == b.dtype());
for (int j = 1; j < a.dim(); ++j) {
CAFFE_ENFORCE(a.sizes()[j] == b.sizes()[j]);
}
}
// 2: copies
for (int i = 0; i < numFields; ++i) {
auto& a = Input(1 + i);
auto& b = Input(1 + i + numFields);
auto* c = Output(i);
if (a.numel() == 0 && a.size(0) == 0) {
c->CopyFrom(b);
continue;
}
auto oldSize = c->numel();
c->Extend(b.sizes()[0], kDatasetGrowthPct);
auto* dst = (char*)c->raw_mutable_data() + oldSize * b.dtype().itemsize();
context_.CopyItemsSameDevice(b.dtype(), b.numel(), b.raw_data(), dst);
}
return true;
}
};
template <class Context>
class CreateTensorVectorOp final : public Operator<Context> {
public:
USE_OPERATOR_CONTEXT_FUNCTIONS;
using Operator<Context>::Operator;
bool RunOnDevice() override {
auto ptr = make_unique<std::vector<Tensor>>();
*OperatorBase::Output<TensorVectorPtr>(TENSOR_VECTOR) = std::move(ptr);
return true;
}
private:
OUTPUT_TAGS(TENSOR_VECTOR);
};
template <class Context>
class TensorVectorSizeOp final : public Operator<Context> {
public:
USE_OPERATOR_CONTEXT_FUNCTIONS;
USE_SIMPLE_CTOR_DTOR(TensorVectorSizeOp);
bool RunOnDevice() override {
auto& vector_ptr = OperatorBase::Input<TensorVectorPtr>(TENSOR_VECTOR);
auto* size = Output(SIZE);
size->Resize();
// 32-bit should be enough here
*size->template mutable_data<int32_t>() = vector_ptr->size();
return true;
}
private:
INPUT_TAGS(TENSOR_VECTOR);
OUTPUT_TAGS(SIZE);
};
template <class Context>
class ConcatTensorVectorOp final : public Operator<Context> {
public:
USE_OPERATOR_CONTEXT_FUNCTIONS;
using Operator<Context>::Operator;
bool RunOnDevice() override {
const TensorVectorPtr& tensorVector =
OperatorBase::Input<TensorVectorPtr>(TENSOR_VECTOR);
auto* tensor = Output(TENSOR);
CAFFE_ENFORCE(!tensorVector->empty());
vector<int64_t> outputDims(tensorVector->at(0).sizes().vec());
CAFFE_ENFORCE(outputDims.size() > 0);
for (int i = 1; i < tensorVector->size(); i++) {
// the tensor shapes are the same except for the first dimension
for (int j = 1; j < tensorVector->at(i).dim(); j++) {
CAFFE_ENFORCE(outputDims[j] == tensorVector->at(i).sizes()[j]);
}
CAFFE_ENFORCE(tensorVector->at(0).dtype() == tensorVector->at(i).dtype());
outputDims[0] += tensorVector->at(i).sizes()[0];
}
tensor->Resize(outputDims);
int64_t offset = 0;
auto* dst = (char*)tensor->raw_mutable_data(tensorVector->at(0).dtype());
for (const auto& t : *tensorVector) {
context_.CopyItemsSameDevice(
t.dtype(), t.numel(), t.raw_data(), dst + offset);
offset += t.nbytes();
}
return true;
}
private:
INPUT_TAGS(TENSOR_VECTOR);
OUTPUT_TAGS(TENSOR);
};
template <class Context>
class CollectTensorOp final : public Operator<Context> {
public:
USE_OPERATOR_CONTEXT_FUNCTIONS;
template <class... Args>
explicit CollectTensorOp(Args&&... args)
: Operator<Context>(std::forward<Args>(args)...),
numToCollect_(
OperatorBase::GetSingleArgument<int>("num_to_collect", -1)),
numVisited_(0) {
CAFFE_ENFORCE(numToCollect_ > 0);
}
bool RunOnDevice() override {
int pos = -1;
if (numVisited_ < numToCollect_) {
// append
pos = numVisited_;
} else {
auto& gen = context_.RandGenerator();
// uniform between [0, numVisited_]
std::uniform_int_distribution<int> uniformDist(0, numVisited_);
pos = uniformDist(gen);
if (pos >= numToCollect_) {
// discard
pos = -1;
}
}
for (int i = 0; i < OutputSize(); ++i) {
// TENSOR_VECTOR_IN is enforced inplace with TENSOR_VECTOR_OUT
TensorVectorPtr& tensorVector = *OperatorBase::Output<TensorVectorPtr>(i);
if (numVisited_ >= numToCollect_) {
CAFFE_ENFORCE(
tensorVector->size() == numToCollect_,
"TensorVecotor size = ",
tensorVector->size(),
" is different from numToCollect = ",
numToCollect_);
}
const auto& tensor = Input(OutputSize() + i);
if (pos < 0) {
// discard
CAFFE_ENFORCE(numVisited_ >= numToCollect_);
} else if (pos >= tensorVector->size()) {
// append
tensorVector->emplace_back();
ReinitializeAndCopyFrom(
&tensorVector->back(),
Context::GetDeviceType(),
tensor); // sync copy
} else {
// replace
tensorVector->at(pos).CopyFrom(tensor); // sync copy
}
}
numVisited_++;
return true;
}
private:
// number of tensors to collect
int numToCollect_;
// number of tensors visited
int numVisited_;
};
class TrimDatasetOp : public Operator<CPUContext> {
public:
template <class... Args>
explicit TrimDatasetOp(Args&&... args)
: Operator(std::forward<Args>(args)...),
iterator_(OperatorBase::GetRepeatedArgument<std::string>("fields")),
multiple_of_(OperatorBase::GetSingleArgument<int>("multiple_of", 1)) {
CAFFE_ENFORCE_GE(multiple_of_, 1);
}
bool RunOnDevice() override {
TreeCursor cursor(iterator_);
TreeWalker walker(Inputs(), cursor);
int trimmedSize = (walker.size() / multiple_of_) * multiple_of_;
if (trimmedSize == walker.size()) {
// we already satisfy the condition
return true;
}
// advance desired number of records
for (int i = 0; i < trimmedSize; ++i) {
walker.advance();
}
// trim each column to the offset
for (int col = 0; col < walker.fields().size(); ++col) {
auto newOuterSize = walker.fields().at(col).offset();
Output(col)->ShrinkTo(newOuterSize);
}
return true;
}
private:
TreeIterator iterator_;
int multiple_of_;
};
REGISTER_CPU_OPERATOR(CreateTreeCursor, CreateTreeCursorOp);
REGISTER_CPU_OPERATOR(ResetCursor, ResetCursorOp);
REGISTER_CPU_OPERATOR(ReadNextBatch, ReadNextBatchOp);
REGISTER_CPU_OPERATOR(GetCursorOffset, GetCursorOffsetOp);
REGISTER_CPU_OPERATOR(ComputeOffset, ComputeOffsetOp);
REGISTER_CPU_OPERATOR(SortAndShuffle, SortAndShuffleOp);
REGISTER_CPU_OPERATOR(ReadRandomBatch, ReadRandomBatchOp);
REGISTER_CPU_OPERATOR(CheckDatasetConsistency, CheckDatasetConsistencyOp);
REGISTER_CPU_OPERATOR(Append, AppendOp<CPUContext>);
REGISTER_CPU_OPERATOR(AtomicAppend, AtomicAppendOp<CPUContext>);
REGISTER_CPU_OPERATOR(CreateTensorVector, CreateTensorVectorOp<CPUContext>);
REGISTER_CPU_OPERATOR(TensorVectorSize, TensorVectorSizeOp<CPUContext>);
REGISTER_CPU_OPERATOR(ConcatTensorVector, ConcatTensorVectorOp<CPUContext>);
REGISTER_CPU_OPERATOR(CollectTensor, CollectTensorOp<CPUContext>);
REGISTER_CPU_OPERATOR(PackRecords, PackRecordsOp);
REGISTER_CPU_OPERATOR(UnPackRecords, UnPackRecordsOp);
REGISTER_CPU_OPERATOR(TrimDataset, TrimDatasetOp);
OPERATOR_SCHEMA(CreateTreeCursor)
.NumInputs(0)
.NumOutputs(1)
.SetDoc(R"DOC(
Creates a cursor to iterate through a list of tensors, where some of those
tensors contains the lengths in a nested schema. The schema is determined by
the `fields` arguments.
For example, to represent the following schema:
Struct(
a=Int(),
b=List(List(Int),
c=List(
Struct(
c1=String,
c2=List(Int),
),
),
)
the field list will be:
[
"a",
"b:lengths",
"b:values:lengths",
"b:values:values",
"c:lengths",
"c:c1",
"c:c2:lengths",
"c:c2:values",
]
And for the following instance of the struct:
Struct(
a=3,
b=[[4, 5], [6, 7, 8], [], [9]],
c=[
Struct(c1='alex', c2=[10, 11]),
Struct(c1='bob', c2=[12]),
],
)
The values of the fields will be:
{
"a": [3],
"b:lengths": [4],
"b:values:lengths": [2, 3, 0, 1],
"b:values:values": [4, 5, 6, 7, 8, 9],
"c:lengths": [2],
"c:c1": ["alex", "bob"],
"c:c2:lengths": [2, 1],
"c:c2:values", [10, 11, 12],
}
In general, every field name in the format "{prefix}:lengths" defines a domain
"{prefix}", and every subsequent field in the format "{prefix}:{field}" will
be in that domain, and the length of the domain is provided for each entry of
the parent domain. In the example, "b:lengths" defines a domain of length 4, so
every field under domain "b" will have 4 entries.
The "lengths" field for a given domain must appear before any reference to
that domain.
Returns a pointer to an instance of the Cursor, which keeps the current offset
on each of the domains defined by `fields`. Cursor also ensures thread-safety
such that ReadNextBatch and ResetCursor can be used safely in parallel.
A cursor does not contain data per se, so calls to ReadNextBatch actually need
to pass a list of blobs containing the data to read for each one of the fields.
)DOC")
.Output(0, "cursor", "A blob pointing to an instance of a new TreeCursor.")
.Arg(
"fields",
"A list of strings each one representing a field of the dataset.");
OPERATOR_SCHEMA(ResetCursor)
.NumInputs(1)
.NumOutputs(0)
.SetDoc(R"DOC(
Resets the offsets for the given TreeCursor. This operation is thread safe.
)DOC")
.Input(0, "cursor", "A blob containing a pointer to the cursor.");
OPERATOR_SCHEMA(ReadNextBatch)
.NumInputs(1, INT_MAX)
.NumOutputs(1, INT_MAX)
.SetDoc(R"DOC(
Read the next batch of examples out of the given cursor and data blobs.
Input(0) is a blob pointing to a TreeCursor, and
[Input(1),... Input(num_fields)] a list of tensors containing the data for
each field of the dataset.
ReadNextBatch is thread safe.
)DOC")
.Input(0, "cursor", "A blob containing a pointer to the cursor.")
.Input(1, "dataset_field_0", "First dataset field")
.Output(0, "field_0", "Tensor containing the next batch for field 0.")
.Arg("batch_size", "Number of top-level entries to read.");
OPERATOR_SCHEMA(GetCursorOffset)
.NumInputs(1)
.NumOutputs(1)
.SetDoc("Get the current offset in the cursor.")
.Input(0, "cursor", "A blob containing a pointer to the cursor.")
.Output(0, "offsets", "Tensor containing the offsets for the cursor.");
OPERATOR_SCHEMA(ComputeOffset)
.NumInputs(1, INT_MAX)
.NumOutputs(1)
.SetDoc(R"DOC(
Compute the offsets matrix given cursor and data blobs. Need to be ran at
beginning or after reseting cursor
Input(0) is a blob pointing to a TreeCursor, and
[Input(1),... Input(num_fields)] a list of tensors containing the data for
each field of the dataset.
ComputeOffset is thread safe.
)DOC")
.Input(0, "cursor", "A blob containing a pointer to the cursor.")
.Input(1, "dataset_field_0", "First dataset field")
.Output(0, "field_0", "Tensor containing offset info for this chunk.");
OPERATOR_SCHEMA(SortAndShuffle)
.NumInputs(1, INT_MAX)
.NumOutputs(1)
.SetDoc(R"DOC(
Compute the sorted indices given a field index to sort by and break the sorted
indices into chunks of shuffle_size * batch_size and shuffle each chunk,
finally we shuffle between batches. If sort_by_field_idx is -1 we skip sort.
For example, we have data sorted as
1,2,3,4,5,6,7,8,9,10,11,12
and batchSize = 2 and shuffleSize = 3, when we shuffle we get:
[3,1,4,6,5,2] [12,10,11,8,9,7]
After this we will shuffle among different batches with size 2
[3,1],[4,6],[5,2],[12,10],[11,8],[9,7]
We may end up with something like
[9,7],[5,2],[12,10],[4,6],[3,1],[11,8]
Input(0) is a blob pointing to a TreeCursor, and
[Input(1),... Input(num_fields)] a list of tensors containing the data for
each field of the dataset.
SortAndShuffle is thread safe.
)DOC")
.Input(0, "cursor", "A blob containing a pointer to the cursor.")
.Input(1, "dataset_field_0", "First dataset field")
.Output(0, "indices", "Tensor containing sorted indices.");
OPERATOR_SCHEMA(ReadRandomBatch)
.NumInputs(1, INT_MAX)
.NumOutputs(1, INT_MAX)
.SetDoc(R"DOC(
Read the next batch of examples out of the given cursor,
idx blob, offset matrix and data blobs.
Input(0) is a blob pointing to a TreeCursor,
Input(1) is a blob pointing to the shuffled idx
Input(2) is a blob pointing to the offset matrix and
[Input(3),... Input(num_fields)] a list of tensors containing the data for
each field of the dataset.
ReadRandomBatch is thread safe.
)DOC")
.Input(0, "cursor", "A blob containing a pointer to the cursor.")
.Input(1, "idx", "idx with a shuffled order.")
.Input(2, "offsetsmat", "offset matrix containing length offset info.")
.Input(3, "dataset_field_0", "First dataset field")
.Output(0, "field_0", "Tensor containing the next batch for field 0.")
.Arg("batch_size", "Number of top-level entries to read.")
.Arg("loop_over", "(bool) Repeat the dataset indefinitely");
OPERATOR_SCHEMA(CheckDatasetConsistency)
.NumInputs(1, INT_MAX)
.NumOutputs(0)
.SetDoc(R"DOC(
Checks that the given data fields represents a consistent dataset under
the schema specified by the `fields` argument. Operator fails if the fields
are not consistent. If data is consistent, each field's data can be safely
appended to an existing dataset, keeping it consistent.
)DOC")
.Input(0, "field_0", "Data for field 0.")
.Arg(
"fields",
"List of strings representing the string names in the format"
"specified in the doc for CreateTreeCursor.");
OPERATOR_SCHEMA(Append)
.NumInputs(2)
.NumOutputs(1)
.EnforceInplace({{0, 0}})
.SetDoc(R"DOC(
Append input `B` to the end of input `A`.
- It is required that this operation run in-place, meaning that the input `A` blob must match the output blob.
- All except the outer-most dimension must be the same between `A` and `B`.
- Input `A` may have to be re-allocated in order for accommodate to the new size. Currently, an exponential growth ratio is used in order to ensure amortized constant time complexity.
Github Links:
- https://github.com/pytorch/pytorch/blob/master/caffe2/operators/dataset_ops.cc
<details>
<summary> <b>Example</b> </summary>
**Code**
```
workspace.ResetWorkspace()
op = core.CreateOperator(
"Append",
["A", "B"],
["A"],
)
workspace.FeedBlob("A", np.random.randint(10, size=(1,3,3)))
workspace.FeedBlob("B", np.random.randint(10, size=(2,3,3)))
print("A:", workspace.FetchBlob("A"))
print("B:", workspace.FetchBlob("B"))
workspace.RunOperatorOnce(op)
print("A:", workspace.FetchBlob("A"))
```
**Result**
```
A:
[[[3 8 7]
[1 6 6]
[5 0 6]]]
B:
[[[4 3 1]
[7 9 6]
[9 4 5]]
[[7 7 4]
[9 8 7]
[1 6 6]]]
A:
[[[3 8 7]
[1 6 6]
[5 0 6]]
[[4 3 1]
[7 9 6]
[9 4 5]]
[[7 7 4]
[9 8 7]
[1 6 6]]]
```
</details>
)DOC")
.Input(0, "A", "(*Tensor*): base input tensor of shape $(N, d_1, d_2, ..., d_n)$")
.Input(1, "B", "(*Tensor*): second input tensor of shape $(M, d_1, d_2, ..., d_n)$ to be appended to the base")
.Output(0, "A", "(*Tensor*): output tensor of shape $(N+M, d_1, d_2, ..., d_n)$");
OPERATOR_SCHEMA(AtomicAppend)
.NumInputs(3, INT_MAX)
.NumOutputs(1, INT_MAX)
.AllowInplace([](int in, int out) { return in == out + 1; });
OPERATOR_SCHEMA(CreateTensorVector)
.NumInputs(0)
.NumOutputs(1)
.SetDoc("Create a std::unique_ptr<std::vector<Tensor> >");
OPERATOR_SCHEMA(TensorVectorSize)
.NumInputs(1)
.NumOutputs(1)
.SetDoc("Get the size of the input vector")
.Input(0, "tensor vector", "std::unique_ptr<std::vector<Tensor> >")
.Output(0, "size", "int32_t size");
OPERATOR_SCHEMA(ConcatTensorVector)
.NumInputs(1)
.NumOutputs(1)
.SetDoc(R"DOC(
Concat Tensors in the std::unique_ptr<std::vector<Tensor> >
along the first dimension.
)DOC")
.Input(0, "vector of Tensor", "std::unique_ptr<std::vector<Tensor> >")
.Output(0, "tensor", "tensor after concatenating");
OPERATOR_SCHEMA(CollectTensor)
.NumInputs([](int n) { return n > 0 && n % 2 == 0; })
.NumOutputs(1, INT_MAX)
.NumInputsOutputs([](int in, int out) { return in == out * 2; })
.EnforceInplace([](int in, int out) { return in == out; })
.SetDoc(R"DOC(
Collect tensor into tensor vector by reservoir sampling,
argument num_to_collect indicates the max number of tensors that will be
collected. The first half of the inputs are tensor vectors, which are also the
outputs. The second half of the inputs are the tensors to be collected into each
vector (in the same order). The input tensors are collected in all-or-none
manner. If they are collected, they will be placed at the same index in the
output vectors.
)DOC")
.Arg("num_to_collect", "The max number of tensors to collect");
OPERATOR_SCHEMA(PackRecords)
.NumInputs(1, INT_MAX)
.NumOutputs(1)
.SetDoc(R"DOC(
Given a dataset under a schema specified by the `fields` argument will pack all
the input tensors into one, where each tensor element represents a row of data
(batch of size 1). This format allows easier use with the rest of Caffe2
operators.
)DOC")
.Arg(
"fields",
"List of strings representing the string names in the format"
"specified in the doc for CreateTreeCursor.")
.Output(
0,
"tensor",
"One dimensional tensor having a complex type of SharedTensorVectorPtr."
" In order to reverse it back to the original input it has to be "
"inserted into UnPackRecordsOp.");
OPERATOR_SCHEMA(TrimDataset)
.NumInputs(1, INT_MAX)
.NumOutputs(1, INT_MAX)
.SetDoc(R"DOC(
Trim the given dataset inplace, given the dataset blobs and the field specs.
Trimming happens such that the dataset will contain the largest possible number
of records that is a multiple of the 'multiple_of' argument.
)DOC")
.EnforceInplace([](int input, int output) { return input == output; })
.Arg(
"fields",
"List of strings representing the string names in the format"
"specified in the doc for CreateTreeCursor.");
OPERATOR_SCHEMA(UnPackRecords)
.NumInputs(1, INT_MAX)
.NumOutputs(1, INT_MAX)
.SetDoc(R"DOC(
Given a packed dataset (packed by the PackRecordsOp) and the `fields` argument
describing the datasets schema returns the original dataset format. Number of
returned tensors is equal to the number of fields in the `fields` argument.
The first input is the packed tensor to be unpacked. Optionally, you can provide
prototype tensors to give the expected shapes of the output tensors. This is
helpful when you expected to unpack empty tensor, e.g., output of a sampling
process.
)DOC")
.Arg(
"fields",
"List of strings representing the string names in the format"
"specified in the doc for CreateTreeCursor.")
.Input(0, "packed_tensor", "The tensor to be unpacked");
SHOULD_NOT_DO_GRADIENT(CreateTreeCursor);
SHOULD_NOT_DO_GRADIENT(ResetCursor);
SHOULD_NOT_DO_GRADIENT(ReadNextBatch);
SHOULD_NOT_DO_GRADIENT(ComputeOffset);
SHOULD_NOT_DO_GRADIENT(ReadRandomBatch);
SHOULD_NOT_DO_GRADIENT(CheckDatasetConsistency);
SHOULD_NOT_DO_GRADIENT(Append);
SHOULD_NOT_DO_GRADIENT(AtomicAppend);
SHOULD_NOT_DO_GRADIENT(CreateTensorVector);
SHOULD_NOT_DO_GRADIENT(TensorVectorSize);
SHOULD_NOT_DO_GRADIENT(ConcatTensorVector);
SHOULD_NOT_DO_GRADIENT(CollectTensor);
SHOULD_NOT_DO_GRADIENT(UnPackRecords);
SHOULD_NOT_DO_GRADIENT(PackRecords);
class TreeCursorSerializer : public BlobSerializerBase {
public:
TreeCursorSerializer() {}
~TreeCursorSerializer() override {}
void Serialize(
const void* pointer,
TypeMeta typeMeta,
const string& name,
SerializationAcceptor acceptor) override {
CAFFE_ENFORCE(typeMeta.Match<std::unique_ptr<TreeCursor>>());
const auto& cursor =
*static_cast<const std::unique_ptr<TreeCursor>*>(pointer);
BlobProto blob_proto;
// serialize offsets as a tensor
if (cursor->offsets.size() > 0) {
Blob offsets_blob;
auto* offsets = BlobGetMutableTensor(&offsets_blob, CPU);
offsets->Resize(cursor->offsets.size());
std::copy(
cursor->offsets.begin(),
cursor->offsets.end(),
offsets->template mutable_data<TOffset>());
TensorSerializer ser;
ser.Serialize(
*offsets, name, blob_proto.mutable_tensor(), 0, offsets->numel());
}
blob_proto.set_name(name);
blob_proto.set_type("std::unique_ptr<TreeCursor>");
// serialize field names in the content
std::ostringstream os;
for (const auto& field : cursor->it.fields()) {
os << field.name << " ";
}
blob_proto.set_content(os.str());
acceptor(name, SerializeBlobProtoAsString_EnforceCheck(blob_proto));
}
};
class TreeCursorDeserializer : public BlobDeserializerBase {
public:
void Deserialize(const BlobProto& proto, Blob* blob) override {
// Deserialize the field names
std::vector<std::string> fieldNames;
std::istringstream is(proto.content());
std::string field;
while (true) {
is >> field;
if (is.eof()) {
break;
}
fieldNames.push_back(field);
}
TreeIterator it(fieldNames);
auto* base = blob->template GetMutable<std::unique_ptr<TreeCursor>>();
CAFFE_ENFORCE(base != nullptr, "TreeCursor doesn't exist.");
(*base).reset(new TreeCursor(it));
// Deserialize the offset vector when it is not empty. The proto.tensor()
// function will return a TensorProto associated with offset vector. The
// offset vector contains fields of type int64_t, and we verify it is not
// empty before calling the deserializer.
if (proto.tensor().int64_data().size() > 0) {
TensorDeserializer deser;
Blob offset_blob;
deser.Deserialize(proto, &offset_blob);
auto& offsets = offset_blob.template Get<Tensor>();
auto* offsets_ptr = offsets.data<TOffset>();
(*base)->offsets.assign(offsets_ptr, offsets_ptr + offsets.numel());
}
}
};
REGISTER_BLOB_SERIALIZER(
(TypeMeta::Id<std::unique_ptr<TreeCursor>>()),
TreeCursorSerializer);
REGISTER_BLOB_DESERIALIZER(std::unique_ptr<TreeCursor>, TreeCursorDeserializer);
} // namespace
void SharedTensorVectorPtrSerializer::Serialize(
const void* pointer,
TypeMeta typeMeta,
const string& name,
BlobSerializerBase::SerializationAcceptor acceptor) {
/* This is dummy serialize that doesn't save anything. If saving the content
is desired in future use case, you can change this serializer. Note: special
care need to be taken for the parameter initialization of
LastNWindowCollectorOp and ReservoirSamplingOp if this serializer actually
saves the content.
*/
CAFFE_ENFORCE(typeMeta.Match<std::shared_ptr<std::vector<TensorCPU>>>());
BlobProto blob_proto;
blob_proto.set_name(name);
blob_proto.set_type("std::shared_ptr<std::vector<TensorCPU>>");
blob_proto.set_content("");
acceptor(name, SerializeBlobProtoAsString_EnforceCheck(blob_proto));
};
void SharedTensorVectorPtrDeserializer::Deserialize(
const BlobProto& /* unused */,
Blob* blob) {
/* This is dummy deserialize which creates a nullptr
*/
blob->GetMutable<std::shared_ptr<std::vector<TensorCPU>>>();
}
REGISTER_BLOB_SERIALIZER(
(TypeMeta::Id<std::shared_ptr<std::vector<TensorCPU>>>()),
SharedTensorVectorPtrSerializer);
REGISTER_BLOB_DESERIALIZER(
std::shared_ptr<std::vector<TensorCPU>>,
SharedTensorVectorPtrDeserializer);
} // namespace dataset_ops
} // namespace caffe2
| [
"rnauhria@gmail.com"
] | rnauhria@gmail.com |
a9d556b8626fec512b1b6430a443627b64af71b9 | 46bf6fc69231692b467f50eba2299db7f1784ace | /Proj/facade/hfbutton_facade.h | 0a23956117c0a795552e3286adfeed7f0c460d65 | [] | no_license | RabbitChenc/crasherror | 5080c6629659a04721e27a04a5100d982c264ff6 | 2b3c589f00e60fc32b0715d795d6ac5070126113 | refs/heads/master | 2022-09-17T13:19:21.198554 | 2020-06-03T09:03:28 | 2020-06-03T09:03:28 | 269,039,710 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 979 | h |
/*
*
*brief:使用qpainter 画家类 自定义一个按钮控件
* 按钮继承了Qwidget 重写绘图事件 和鼠标相关的事件
*
*author: Chenjm
*
*/
#ifndef HFBUTTONFACADE_H
#define HFBUTTONFACADE_H
#include "../hfview_facade.h"
#include <QWidget>
#include <QColor>
class HFButtonFacade : public HFViewFacade
{
Q_OBJECT
public:
explicit HFButtonFacade(QWidget*parent = nullptr);
virtual ~HFButtonFacade();
signals:
void pressed();
void released();
protected:
void paintEvent(QPaintEvent *event);
void mousePressEvent(QMouseEvent *event);
void mouseReleaseEvent(QMouseEvent *event);
void drawImage(QPainter*painter);
QPixmap* ninePatch(QString picName,int iHorzSplit,int iVertSplit, int DstWidth, int DstHeight);
QPixmap generatePixmap(const QPixmap &src, const int w,const int h);
private:
bool press;
int btnWidth;
int btnHight;
int btnStyle;
QString mImageName;
};
#endif // HFBUTTONFACADE_H
| [
"357778342@qq.com"
] | 357778342@qq.com |
43b2255f5fb45d06c9a5e2a83077149df7df4e9c | 26968d29aefc53d207ab2559084fd8b6943da85b | /SourceFiles/httpThread_y.cpp | 83b728b0212680df85c423a8d0c27e56014d5071 | [] | no_license | dzfowen/Visual-Telemedicine-Aided-Diagnosis-Platform | 53d8809af5cecf4e9c7094ea45e6318436d984fe | efe25002e6d62827f3327281ac505480d5bfd3df | refs/heads/master | 2020-06-01T22:56:44.656482 | 2019-06-09T02:59:18 | 2019-06-09T02:59:18 | 190,713,486 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,380 | cpp | #include "httpThread_y.h"
extern Service* service2;
void httpThread_y::on_get(lacewing::webserver webserver, lacewing::webserver_request request)
{
std::string str;
str = request->GET("Command");
qDebug() << "http thread_y " << str.c_str() << endl;
if (strcmp(str.c_str(), "getcurrentuser") == 0)
{
request->writef(service2->Currentuser().c_str());
}
if (strcmp(str.c_str(), "setcurrentuser") == 0)
{
std::string str1 = request->GET("currentuser");
service2->Currentuser(str1);
}
if (strcmp(str.c_str(), "polling") == 0)
{
}
if (strcmp(str.c_str(), "getlastFile") == 0)
{
char temp1[100];
sprintf_s(temp1, "%d", service2->Lastfile());
request->writef(temp1);
}
if (strcmp(str.c_str(), "getFileList") == 0)
{
string strTosend;
map<string, DataFile*>::iterator begin, end;
end = service2->filedir.end();
for (begin = service2->filedir.begin(); begin != end; begin++)
{
strTosend += (*begin).first + ",";
}
if (strTosend.length() != 0)
{
strTosend = strTosend.substr(0, strTosend.length() - 1);
}
request->writef(strTosend.c_str());
}
if (strcmp(str.c_str(), "getFile") == 0)
{
string md5 = request->GET("md5");
map<string, DataFile*>::iterator i;
i = service2->filedir.find(md5);
if ((*i).second->getType() == ".vtk")
{
//HZIP hz;
string oripath = (*i).second->getPath();
//string path = oripath.substr(0, oripath.find_last_of(".")) + ".zip";
//hz = CreateZip(path.c_str(), 0);
//ZipAdd(hz, oripath.substr(oripath.find_last_of("/") + 1).c_str(), oripath.c_str());
//CloseZip(hz);
//request->write_file(path.c_str());
request->write_file(oripath.c_str());
}
if ((*i).second->getType() == ".mhd")
{
request->write_file((*i).second->Path().c_str());
}
if ((*i).second->getType() == ".raw")
{
request->write_file((*i).second->Path().c_str());
}
else if ((*i).second->getType() == ".dcm")
{
request->write_file((*i).second->Path().c_str());
//HZIP hz;
//string fold = (*i).second->getPath().substr(0, (*i).second->getPath().find_last_of("/"));
//_finddata_t file;
//string path2 = fold + ".zip";
//long longf;
////TCHAR pathT[50] = { '0' };
////mbstowcs(pathT, path2.c_str(), path2.size());
//hz = CreateZip(path2.c_str(), 0);
//
//if ((longf = _findfirst((fold + "/*.*").c_str(), &file)) == -1l)
//{
// qDebug() << "cannot find file";
//}
//else
//{
// string tempName;
// while (_findnext(longf, &file) == 0)
// {
// tempName = "";
// tempName = file.name;
// //TCHAR tempNameT[50] = {'0'};
// //mbstowcs(tempNameT, tempName.c_str(), tempName.size());
// //TCHAR tempNameT2[50] = {'0'};
// //mbstowcs(tempNameT2, (fold + "/" + tempName).c_str(), (fold + "/" + tempName).size());
// ZipAdd(hz, tempName.c_str(), (fold + "/" + tempName).c_str());
// qDebug() << tempName.c_str();
// }
//}
//_findclose(longf);
//CloseZip(hz);
//request->write_file(path2.c_str());
}
}
}
httpThread_y::httpThread_y()
{
eventpump = lacewing::eventpump_new();
webserver = lacewing::webserver_new(eventpump);
}
httpThread_y::~httpThread_y()
{
}
void httpThread_y::run()
{
qDebug() << "http thread_y start";
webserver->on_get(on_get);
webserver->host(20001);
eventpump->start_eventloop();
lacewing::webserver_delete(webserver);
lacewing::pump_delete(eventpump);
}
| [
"575900931@qq.com"
] | 575900931@qq.com |
e8ff4ec859a9827f95d2ec728e9bdf4389f00882 | 36579e820f5c07cd1fe796abc777f23f32efeb10 | /src/chrome/browser/prerender/prerender_link_manager.cc | b0b2bc6496b8ef837beef4932b00a47c03cafadf | [
"BSD-3-Clause"
] | permissive | sokolovp/BraveMining | 089ea9940ee6e6cb8108b106198e66c62049d27b | 7040cdee80f6f7176bea0e92f8f3435abce3e0ae | refs/heads/master | 2020-03-20T00:52:22.001918 | 2018-06-12T11:33:31 | 2018-06-12T11:33:31 | 137,058,944 | 0 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 18,746 | cc | // Copyright (c) 2012 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "chrome/browser/prerender/prerender_link_manager.h"
#include <functional>
#include <limits>
#include <memory>
#include <set>
#include <string>
#include <utility>
#include "base/metrics/field_trial.h"
#include "base/metrics/histogram_macros.h"
#include "chrome/browser/prerender/prerender_contents.h"
#include "chrome/browser/prerender/prerender_handle.h"
#include "chrome/browser/prerender/prerender_manager.h"
#include "chrome/browser/prerender/prerender_manager_factory.h"
#include "chrome/common/prerender.mojom.h"
#include "chrome/common/prerender_types.h"
#include "content/public/browser/render_process_host.h"
#include "content/public/browser/render_view_host.h"
#include "content/public/browser/session_storage_namespace.h"
#include "content/public/common/referrer.h"
#include "extensions/features/features.h"
#include "third_party/WebKit/public/common/associated_interfaces/associated_interface_provider.h"
#include "ui/gfx/geometry/size.h"
#include "url/gurl.h"
#if BUILDFLAG(ENABLE_EXTENSIONS)
#include "components/guest_view/browser/guest_view_base.h"
#endif
using base::TimeDelta;
using base::TimeTicks;
using content::RenderViewHost;
using content::SessionStorageNamespace;
namespace prerender {
namespace {
static_assert(PrerenderRelTypePrerender == 0x1,
"RelTypeHistogrameEnum must match PrerenderRelType");
static_assert(PrerenderRelTypeNext == 0x2,
"RelTypeHistogramEnum must match PrerenderRelType");
constexpr int kRelTypeHistogramEnumMax =
(PrerenderRelTypePrerender | PrerenderRelTypeNext) + 1;
void RecordLinkManagerAdded(const uint32_t rel_types) {
UMA_HISTOGRAM_ENUMERATION("Prerender.RelTypesLinkAdded",
rel_types & (kRelTypeHistogramEnumMax - 1),
kRelTypeHistogramEnumMax);
}
void RecordLinkManagerStarting(const uint32_t rel_types) {
UMA_HISTOGRAM_ENUMERATION("Prerender.RelTypesLinkStarted",
rel_types & (kRelTypeHistogramEnumMax - 1),
kRelTypeHistogramEnumMax);
}
chrome::mojom::PrerenderDispatcherAssociatedPtr GetPrerenderDispatcher(
int child_id) {
chrome::mojom::PrerenderDispatcherAssociatedPtr prerender_dispatcher;
content::RenderProcessHost* render_process_host =
content::RenderProcessHost::FromID(child_id);
if (render_process_host) {
IPC::ChannelProxy* channel = render_process_host->GetChannel();
// |channel| might be NULL in tests.
if (channel) {
channel->GetRemoteAssociatedInterface(&prerender_dispatcher);
}
}
return prerender_dispatcher;
}
} // namespace
// Helper class to implement PrerenderContents::Observer and watch prerenders
// which launch other prerenders.
class PrerenderLinkManager::PendingPrerenderManager
: public PrerenderContents::Observer {
public:
explicit PendingPrerenderManager(PrerenderLinkManager* link_manager)
: link_manager_(link_manager) {}
~PendingPrerenderManager() override { CHECK(observed_launchers_.empty()); }
void ObserveLauncher(PrerenderContents* launcher) {
DCHECK_EQ(FINAL_STATUS_MAX, launcher->final_status());
bool inserted = observed_launchers_.insert(launcher).second;
if (inserted)
launcher->AddObserver(this);
}
void OnPrerenderStart(PrerenderContents* launcher) override {}
void OnPrerenderStop(PrerenderContents* launcher) override {
observed_launchers_.erase(launcher);
if (launcher->final_status() == FINAL_STATUS_USED) {
link_manager_->StartPendingPrerendersForLauncher(launcher);
} else {
link_manager_->CancelPendingPrerendersForLauncher(launcher);
}
}
void OnPrerenderNetworkBytesChanged(PrerenderContents* launcher) override {}
private:
// A pointer to the parent PrerenderLinkManager.
PrerenderLinkManager* link_manager_;
// The set of PrerenderContentses being observed. Lifetimes are managed by
// OnPrerenderStop.
std::set<PrerenderContents*> observed_launchers_;
};
PrerenderLinkManager::PrerenderLinkManager(PrerenderManager* manager)
: has_shutdown_(false),
manager_(manager),
pending_prerender_manager_(
std::make_unique<PendingPrerenderManager>(this)) {}
PrerenderLinkManager::~PrerenderLinkManager() {
for (auto& prerender : prerenders_) {
if (prerender.handle) {
DCHECK(!prerender.handle->IsPrerendering())
<< "All running prerenders should stop at the same time as the "
<< "PrerenderManager.";
delete prerender.handle;
prerender.handle = nullptr;
}
}
}
void PrerenderLinkManager::OnAddPrerender(int launcher_child_id,
int prerender_id,
const GURL& url,
uint32_t rel_types,
const content::Referrer& referrer,
const gfx::Size& size,
int render_view_route_id) {
DCHECK_EQ(nullptr, FindByLauncherChildIdAndPrerenderId(launcher_child_id,
prerender_id));
#if BUILDFLAG(ENABLE_EXTENSIONS)
content::RenderViewHost* rvh =
content::RenderViewHost::FromID(launcher_child_id, render_view_route_id);
content::WebContents* web_contents =
rvh ? content::WebContents::FromRenderViewHost(rvh) : nullptr;
// Guests inside <webview> do not support cross-process navigation and so we
// do not allow guests to prerender content.
if (guest_view::GuestViewBase::IsGuest(web_contents))
return;
#endif
// Check if the launcher is itself an unswapped prerender.
PrerenderContents* prerender_contents =
manager_->GetPrerenderContentsForRoute(launcher_child_id,
render_view_route_id);
if (prerender_contents &&
prerender_contents->final_status() != FINAL_STATUS_MAX) {
// The launcher is a prerender about to be destroyed asynchronously, but
// its AddLinkRelPrerender message raced with shutdown. Ignore it.
DCHECK_NE(FINAL_STATUS_USED, prerender_contents->final_status());
return;
}
LinkPrerender
prerender(launcher_child_id, prerender_id, url, rel_types, referrer, size,
render_view_route_id, manager_->GetCurrentTimeTicks(),
prerender_contents);
prerenders_.push_back(prerender);
RecordLinkManagerAdded(rel_types);
if (prerender_contents)
pending_prerender_manager_->ObserveLauncher(prerender_contents);
else
StartPrerenders();
}
void PrerenderLinkManager::OnCancelPrerender(int child_id, int prerender_id) {
LinkPrerender* prerender = FindByLauncherChildIdAndPrerenderId(child_id,
prerender_id);
if (!prerender)
return;
CancelPrerender(prerender);
StartPrerenders();
}
void PrerenderLinkManager::OnAbandonPrerender(int child_id, int prerender_id) {
LinkPrerender* prerender = FindByLauncherChildIdAndPrerenderId(child_id,
prerender_id);
if (!prerender)
return;
if (!prerender->handle) {
RemovePrerender(prerender);
return;
}
prerender->has_been_abandoned = true;
prerender->handle->OnNavigateAway();
DCHECK(prerender->handle);
// If the prerender is not running, remove it from the list so it does not
// leak. If it is running, it will send a cancel event when it stops which
// will remove it.
if (!prerender->handle->IsPrerendering())
RemovePrerender(prerender);
}
void PrerenderLinkManager::OnChannelClosing(int child_id) {
std::list<LinkPrerender>::iterator next = prerenders_.begin();
while (next != prerenders_.end()) {
std::list<LinkPrerender>::iterator it = next;
++next;
if (child_id != it->launcher_child_id)
continue;
const size_t running_prerender_count = CountRunningPrerenders();
OnAbandonPrerender(child_id, it->prerender_id);
DCHECK_EQ(running_prerender_count, CountRunningPrerenders());
}
}
PrerenderLinkManager::LinkPrerender::LinkPrerender(
int launcher_child_id,
int prerender_id,
const GURL& url,
uint32_t rel_types,
const content::Referrer& referrer,
const gfx::Size& size,
int render_view_route_id,
TimeTicks creation_time,
PrerenderContents* deferred_launcher)
: launcher_child_id(launcher_child_id),
prerender_id(prerender_id),
url(url),
rel_types(rel_types),
referrer(referrer),
size(size),
render_view_route_id(render_view_route_id),
creation_time(creation_time),
deferred_launcher(deferred_launcher),
handle(nullptr),
has_been_abandoned(false) {}
PrerenderLinkManager::LinkPrerender::LinkPrerender(const LinkPrerender& other) =
default;
PrerenderLinkManager::LinkPrerender::~LinkPrerender() {
DCHECK_EQ(nullptr, handle)
<< "The PrerenderHandle should be destroyed before its Prerender.";
}
bool PrerenderLinkManager::IsEmpty() const {
return prerenders_.empty();
}
size_t PrerenderLinkManager::CountRunningPrerenders() const {
return std::count_if(prerenders_.begin(), prerenders_.end(),
[](const LinkPrerender& prerender) {
return prerender.handle &&
prerender.handle->IsPrerendering();
});
}
void PrerenderLinkManager::StartPrerenders() {
if (has_shutdown_)
return;
size_t total_started_prerender_count = 0;
std::list<LinkPrerender*> abandoned_prerenders;
std::list<std::list<LinkPrerender>::iterator> pending_prerenders;
std::multiset<std::pair<int, int> >
running_launcher_and_render_view_routes;
// Scan the list, counting how many prerenders have handles (and so were added
// to the PrerenderManager). The count is done for the system as a whole, and
// also per launcher.
for (std::list<LinkPrerender>::iterator i = prerenders_.begin();
i != prerenders_.end(); ++i) {
LinkPrerender& prerender = *i;
// Skip prerenders launched by a prerender.
if (prerender.deferred_launcher)
continue;
if (!prerender.handle) {
pending_prerenders.push_back(i);
} else {
++total_started_prerender_count;
if (prerender.has_been_abandoned) {
abandoned_prerenders.push_back(&prerender);
} else {
// We do not count abandoned prerenders towards their launcher, since it
// has already navigated on to another page.
std::pair<int, int> launcher_and_render_view_route(
prerender.launcher_child_id, prerender.render_view_route_id);
running_launcher_and_render_view_routes.insert(
launcher_and_render_view_route);
DCHECK_GE(manager_->config().max_link_concurrency_per_launcher,
running_launcher_and_render_view_routes.count(
launcher_and_render_view_route));
}
}
DCHECK_EQ(&prerender,
FindByLauncherChildIdAndPrerenderId(prerender.launcher_child_id,
prerender.prerender_id));
}
DCHECK_LE(abandoned_prerenders.size(), total_started_prerender_count);
DCHECK_GE(manager_->config().max_link_concurrency,
total_started_prerender_count);
DCHECK_LE(CountRunningPrerenders(), total_started_prerender_count);
TimeTicks now = manager_->GetCurrentTimeTicks();
// Scan the pending prerenders, starting prerenders as we can.
for (std::list<std::list<LinkPrerender>::iterator>::const_iterator
i = pending_prerenders.begin(), end = pending_prerenders.end();
i != end; ++i) {
const std::list<LinkPrerender>::iterator& it = *i;
TimeDelta prerender_age = now - it->creation_time;
if (prerender_age >= manager_->config().max_wait_to_launch) {
// This prerender waited too long in the queue before launching.
prerenders_.erase(it);
continue;
}
std::pair<int, int> launcher_and_render_view_route(
it->launcher_child_id, it->render_view_route_id);
if (manager_->config().max_link_concurrency_per_launcher <=
running_launcher_and_render_view_routes.count(
launcher_and_render_view_route)) {
// This prerender's launcher is already at its limit.
continue;
}
if (total_started_prerender_count >=
manager_->config().max_link_concurrency ||
total_started_prerender_count >= prerenders_.size()) {
// The system is already at its prerender concurrency limit. Try removing
// an abandoned prerender, if one exists, to make room.
if (abandoned_prerenders.empty())
return;
CancelPrerender(abandoned_prerenders.front());
--total_started_prerender_count;
abandoned_prerenders.pop_front();
}
if (!(PrerenderRelTypePrerender & it->rel_types)) {
prerenders_.erase(it);
continue;
}
std::unique_ptr<PrerenderHandle> handle =
manager_->AddPrerenderFromLinkRelPrerender(
it->launcher_child_id, it->render_view_route_id, it->url,
it->rel_types, it->referrer, it->size);
if (!handle) {
// This prerender couldn't be launched, it's gone.
prerenders_.erase(it);
continue;
}
if (handle->IsPrerendering()) {
// We have successfully started a new prerender.
it->handle = handle.release();
++total_started_prerender_count;
it->handle->SetObserver(this);
OnPrerenderStart(it->handle);
RecordLinkManagerStarting(it->rel_types);
running_launcher_and_render_view_routes.insert(
launcher_and_render_view_route);
} else {
content::RenderProcessHost* render_process_host =
content::RenderProcessHost::FromID(it->launcher_child_id);
if (!render_process_host)
return;
IPC::ChannelProxy* channel = render_process_host->GetChannel();
// |channel| might be NULL in tests.
if (channel) {
chrome::mojom::PrerenderDispatcherAssociatedPtr prerender_dispatcher;
channel->GetRemoteAssociatedInterface(&prerender_dispatcher);
prerender_dispatcher->PrerenderStop(it->prerender_id);
}
prerenders_.erase(it);
}
}
}
PrerenderLinkManager::LinkPrerender*
PrerenderLinkManager::FindByLauncherChildIdAndPrerenderId(int launcher_child_id,
int prerender_id) {
for (auto& prerender : prerenders_) {
if (prerender.launcher_child_id == launcher_child_id &&
prerender.prerender_id == prerender_id) {
return &prerender;
}
}
return nullptr;
}
PrerenderLinkManager::LinkPrerender*
PrerenderLinkManager::FindByPrerenderHandle(PrerenderHandle* prerender_handle) {
DCHECK(prerender_handle);
for (auto& prerender : prerenders_) {
if (prerender.handle == prerender_handle)
return &prerender;
}
return nullptr;
}
void PrerenderLinkManager::RemovePrerender(LinkPrerender* prerender) {
for (std::list<LinkPrerender>::iterator i = prerenders_.begin();
i != prerenders_.end(); ++i) {
LinkPrerender& current_prerender = *i;
if (¤t_prerender == prerender) {
std::unique_ptr<PrerenderHandle> own_handle(prerender->handle);
prerender->handle = nullptr;
prerenders_.erase(i);
return;
}
}
NOTREACHED();
}
void PrerenderLinkManager::CancelPrerender(LinkPrerender* prerender) {
for (std::list<LinkPrerender>::iterator i = prerenders_.begin();
i != prerenders_.end(); ++i) {
LinkPrerender& current_prerender = *i;
if (¤t_prerender == prerender) {
std::unique_ptr<PrerenderHandle> own_handle(prerender->handle);
prerender->handle = nullptr;
prerenders_.erase(i);
if (own_handle)
own_handle->OnCancel();
return;
}
}
NOTREACHED();
}
void PrerenderLinkManager::StartPendingPrerendersForLauncher(
PrerenderContents* launcher) {
for (auto& prerender : prerenders_) {
if (prerender.deferred_launcher == launcher)
prerender.deferred_launcher = nullptr;
}
StartPrerenders();
}
void PrerenderLinkManager::CancelPendingPrerendersForLauncher(
PrerenderContents* launcher) {
// Remove all pending prerenders for this launcher.
for (std::list<LinkPrerender>::iterator i = prerenders_.begin();
i != prerenders_.end();) {
if (i->deferred_launcher == launcher) {
DCHECK(!i->handle);
i = prerenders_.erase(i);
} else {
++i;
}
}
}
void PrerenderLinkManager::Shutdown() {
has_shutdown_ = true;
}
// In practice, this is always called from PrerenderLinkManager::OnAddPrerender.
void PrerenderLinkManager::OnPrerenderStart(
PrerenderHandle* prerender_handle) {
LinkPrerender* prerender = FindByPrerenderHandle(prerender_handle);
if (!prerender)
return;
chrome::mojom::PrerenderDispatcherAssociatedPtr prerender_dispatcher =
GetPrerenderDispatcher(prerender->launcher_child_id);
if (prerender_dispatcher)
prerender_dispatcher->PrerenderStart(prerender->prerender_id);
}
void PrerenderLinkManager::OnPrerenderStopLoading(
PrerenderHandle* prerender_handle) {
LinkPrerender* prerender = FindByPrerenderHandle(prerender_handle);
if (!prerender)
return;
chrome::mojom::PrerenderDispatcherAssociatedPtr prerender_dispatcher =
GetPrerenderDispatcher(prerender->launcher_child_id);
if (prerender_dispatcher)
prerender_dispatcher->PrerenderStopLoading(prerender->prerender_id);
}
void PrerenderLinkManager::OnPrerenderDomContentLoaded(
PrerenderHandle* prerender_handle) {
LinkPrerender* prerender = FindByPrerenderHandle(prerender_handle);
if (!prerender)
return;
chrome::mojom::PrerenderDispatcherAssociatedPtr prerender_dispatcher =
GetPrerenderDispatcher(prerender->launcher_child_id);
if (prerender_dispatcher)
prerender_dispatcher->PrerenderDomContentLoaded(prerender->prerender_id);
}
void PrerenderLinkManager::OnPrerenderStop(
PrerenderHandle* prerender_handle) {
LinkPrerender* prerender = FindByPrerenderHandle(prerender_handle);
if (!prerender)
return;
chrome::mojom::PrerenderDispatcherAssociatedPtr prerender_dispatcher =
GetPrerenderDispatcher(prerender->launcher_child_id);
if (prerender_dispatcher)
prerender_dispatcher->PrerenderStop(prerender->prerender_id);
RemovePrerender(prerender);
StartPrerenders();
}
void PrerenderLinkManager::OnPrerenderNetworkBytesChanged(
PrerenderHandle* prerender_handle) {}
} // namespace prerender
| [
"sokolov.p@gmail.com"
] | sokolov.p@gmail.com |
00b64af96e6f79abe8dd36186141c0fb2b3ea788 | 237acec099992ddb5fc8d55f59d7a89b25724350 | /src/AEntities/GraphicEntityManager.cpp | f935c003e910eaf708a3e42845ac55e6e8558051 | [] | no_license | polyeezy/mouillette_indie | dbefe96b6ebf96143e152c95dced7093e75f5d42 | 268084ec43a6f1006399915c3141a6193ba96359 | refs/heads/master | 2021-01-11T06:09:28.384481 | 2016-06-06T21:32:20 | 2016-06-06T21:32:20 | 57,026,638 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,735 | cpp | //
// GraphicEntityManager.cpp for in /home/polyeezy/rendu/CPP/mouillette_indie/src/AEntities
//
// Made by Valérian Polizzi
// Login <polizz_v@epitech.net>
//
// Started on Mon May 30 05:58:38 2016 Valérian Polizzi
// Last update Mon Jun 6 11:30:54 2016 Valérian Polizzi
//
#include <GraphicEntityManager.hh>
GraphicEntityManager::GraphicEntityManager()
{
}
GraphicEntityManager::~GraphicEntityManager()
{
}
irr::scene::IMeshSceneNode *GraphicEntityManager::createMap(const std::string &map)
{
enum
{
ID_IsNotPickable = 0,
IDFlag_IsPickable = 1 << 0,
IDFlag_IsHighlightable = 1 << 1
};
irr::scene::IAnimatedMesh* mesh_map = _scene->getMesh(map.c_str());
// irr::scene::ISceneNode* skydome = _scene->addSkyDomeSceneNode(_driver->getTexture("../../media/skydome.jpg"),16,8,0.95f,2.0f);
return (_scene->addOctreeSceneNode(mesh_map->getMesh(0), 0, IDFlag_IsPickable));
// if (map)
// {
// map->setPosition(irr::core::vector3df(-50,-10,0));
// map->setRotation(irr::core::vector3df(0,180,0));
// map->setMaterialFlag(irr::video::EMF_LIGHTING, false);
// map->setScale(irr::core::vector3df(1.5, 1.5, 1.5));
// }
return (_scene->addCubeSceneNode());
}
irr::scene::ISceneNode *GraphicEntityManager::createCube()
{
return (_scene->addCubeSceneNode());
}
irr::scene::ISceneManager *GraphicEntityManager::getScene()
{
return (_scene);
}
irr::scene::IMeshSceneNode *GraphicEntityManager::createObject(const std::string &path)
{
irr::scene::IMesh *mesh = _scene->getMesh(path.c_str());
if (mesh)
return (_scene->addMeshSceneNode(mesh));
return (NULL);
}
void GraphicEntityManager::setScene(irr::scene::ISceneManager *scene)
{
_scene = scene;
}
| [
"valerian.polizzi@epitech.eu"
] | valerian.polizzi@epitech.eu |
ce9bb75c4341bba37f5a64401968ce184f08b755 | 30bdd8ab897e056f0fb2f9937dcf2f608c1fd06a | /contest/1542580447.cpp | f941677b85b2f0c7d50bbecdcc0738400d203115 | [] | no_license | thegamer1907/Code_Analysis | 0a2bb97a9fb5faf01d983c223d9715eb419b7519 | 48079e399321b585efc8a2c6a84c25e2e7a22a61 | refs/heads/master | 2020-05-27T01:20:55.921937 | 2019-11-20T11:15:11 | 2019-11-20T11:15:11 | 188,403,594 | 2 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 3,465 | cpp | #include<bits/stdc++.h>
#define ll long long int
#define ull unsigned long long int
#define I(a) scanf("%d",&a)
#define I2(a,b) scanf("%d%d",&a,&b)
#define I3(a,b,c) scanf("%d%d%d",&a,&b,&c)
#define L(a) scanf("%lld",&a)
#define L2(a,b) scanf("%lld%lld",&a,&b)
#define L3(a,b,c) scanf("%lld%lld%lld",&a,&b,&c)
#define PI(a) printf("%d",a)
#define PL(a) printf("%lld",a)
#define PT(t) printf("Case %d: ",t)
#define PB push_back
#define x first
#define y second
#define xx first.first
#define xy first.second
#define yx second.first
#define yy second.second
#define SC scanf
#define PC printf
#define NL printf("\n")
#define SET(a) memset(a,0,sizeof a)
#define SETR(a) memset(a,-1,sizeof a)
#define SZ(a) ((int)a.size())-1
#define f(i,a,b) for(int i=a;i<=b; i++)
#define fr(i,a,b) for(int i=a;i<=b; i++)
#define frr(i,a,b) for(int i=a;i>=b; i--)
#define frv(i,a) for(int i=0;i<a.size();i++)
#define pi 2.0*acos(0.0)
#define R(a) freopen(a, "r", stdin);
#define W(a) freopen(a, "w", stdout);
#define CB(x) __builtin_popcount(x)
#define STN(a) stringtonumber<ll>(a)
#define lol printf("BUG\n")
#define Endl "\n"
#define mk make_pair
using namespace std;
template <class T> inline T BM(T p, T e, T M)
{
ll ret = 1;
for(; e > 0; e >>= 1)
{
if(e & 1) ret = (ret * p) % M;
p = (p * p) % M;
}
return (T)ret;
}
template <class T> inline T gcd(T a, T b)
{
if(b == 0)return a;
return gcd(b, a % b);
}
template <class T> inline T mdINV(T a, T M)
{
return BM(a, M - 2, M);
}
template <class T> inline T PW(T p, T e)
{
ll ret = 1;
for(; e > 0; e >>= 1)
{
if(e & 1) ret = (ret * p);
p = (p * p);
}
return (T)ret;
}
template <class T>bool ISLEFT(T a, T b, T c)
{
if(((a.xx - b.xx) * (b.yy - c.yy) - (b.xx - c.xx) * (a.yy - b.yy)) < 0.0)return 1; //Uporer dike //A,b,c, x okkher ordera sorted
else return 0;
}
#define md 2100000007ll
#define mx 200004
#define base 193ll
typedef pair<int,int >P;
//////////////////////////
/////////////////////////
int main()
{
int n,m;
I2(n,m);
int ar[20];
SET(ar);
fr(i,1,n)
{
int num=0;
fr(j,0,m-1)
{
int x;
I(x);
if(x)num|=(1<<j);
}
ar[num]++;
}
if(ar[0]){PC("YES\n");
return 0;
}
else
{
int ara[5];
int ko=(1<<m);
for(int j=1; j<(1<<ko); j++)
{
bool fl=0;
memset(ara,0,sizeof ara);
for(int i=0; i<ko; i++)
{
if((j&(1<<i)))
{
if(!ar[i])fl=1;
for(int l=0; l<m; l++)
{
if((i&(1<<l)))ara[l]++;
}
}
}
if(!fl)
{
int lp=CB(j);
int cl=0;
for(int op=0; op<m; op++)
{
if(ara[op]*2>lp)cl=1;
}
if(!cl)
{
PC("YES\n");
return 0;
}
}
}
}
PC("NO\n");
return 0;
}
| [
"harshitagar1907@gmail.com"
] | harshitagar1907@gmail.com |
096b1959569e2c90b388d1a41d90494f4e33c0e2 | 1f0bb9cef7f824805599c40236a1d68965bf682f | /app/src/main/cpp/Transform.cpp | 43f0fda29e8b1aafa975e3e15a78b163588db8e8 | [
"Apache-2.0"
] | permissive | Da-minHan/android-gles3jni-texturecube | 7282f9b9d1231c40892d7331bd4be594c7c68508 | 4d8c84b9f88ab5949b01fcfe82fbaec84b695089 | refs/heads/master | 2023-03-03T18:53:26.643074 | 2021-02-17T15:43:23 | 2021-02-17T15:43:23 | 338,627,011 | 0 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 9,318 | cpp | // The MIT License (MIT)
//
// Copyright (c) 2013 Dan Ginsburg, Budirijanto Purnomo
//
// 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.
//
// Book: OpenGL(R) ES 3.0 Programming Guide, 2nd Edition
// Authors: Dan Ginsburg, Budirijanto Purnomo, Dave Shreiner, Aaftab Munshi
// ISBN-10: 0-321-93388-5
// ISBN-13: 978-0-321-93388-1
// Publisher: Addison-Wesley Professional
// URLs: http://www.opengles-book.com
// http://my.safaribooksonline.com/book/animation-and-3d/9780133440133
//
// ESUtil.c
//
// A utility library for OpenGL ES. This library provides a
// basic common framework for the example applications in the
// OpenGL ES 3.0 Programming Guide.
//
///
// Includes
//
#include <string.h>
#include "Transform.h"
#define PI 3.1415926535897932384626433832795f
void esScale ( GLfloat result[][4], GLfloat sx, GLfloat sy, GLfloat sz )
{
result[0][0] *= sx;
result[0][1] *= sx;
result[0][2] *= sx;
result[0][3] *= sx;
result[1][0] *= sy;
result[1][1] *= sy;
result[1][2] *= sy;
result[1][3] *= sy;
result[2][0] *= sz;
result[2][1] *= sz;
result[2][2] *= sz;
result[2][3] *= sz;
}
void
esTranslate ( GLfloat result[][4], GLfloat tx, GLfloat ty, GLfloat tz )
{
result[3][0] += ( result[0][0] * tx + result[1][0] * ty + result[2][0] * tz );
result[3][1] += ( result[0][1] * tx + result[1][1] * ty + result[2][1] * tz );
result[3][2] += ( result[0][2] * tx + result[1][2] * ty + result[2][2] * tz );
result[3][3] += ( result[0][3] * tx + result[1][3] * ty + result[2][3] * tz );
}
void
esRotate ( GLfloat result[][4], GLfloat angle, GLfloat x, GLfloat y, GLfloat z )
{
GLfloat sinAngle, cosAngle;
GLfloat mag = sqrtf ( x * x + y * y + z * z );
sinAngle = sinf ( angle * PI / 180.0f );
cosAngle = cosf ( angle * PI / 180.0f );
if ( mag > 0.0f )
{
GLfloat xx, yy, zz, xy, yz, zx, xs, ys, zs;
GLfloat oneMinusCos;
GLfloat rotMat[4][4];
x /= mag;
y /= mag;
z /= mag;
xx = x * x;
yy = y * y;
zz = z * z;
xy = x * y;
yz = y * z;
zx = z * x;
xs = x * sinAngle;
ys = y * sinAngle;
zs = z * sinAngle;
oneMinusCos = 1.0f - cosAngle;
rotMat[0][0] = ( oneMinusCos * xx ) + cosAngle;
rotMat[0][1] = ( oneMinusCos * xy ) - zs;
rotMat[0][2] = ( oneMinusCos * zx ) + ys;
rotMat[0][3] = 0.0F;
rotMat[1][0] = ( oneMinusCos * xy ) + zs;
rotMat[1][1] = ( oneMinusCos * yy ) + cosAngle;
rotMat[1][2] = ( oneMinusCos * yz ) - xs;
rotMat[1][3] = 0.0F;
rotMat[2][0] = ( oneMinusCos * zx ) - ys;
rotMat[2][1] = ( oneMinusCos * yz ) + xs;
rotMat[2][2] = ( oneMinusCos * zz ) + cosAngle;
rotMat[2][3] = 0.0F;
rotMat[3][0] = 0.0F;
rotMat[3][1] = 0.0F;
rotMat[3][2] = 0.0F;
rotMat[3][3] = 1.0F;
esMatrixMultiply (result, rotMat, result );
}
}
void
esFrustum ( GLfloat result[][4], float left, float right, float bottom, float top, float nearZ, float farZ )
{
float deltaX = right - left;
float deltaY = top - bottom;
float deltaZ = farZ - nearZ;
GLfloat frust[4][4];
if ( ( nearZ <= 0.0f ) || ( farZ <= 0.0f ) ||
( deltaX <= 0.0f ) || ( deltaY <= 0.0f ) || ( deltaZ <= 0.0f ) )
{
return;
}
frust[0][0] = 2.0f * nearZ / deltaX;
frust[0][1] = frust[0][2] = frust[0][3] = 0.0f;
frust[1][1] = 2.0f * nearZ / deltaY;
frust[1][0] = frust[1][2] = frust[1][3] = 0.0f;
frust[2][0] = ( right + left ) / deltaX;
frust[2][1] = ( top + bottom ) / deltaY;
frust[2][2] = - ( nearZ + farZ ) / deltaZ;
frust[2][3] = -1.0f;
frust[3][2] = -2.0f * nearZ * farZ / deltaZ;
frust[3][0] = frust[3][1] = frust[3][3] = 0.0f;
esMatrixMultiply ( result, frust, result );
}
void
esPerspective ( GLfloat result[][4], float fovy, float aspect, float nearZ, float farZ )
{
GLfloat frustumW, frustumH;
frustumH = tanf ( fovy / 360.0f * PI ) * nearZ;
frustumW = frustumH * aspect;
esFrustum ( result, -frustumW, frustumW, -frustumH, frustumH, nearZ, farZ );
}
void
esOrtho ( GLfloat result[][4], float left, float right, float bottom, float top, float nearZ, float farZ )
{
float deltaX = right - left;
float deltaY = top - bottom;
float deltaZ = farZ - nearZ;
GLfloat ortho[4][4];
if ( ( deltaX == 0.0f ) || ( deltaY == 0.0f ) || ( deltaZ == 0.0f ) )
{
return;
}
esMatrixLoadIdentity ( ortho );
ortho[0][0] = 2.0f / deltaX;
ortho[3][0] = - ( right + left ) / deltaX;
ortho[1][1] = 2.0f / deltaY;
ortho[3][1] = - ( top + bottom ) / deltaY;
ortho[2][2] = -2.0f / deltaZ;
ortho[3][2] = - ( nearZ + farZ ) / deltaZ;
esMatrixMultiply ( result, ortho, result );
}
void
esMatrixLookAt ( GLfloat result[][4],
float posX, float posY, float posZ,
float lookAtX, float lookAtY, float lookAtZ,
float upX, float upY, float upZ )
{
float axisX[3], axisY[3], axisZ[3];
float length;
// axisZ = lookAt - pos
axisZ[0] = lookAtX - posX;
axisZ[1] = lookAtY - posY;
axisZ[2] = lookAtZ - posZ;
// normalize axisZ
length = sqrtf ( axisZ[0] * axisZ[0] + axisZ[1] * axisZ[1] + axisZ[2] * axisZ[2] );
if ( length != 0.0f )
{
axisZ[0] /= length;
axisZ[1] /= length;
axisZ[2] /= length;
}
// axisX = up X axisZ
axisX[0] = upY * axisZ[2] - upZ * axisZ[1];
axisX[1] = upZ * axisZ[0] - upX * axisZ[2];
axisX[2] = upX * axisZ[1] - upY * axisZ[0];
// normalize axisX
length = sqrtf ( axisX[0] * axisX[0] + axisX[1] * axisX[1] + axisX[2] * axisX[2] );
if ( length != 0.0f )
{
axisX[0] /= length;
axisX[1] /= length;
axisX[2] /= length;
}
// axisY = axisZ x axisX
axisY[0] = axisZ[1] * axisX[2] - axisZ[2] * axisX[1];
axisY[1] = axisZ[2] * axisX[0] - axisZ[0] * axisX[2];
axisY[2] = axisZ[0] * axisX[1] - axisZ[1] * axisX[0];
// normalize axisY
length = sqrtf ( axisY[0] * axisY[0] + axisY[1] * axisY[1] + axisY[2] * axisY[2] );
if ( length != 0.0f )
{
axisY[0] /= length;
axisY[1] /= length;
axisY[2] /= length;
}
memset ( result, 0x0, sizeof ( GLfloat ) * 16 );
result[0][0] = -axisX[0];
result[0][1] = axisY[0];
result[0][2] = -axisZ[0];
result[1][0] = -axisX[1];
result[1][1] = axisY[1];
result[1][2] = -axisZ[1];
result[2][0] = -axisX[2];
result[2][1] = axisY[2];
result[2][2] = -axisZ[2];
// translate (-posX, -posY, -posZ)
result[3][0] = axisX[0] * posX + axisX[1] * posY + axisX[2] * posZ;
result[3][1] = -axisY[0] * posX - axisY[1] * posY - axisY[2] * posZ;
result[3][2] = axisZ[0] * posX + axisZ[1] * posY + axisZ[2] * posZ;
result[3][3] = 1.0f;
}
void
esMatrixMultiply ( GLfloat result[][4], GLfloat srcA[][4], GLfloat srcB[][4] )
{
GLfloat tmp[4][4];
int i;
for ( i = 0; i < 4; i++ )
{
tmp[i][0] = ( srcA[i][0] * srcB[0][0] ) +
( srcA[i][1] * srcB[1][0] ) +
( srcA[i][2] * srcB[2][0] ) +
( srcA[i][3] * srcB[3][0] ) ;
tmp[i][1] = ( srcA[i][0] * srcB[0][1] ) +
( srcA[i][1] * srcB[1][1] ) +
( srcA[i][2] * srcB[2][1] ) +
( srcA[i][3] * srcB[3][1] ) ;
tmp[i][2] = ( srcA[i][0] * srcB[0][2] ) +
( srcA[i][1] * srcB[1][2] ) +
( srcA[i][2] * srcB[2][2] ) +
( srcA[i][3] * srcB[3][2] ) ;
tmp[i][3] = ( srcA[i][0] * srcB[0][3] ) +
( srcA[i][1] * srcB[1][3] ) +
( srcA[i][2] * srcB[2][3] ) +
( srcA[i][3] * srcB[3][3] ) ;
}
memcpy ( result, tmp, sizeof ( GLfloat ) * 16 );
}
void
esMatrixLoadIdentity ( GLfloat result[][4] )
{
memset ( result, 0x0, sizeof ( GLfloat ) * 16 );
result[0][0] = 1.0f;
result[1][1] = 1.0f;
result[2][2] = 1.0f;
result[3][3] = 1.0f;
} | [
"handa7289@gmail.com"
] | handa7289@gmail.com |
165da4abd4f993eb027567a3e8f025fc364ba656 | 89dedd7f3c7acc81d12e2bcb2e716f9af9e5fa04 | /chrome/browser/extensions/api/management/chrome_management_api_delegate.h | 4140ee93e1e8266f3dcad4ddf9efc5b0703442ab | [
"BSD-3-Clause"
] | permissive | bino7/chromium | 8d26f84a1b6e38a73d1b97fea6057c634eff68cb | 4666a6bb6fdcb1114afecf77bdaa239d9787b752 | refs/heads/master | 2022-12-22T14:31:53.913081 | 2016-09-06T10:05:11 | 2016-09-06T10:05:11 | 67,410,510 | 1 | 3 | BSD-3-Clause | 2022-12-17T03:08:52 | 2016-09-05T10:11:59 | null | UTF-8 | C++ | false | false | 3,729 | h | // Copyright 2014 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#ifndef CHROME_BROWSER_EXTENSIONS_API_MANAGEMENT_CHROME_MANAGEMENT_API_DELEGATE_H_
#define CHROME_BROWSER_EXTENSIONS_API_MANAGEMENT_CHROME_MANAGEMENT_API_DELEGATE_H_
#include "base/task/cancelable_task_tracker.h"
#include "chrome/browser/extensions/extension_install_prompt.h"
#include "chrome/browser/extensions/extension_uninstall_dialog.h"
#include "extensions/browser/api/management/management_api_delegate.h"
namespace favicon_base {
struct FaviconImageResult;
} // namespace favicon_base
class ChromeManagementAPIDelegate : public extensions::ManagementAPIDelegate {
public:
ChromeManagementAPIDelegate();
~ChromeManagementAPIDelegate() override;
// ManagementAPIDelegate.
void LaunchAppFunctionDelegate(
const extensions::Extension* extension,
content::BrowserContext* context) const override;
GURL GetFullLaunchURL(const extensions::Extension* extension) const override;
extensions::LaunchType GetLaunchType(
const extensions::ExtensionPrefs* prefs,
const extensions::Extension* extension) const override;
void GetPermissionWarningsByManifestFunctionDelegate(
extensions::ManagementGetPermissionWarningsByManifestFunction* function,
const std::string& manifest_str) const override;
std::unique_ptr<extensions::InstallPromptDelegate> SetEnabledFunctionDelegate(
content::WebContents* web_contents,
content::BrowserContext* browser_context,
const extensions::Extension* extension,
const base::Callback<void(bool)>& callback) const override;
std::unique_ptr<extensions::RequirementsChecker> CreateRequirementsChecker()
const override;
std::unique_ptr<extensions::UninstallDialogDelegate>
UninstallFunctionDelegate(
extensions::ManagementUninstallFunctionBase* function,
const extensions::Extension* target_extension,
bool show_programmatic_uninstall_ui) const override;
bool CreateAppShortcutFunctionDelegate(
extensions::ManagementCreateAppShortcutFunction* function,
const extensions::Extension* extension) const override;
std::unique_ptr<extensions::AppForLinkDelegate>
GenerateAppForLinkFunctionDelegate(
extensions::ManagementGenerateAppForLinkFunction* function,
content::BrowserContext* context,
const std::string& title,
const GURL& launch_url) const override;
bool CanHostedAppsOpenInWindows() const override;
bool IsNewBookmarkAppsEnabled() const override;
void EnableExtension(content::BrowserContext* context,
const std::string& extension_id) const override;
void DisableExtension(
content::BrowserContext* context,
const std::string& extension_id,
extensions::Extension::DisableReason disable_reason) const override;
bool UninstallExtension(content::BrowserContext* context,
const std::string& transient_extension_id,
extensions::UninstallReason reason,
const base::Closure& deletion_done_callback,
base::string16* error) const override;
void SetLaunchType(content::BrowserContext* context,
const std::string& extension_id,
extensions::LaunchType launch_type) const override;
GURL GetIconURL(const extensions::Extension* extension,
int icon_size,
ExtensionIconSet::MatchType match,
bool grayscale,
bool* exists) const override;
};
#endif // CHROME_BROWSER_EXTENSIONS_API_MANAGEMENT_CHROME_MANAGEMENT_API_DELEGATE_H_
| [
"bino.zh@gmail.com"
] | bino.zh@gmail.com |
9c795ee75d773fecc1d57b6db89fe80ed6b40504 | 41bf5ab42b2e29c20dda2eef9d073cbc6eb4ea5e | /md3dframework/InputListener.h | 1e93a7c6ae6c6eaad7ee3f3ab546a18ab2dd7f25 | [] | no_license | mvdgaag/D3D | 954078a7e0dbd7c647a4d111304157863e37ec90 | 26275e0b032ff585ac4beb75caff8a2f6e567aca | refs/heads/master | 2020-04-06T07:04:03.835089 | 2017-07-15T19:55:31 | 2017-07-15T19:55:31 | 43,242,562 | 2 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 743 | h | #pragma once
#include "GaagCommon.h"
#include "Input.h"
REGISTERCLASS(InputListener);
class InputListener
{
public:
explicit InputListener() { theInput.RegisterListener(this); }
virtual ~InputListener() { theInput.UnRegisterListener(this); }
virtual void OnKeyDown(unsigned int inKey) { UNREFERENCED_PARAMETER(inKey); }
virtual void OnKeyUp(unsigned int inKey) { UNREFERENCED_PARAMETER(inKey); }
virtual void OnMouseMove(float2 inCurrentCoord, float2 inPrevCoord) { UNREFERENCED_PARAMETER(inCurrentCoord); UNREFERENCED_PARAMETER(inPrevCoord); }
virtual void OnMouseDown(int inButton) { UNREFERENCED_PARAMETER(inButton); }
virtual void OnMouseUp(int inButton) { UNREFERENCED_PARAMETER(inButton); }
};
| [
"maarten.van.der.gaag@gmail.com"
] | maarten.van.der.gaag@gmail.com |
9ee72a3e56b3001c3a123396077db6a389f7ebfa | 304ef9ff301d97451d01ed44e145a974ecf8ff87 | /leetcode/203-remove-linked-list-elements.cpp | 4193b8451a777025416304f692e501dbb3d392a0 | [] | no_license | hartaacme/competitive-programming | eafb8d6ca09b000d2a6207e8e7f915742b440b79 | 0f77cb0c2240e687ce7813b4f5bf79a4d9828715 | refs/heads/master | 2021-01-17T15:55:03.735973 | 2016-07-12T06:52:47 | 2016-07-12T06:52:47 | 57,095,232 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 509 | cpp | /**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution {
public:
ListNode* removeElements(ListNode* head, int val) {
while (head && head->val == val) {
head = head->next;
}
if (head == NULL) return head;
ListNode *curr = head;
while (curr->next) {
if (curr->next->val == val) curr->next = curr->next->next;
else curr = curr->next;
}
return head;
}
};
| [
"wijayaha@garena.com"
] | wijayaha@garena.com |
912207ae47a0d6f3381398216d9a415ad8b1e119 | 370aa8b7d58d20bf02dbc7c32510b87bee872759 | /testsrc/configtest.cc | be3a8a46f5101f0a888a300ded6166f452c8dec1 | [] | no_license | tlvb/dmx512usb_software | f61d9fbfa403ba71f88ecf1d06db9eb83570ca3f | 5eabf8d6fc8a602c0ed116feec195749d509624b | refs/heads/master | 2020-05-27T19:38:43.656248 | 2012-08-20T20:47:00 | 2012-08-20T20:47:00 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 431 | cc | #include "config.hh"
#include <iostream>
using namespace std;
using namespace dmx512usb_software;
int main(void) {
Config c;
if (c.get_device().compare("/dev/ttyUSB0") != 0) {
cout << "c.get_device() does does not equal expected value" << endl;
cout << "expected: \"/dev/ttyUSB0\"" << endl;
cout << "actual: \"" << c.get_device() << "\"" << endl;
return 1;
}
cout << "configtest success" << endl;
return 0;
}
| [
"leo.barring@gmail.com"
] | leo.barring@gmail.com |
25fee3b5917604de4088248873dec5c74e1ab913 | 5c77807c8a39658e995c00adecb5f9e3bde0884d | /DataStructures/Vector/main.cpp | 849141fdf730dd9922f5e3d6837abd844f6426e3 | [] | no_license | starlitnext/practice | 6a39b116213caaf014875b32d048ff5f2d6ca190 | 3d1be394c7c7cc444a10cfd878caacb2f592b653 | refs/heads/master | 2021-01-18T21:33:09.692397 | 2018-01-24T15:23:25 | 2018-01-24T15:23:25 | 40,886,119 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 473 | cpp | #include <iostream>
#include "Vector.h"
using namespace std;
int main() {
Vector<double> v1(10, 0);
cout << v1.size() << endl;
cout << v1.capacity() << endl;
for (int i = 0; i < 10; i++)
v1.push_back(i);
cout << v1.size() << endl;
cout << v1.capacity() << endl;
v1.resize(20);
cout << v1.size() << endl;
cout << v1.capacity() << endl;
Vector<double> v2(v1);
for (auto it = v2.begin(); it != v2.end(); it++)
cout << *it << " ";
cout << endl;
return 0;
} | [
"vipxxq@foxmail.com"
] | vipxxq@foxmail.com |
ca902ad76562670fa57749832583bb07539b0634 | 76b7e459b143c8481b044c60a68c768a0848b8f6 | /Codeforces/Round570/A.cpp | 7a33fbf9abb5c35ea39880db5f49f2e0e870fed0 | [] | no_license | hsnavarro/imepp | f3b195e5ed4e453eac9b73d5a77b39f44917435f | eb90580caea91b48e7d541db92531ba3fd2b82c1 | refs/heads/master | 2021-11-28T07:25:05.778476 | 2021-09-10T02:20:32 | 2021-09-10T02:20:32 | 145,646,296 | 0 | 1 | null | 2021-09-10T02:20:33 | 2018-08-22T02:40:54 | C++ | UTF-8 | C++ | false | false | 446 | cpp | #include <bits/stdc++.h>
using namespace std;
const int INF = 0x3f3f3f3f;
#define st first
#define nd second
typedef pair<int, int> pii;
typedef long long ll;
const ll LINF = 0x3f3f3f3f3f3f3f3f;
int n;
bool check(int n){
string s = to_string(n);
int sum = 0;
for(auto x : s) sum += (x - '0');
return sum % 4 == 0;
}
int main(){
ios_base::sync_with_stdio(0), cin.tie(0);
cin >> n;
while(!check(n)) n++;
cout << n << "\n";
}
| [
"ricksnavarro@gmail.com"
] | ricksnavarro@gmail.com |
86a881bdf6dea9b3cbf97ea3120d14f5500d45d2 | 0c52896b835655e23421a1fbe50bbe391a5df75c | /Spark-Auth/cpp-Loader/http/utils.cpp | 589d2d1940ebfa63d36c27f86d9767b1fb16dfc1 | [] | no_license | RyzeGen/PastedAuth | 47d3c493154d51b767acc31c1defa4cebf47f336 | 01adc70867942bedc4bee8e78f8ffb1db864e38e | refs/heads/main | 2023-01-20T06:13:03.266814 | 2020-11-29T21:52:17 | 2020-11-29T21:52:17 | 317,049,294 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 7,091 | cpp | // This file is part of the "requests" project, https://github.com/Code-Building/requests
// (c) 2018 Code Building https://codebuilding.org
//
// Licensed under the MIT 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/MIT
#include "utils.h"
/*This namespace is responsible of utilities on processing sockets HTTP responses and their data*/
namespace ReqUtils
{
// Split function will receive a string and a char. The character will be responsible by
// the separator between strings of the given string.
// the first step is to loop a function while a given character exists in the given string
// then, in that function, if the char was found, it assigns a index value to it.
// with that value, we can use substring to get the value between the last found index and
// actual found index - last found index.
// (last found index will be actual found index+1 at the iteration end)
// after that loop, we also need to return the value between last found index and actual
// found index - last found index to ensure that strings like
// a:b with the separator ':' return a & b.
// we can visualize that with:
// std::string x = "Hi:How:Are:You"; const char separator = ':';
// first loop iteration, found separator at index 2, the substr will be substr(0, (2-0));
// resulting in "Hi" pushed onto output vector
// second loop iteration, found separator at index 6, the substr will be substr(3, (6-3));
// resulting in "How" pushed onto output vector
// the loop will remains until all separators got consumed.
// in this case, at "Are" since "You" don't have ':' at the end.
// as we need to cover "You" also, we do a last substring bewteen last ':' index and string end.
// and push it onto vector.
std::vector<std::string> split(const std::string& str, const char seperator)
{
std::vector<std::string> output;
std::string::size_type prev_pos = 0, pos = 0;
while ((pos = str.find(seperator, pos)) != std::string::npos)
{
auto substring(str.substr(prev_pos, pos - prev_pos));
output.push_back(substring);
prev_pos = ++pos;
}
output.push_back(str.substr(prev_pos, pos - prev_pos));
return output;
}
std::string serial()
{
DWORD lVolSerialNbr = 0;
char sHDSerial[255] = "";
GetVolumeInformationA("C:\\", 0, 0, &lVolSerialNbr, 0, 0, 0, NULL);
_ultoa_s(lVolSerialNbr, sHDSerial, 10);
std::string c(sHDSerial);
return c;
}
// Parse Headers function will recieve a map of two std::string's and then check
// if crucial headers is included in that map, if not, it will include automatically
// this is solved by looping through all given map keys and values and checking each
// of them.
std::map<std::string, std::string> parse_headers(std::map<std::string, std::string> h_map, const DWORD verb)
{
if (!h_map.count("Content-Type") && verb == 2)
{
h_map["Content-Type"] = "application/x-www-form-urlencoded";
}
if (!h_map.count("User-Agent"))
{
h_map["User-Agent"] = "Requests 2.0";
}
return h_map;
}
// Parse Response Headers function will recieve a raw std::string of response headers
// a valid http response should start with
// HTTP/N.N STATUS CODE
// so let's deal with it.
// we simply do a 8 characters -to- the first CLRF index substring to retrieve
// the response code.
// then, we can just apply the split function logic to get all headers between CLRF
std::map<std::string, std::string> parse_res_headers(std::string raw_headers)
{
std::map<std::string, std::string> formatted;
const auto x = string_index(raw_headers, "\r\n");
auto http_res = raw_headers.substr(8, x - 8);
http_res.erase(0, 1);
formatted["Status"] = http_res;
raw_headers = raw_headers.substr(x);
while (string_index(raw_headers, "\r\n") != -1)
{
raw_headers = raw_headers.substr(string_index(raw_headers, "\r\n") + 2);
const auto delimeter = string_index(raw_headers, ":");
auto value = return_between(raw_headers, ":", "\r\n");
value.erase(0, 1);
const auto header = raw_headers.substr(0, delimeter);
formatted[header] = value;
}
return formatted;
}
// To LPCWSTR function will take a const char* and
// then translate it into const wchar_t* aka LPCWSTR
LPCWSTR to_lpcwstr(const char* text)
{
const auto size = strlen(text) + 1;
auto* wtext = new wchar_t[size];
size_t out_size;
mbstowcs_s(&out_size, wtext, size, text, size - 1);
return wtext;
}
// Populate URI function, will take a string, split it
// with '/' delimeter, skip the first index(hostname)
// and then re-create the URL requested path
std::string populate_uri(const std::string& content)
{
std::string uri;
auto array = split(content, '/');
for (auto i = 1; array.size() > i; i++)
uri += "/" + array[i];
return uri;
}
// Generate Post function will take a std::map<std::string,std::string>
// then create a post payload string with each of it values.
std::string generate_post(http::post_data pdata_map)
{
std::string generated;
for (auto& it : pdata_map)
generated += it.first + "=" + it.second + "&";
generated.pop_back();
return generated;
}
// Return Between function will take a string and two delimeters to
// search for which string is between those two delimeters.
// first, it will search for the index of first delimeter then
// store the length of that first delimeter, make a new variable
// with substring on the end of first delimeter length and just
// find the pos of second delimeter to use substring with
// the substring of frist delimeter -to- last delimeter position.
std::string return_between(const std::string& s, const std::string& start_delim, const std::string& stop_delim)
{
const auto first_delim_pos = s.find(start_delim);
const auto end_pos_of_first_delim = first_delim_pos + start_delim.length();
auto fixed_next_search = s.substr(end_pos_of_first_delim);
const auto last_delim_pos = fixed_next_search.find(stop_delim);
return fixed_next_search.substr(0,
last_delim_pos);
}
// Starts with function checks if a N string is at position 0
// of string X.
bool starts_with(const std::string& str, const std::string& who)
{
return str.rfind(who, 0) == 0;
}
// String Index function will return a N string position at
// a string X.
int string_index(const std::string& str, const std::string& who)
{
return str.find(who);
}
std::string encrypt_str(std::string vulstr)
{
auto v_str = vulstr;
uint8_t doinc = 0;
for (size_t i = 0; i < vulstr.length(); i++)
{
if (doinc == 5) doinc = 0;
*reinterpret_cast<uint8_t*>(&v_str[i]) = *reinterpret_cast<uint8_t*>(&vulstr[i]) + doinc;
doinc++;
}
return v_str;
}
std::string decrypt_str(std::string vulstr)
{
auto v_str = vulstr;
uint8_t doinc = 0;
for (size_t i = 0; i < vulstr.length(); i++)
{
if (doinc == 5) doinc = 0;
*reinterpret_cast<uint8_t*>(&v_str[i]) = *reinterpret_cast<uint8_t*>(&vulstr[i]) - doinc;
doinc++;
}
return v_str;
}
}
| [
"noreply@github.com"
] | RyzeGen.noreply@github.com |
7071db0db32dea4f337dafad1a521ffb7272c0d1 | 2c347933a7c0baf41689167a82922f457e809bcb | /sphlib/system/common/CellIndices.h | aff24c3309b83d42143bc157e17c15b5e7a8fcbc | [] | no_license | shibing/fluid | 4173380401ddce6a94bba5857a02bf180131b15a | 23c19927f393234139e9243b56cb2ad995a2f2d8 | refs/heads/master | 2020-04-17T08:29:22.797889 | 2014-11-23T13:09:07 | 2014-11-23T13:09:07 | 25,852,296 | 5 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 725 | h |
#ifndef RTPS_CELLINDICES_H_INCLUDED
#define RTPS_CELLINDICES_H_INCLUDED
#include <RTPS.h>
#include <Buffer.h>
namespace rtps
{
class CellIndices
{
public:
CellIndices() { cli = NULL; }
CellIndices(const std::string& path, CL* cli);
int execute(int num,
Buffer<unsigned int>& hashes,
Buffer<unsigned int>& ci_start,
Buffer<unsigned int>& ci_stop,
Buffer<GridParams>& gp,
int nb_cells,
Buffer<float4>& clf_debug,
Buffer<int4>& cli_debug);
private:
CL* cli;
Kernel k_cellindices;
};
}
#endif
| [
"shibing.sw@gmail.com"
] | shibing.sw@gmail.com |
640ef8237b51d26f621b5a0cc0b79fc5f943a67f | d96333ca6eb18677c2579c1114fb047cc799bf13 | /aoj0232.cpp | c9e6b147c3cbea116a8616994710cc08ec2fef62 | [] | no_license | zaburo-ch/icpc_practice | e8fe735857689f685ea86435346963731f5dcd18 | fc275c0d0a0b8feba786059fa1f571563d8e432e | refs/heads/master | 2021-01-19T05:03:31.891988 | 2015-06-28T17:39:00 | 2015-06-28T17:39:00 | 21,899,426 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,717 | cpp | #include <iostream>
#include <stdio.h>
#include <sstream>
#include <string>
#include <vector>
#include <map>
#include <queue>
#include <algorithm>
#include <set>
#include <math.h>
#include <utility>
#include <stack>
#include <string.h>
#include <complex>
using namespace std;
const int INF = 1<<29;
const double EPS = 1e-5;
typedef vector<int> vec;
typedef pair<int,int> P;
struct edge{int to,cost;};
const int MAX_J = 5001;
int X,Y,Z;
int V[4];
int event[51];
int event_A[51];
double dp[51][MAX_J];
int main(){
while(1){
scanf("%d%d%d",&X,&Y,&Z);
if(!X)break;
for(int i=0;i<X;i++){
scanf("%d",&V[i]);
}
fill(event,event+Y+1,0);
for(int i=0;i<Z;i++){
int N,E,A;
scanf("%d%d%d",&N,&E,&A);
event[N] = E;
event_A[N] = A;
}
for(int i=0;i<Y+1;i++){
for(int j=0;j<MAX_J;j++){
dp[i][j] = 0;
}
}
dp[0][0] = 1;
for(int i=0;i<Y;i++){
for(int j=0;j<MAX_J;j++){
for(int k=0;k<X;k++){
int ni = min(Y, i+V[k]), nj = j;
if(event[ni]==1){
ni = min(Y, ni+event_A[ni]);
}else if(event[ni]==2){
nj += event_A[ni];
}else if(event[ni]==3){
nj = max(0, j-event_A[ni]);
}
dp[ni][nj] += dp[i][j] / X;
}
}
}
double ans = 0;
for(int j=1;j<MAX_J;j++){
ans += j*dp[Y][j];
}
printf("%d\n", (int)(ans+EPS));
//break;
}
return 0;
}
| [
"musharna000@gmail.com"
] | musharna000@gmail.com |
9542088c3d3fe5f00bff4b9ac46c660ee6e907dc | e1bafb9c94db3a6cfd86ce4b3a641e79583220b3 | /leetcode-clion/leetcode-problems/cpp/805.split-array-with-same-average.cpp | ede57023a8b404c948a30239146226dc7b2caabc | [] | no_license | lightjameslyy/lt-cpp | 055b0245ba9cc4608db6a0d08dc081d1c2766ba2 | 525c3f0fbeb4b112361a6650bf3ef445fdb61e2c | refs/heads/master | 2021-07-09T08:32:24.405308 | 2020-06-08T08:45:10 | 2020-06-08T08:45:10 | 128,907,003 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,006 | cpp | /*
* @lc app=leetcode id=805 lang=cpp
*
* [805] Split Array With Same Average
*
* https://leetcode.com/problems/split-array-with-same-average/description/
*
* algorithms
* Hard (25.21%)
* Total Accepted: 11.4K
* Total Submissions: 45.2K
* Testcase Example: '[1,2,3,4,5,6,7,8]'
*
* In a given integer array A, we must move every element of A to either list B
* or list C. (B and C initially start empty.)
*
* Return true if and only if after such a move, it is possible that the
* average value of B is equal to the average value of C, and B and C are both
* non-empty.
*
*
* Example :
* Input:
* [1,2,3,4,5,6,7,8]
* Output: true
* Explanation: We can split the array into [1,4,5,8] and [2,3,6,7], and both
* of them have the average of 4.5.
*
*
* Note:
*
*
* The length of A will be in the range [1, 30].
* A[i] will be in the range of [0, 10000].
*
*
*
*
*/
class Solution {
public:
bool splitArraySameAverage(vector<int>& A) {
}
};
| [
"lightjameslyy@gmail.com"
] | lightjameslyy@gmail.com |
ed7c679d7382443a228fce5f7f34b9dd1950409e | 077810b41a92310c6325300a7442e3cef28d1c55 | /lib/xtl/test/test_xfunctional.cpp | db4c8ae3dff6efac3794a36943e530ba444d9023 | [
"MIT",
"BSD-3-Clause"
] | permissive | mjgalindo/VoxSurf | eab0412dd24b2695420911becb5851456c689382 | 6218a73da4acbf0db0895b9204846a19c23ba1c0 | refs/heads/master | 2022-09-06T05:17:47.734479 | 2020-06-01T18:54:08 | 2020-06-01T18:54:08 | 261,152,584 | 1 | 4 | MIT | 2020-05-04T11:13:41 | 2020-05-04T11:13:40 | null | UTF-8 | C++ | false | false | 863 | cpp | /***************************************************************************
* Copyright (c) Johan Mabille, Sylvain Corlay and Wolf Vollprecht *
* Copyright (c) QuantStack *
* *
* Distributed under the terms of the BSD 3-Clause License. *
* *
* The full license is in the file LICENSE, distributed with this software. *
****************************************************************************/
#include "xtl/xfunctional.hpp"
#include "gtest/gtest.h"
#include "xtl/xoptional.hpp"
namespace xtl
{
TEST(xfunctional, select_scalar)
{
EXPECT_EQ(select(true, 2., 3.), 2.);
EXPECT_EQ(select(false, 2., 3.), 3.);
}
}
| [
"38547166+toomb-raider@users.noreply.github.com"
] | 38547166+toomb-raider@users.noreply.github.com |
4534841781d88142aa184985c163cc2c6e41779d | 3ff1fe3888e34cd3576d91319bf0f08ca955940f | /cdwch/src/v20200915/model/DestroyInstanceResponse.cpp | 30694b76df35e21c4f2917a8ee1a1947248c6676 | [
"Apache-2.0"
] | permissive | TencentCloud/tencentcloud-sdk-cpp | 9f5df8220eaaf72f7eaee07b2ede94f89313651f | 42a76b812b81d1b52ec6a217fafc8faa135e06ca | refs/heads/master | 2023-08-30T03:22:45.269556 | 2023-08-30T00:45:39 | 2023-08-30T00:45:39 | 188,991,963 | 55 | 37 | Apache-2.0 | 2023-08-17T03:13:20 | 2019-05-28T08:56:08 | C++ | UTF-8 | C++ | false | false | 5,584 | cpp | /*
* Copyright (c) 2017-2019 THL A29 Limited, a Tencent company. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include <tencentcloud/cdwch/v20200915/model/DestroyInstanceResponse.h>
#include <tencentcloud/core/utils/rapidjson/document.h>
#include <tencentcloud/core/utils/rapidjson/writer.h>
#include <tencentcloud/core/utils/rapidjson/stringbuffer.h>
using TencentCloud::CoreInternalOutcome;
using namespace TencentCloud::Cdwch::V20200915::Model;
using namespace std;
DestroyInstanceResponse::DestroyInstanceResponse() :
m_flowIDHasBeenSet(false),
m_instanceIDHasBeenSet(false),
m_errorMsgHasBeenSet(false)
{
}
CoreInternalOutcome DestroyInstanceResponse::Deserialize(const string &payload)
{
rapidjson::Document d;
d.Parse(payload.c_str());
if (d.HasParseError() || !d.IsObject())
{
return CoreInternalOutcome(Core::Error("response not json format"));
}
if (!d.HasMember("Response") || !d["Response"].IsObject())
{
return CoreInternalOutcome(Core::Error("response `Response` is null or not object"));
}
rapidjson::Value &rsp = d["Response"];
if (!rsp.HasMember("RequestId") || !rsp["RequestId"].IsString())
{
return CoreInternalOutcome(Core::Error("response `Response.RequestId` is null or not string"));
}
string requestId(rsp["RequestId"].GetString());
SetRequestId(requestId);
if (rsp.HasMember("Error"))
{
if (!rsp["Error"].IsObject() ||
!rsp["Error"].HasMember("Code") || !rsp["Error"]["Code"].IsString() ||
!rsp["Error"].HasMember("Message") || !rsp["Error"]["Message"].IsString())
{
return CoreInternalOutcome(Core::Error("response `Response.Error` format error").SetRequestId(requestId));
}
string errorCode(rsp["Error"]["Code"].GetString());
string errorMsg(rsp["Error"]["Message"].GetString());
return CoreInternalOutcome(Core::Error(errorCode, errorMsg).SetRequestId(requestId));
}
if (rsp.HasMember("FlowID") && !rsp["FlowID"].IsNull())
{
if (!rsp["FlowID"].IsString())
{
return CoreInternalOutcome(Core::Error("response `FlowID` IsString=false incorrectly").SetRequestId(requestId));
}
m_flowID = string(rsp["FlowID"].GetString());
m_flowIDHasBeenSet = true;
}
if (rsp.HasMember("InstanceID") && !rsp["InstanceID"].IsNull())
{
if (!rsp["InstanceID"].IsString())
{
return CoreInternalOutcome(Core::Error("response `InstanceID` IsString=false incorrectly").SetRequestId(requestId));
}
m_instanceID = string(rsp["InstanceID"].GetString());
m_instanceIDHasBeenSet = true;
}
if (rsp.HasMember("ErrorMsg") && !rsp["ErrorMsg"].IsNull())
{
if (!rsp["ErrorMsg"].IsString())
{
return CoreInternalOutcome(Core::Error("response `ErrorMsg` IsString=false incorrectly").SetRequestId(requestId));
}
m_errorMsg = string(rsp["ErrorMsg"].GetString());
m_errorMsgHasBeenSet = true;
}
return CoreInternalOutcome(true);
}
string DestroyInstanceResponse::ToJsonString() const
{
rapidjson::Document value;
value.SetObject();
rapidjson::Document::AllocatorType& allocator = value.GetAllocator();
if (m_flowIDHasBeenSet)
{
rapidjson::Value iKey(rapidjson::kStringType);
string key = "FlowID";
iKey.SetString(key.c_str(), allocator);
value.AddMember(iKey, rapidjson::Value(m_flowID.c_str(), allocator).Move(), allocator);
}
if (m_instanceIDHasBeenSet)
{
rapidjson::Value iKey(rapidjson::kStringType);
string key = "InstanceID";
iKey.SetString(key.c_str(), allocator);
value.AddMember(iKey, rapidjson::Value(m_instanceID.c_str(), allocator).Move(), allocator);
}
if (m_errorMsgHasBeenSet)
{
rapidjson::Value iKey(rapidjson::kStringType);
string key = "ErrorMsg";
iKey.SetString(key.c_str(), allocator);
value.AddMember(iKey, rapidjson::Value(m_errorMsg.c_str(), allocator).Move(), allocator);
}
rapidjson::Value iKey(rapidjson::kStringType);
string key = "RequestId";
iKey.SetString(key.c_str(), allocator);
value.AddMember(iKey, rapidjson::Value().SetString(GetRequestId().c_str(), allocator), allocator);
rapidjson::StringBuffer buffer;
rapidjson::Writer<rapidjson::StringBuffer> writer(buffer);
value.Accept(writer);
return buffer.GetString();
}
string DestroyInstanceResponse::GetFlowID() const
{
return m_flowID;
}
bool DestroyInstanceResponse::FlowIDHasBeenSet() const
{
return m_flowIDHasBeenSet;
}
string DestroyInstanceResponse::GetInstanceID() const
{
return m_instanceID;
}
bool DestroyInstanceResponse::InstanceIDHasBeenSet() const
{
return m_instanceIDHasBeenSet;
}
string DestroyInstanceResponse::GetErrorMsg() const
{
return m_errorMsg;
}
bool DestroyInstanceResponse::ErrorMsgHasBeenSet() const
{
return m_errorMsgHasBeenSet;
}
| [
"tencentcloudapi@tencent.com"
] | tencentcloudapi@tencent.com |
b50f477b68a33dc4dd53b838ca071604d5d469c1 | f22bdc99b6b308ec2be3f9cb63aa117f04d82dbe | /Apps/Tracker Applications/SimpleTrackerApplication/collisionCheck.h | c50f1c0e28fec36e5ddd129986edbe1ad77e7e3b | [] | no_license | naneaa/cybermed-master | d268b7b6c573feadc7cde041bd80de4a7ccc5687 | 46fba3ea54e9c4671a521cf21624a65a50812bd0 | refs/heads/master | 2021-01-21T08:37:19.621596 | 2018-05-14T23:30:42 | 2018-05-14T23:30:42 | 91,632,795 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 693 | h | class collisionCheck : public CybThread
{
private:
CybSphereTriangle *collisionObj;
CybParameters *cybCore;
int count;
public:
collisionCheck(int layerID)
{
collisionObj = new CybSphereTriangle(layerID);
count = 0;
cybCore = CybParameters::getInstance();
this->setTime(50);
}
~collisionCheck(){ delete collisionObj; }
void run()
{
CybThread::lock();
if(collisionObj->getCollisionStatus()){
cybCore->setColor(0,1,1,0,1);
cout << "is Equal the last collision " << collisionObj->isEqualLastCollision() << endl;
}
else
cybCore->setColor(0,1,0,1,1);
CybThread::unlock();
}
CybSphereTriangle *getCollisionInstance() { return collisionObj; }
};
| [
"elaineanita1@gmail.com"
] | elaineanita1@gmail.com |
8ba186ab00dc67517b1f6dcadf0b4b286f5588ce | 07368f604a72c97faf863529dfef690ff21d8675 | /tensorflow/compiler/jit/xla_device_context.cc | ff30b62bad782f281bcd25275521ed8b0c4c0bfd | [
"Apache-2.0"
] | permissive | Amywanwan/tensorflow | 8f847abe28815977fb1f9edbcc10c9d5ec0d4214 | 4b010b31890369d3236887f29633910af04d1410 | refs/heads/master | 2022-10-26T19:18:29.518549 | 2022-10-17T13:26:51 | 2022-10-17T13:26:51 | 134,808,604 | 0 | 0 | Apache-2.0 | 2018-05-25T05:42:23 | 2018-05-25T05:42:23 | null | UTF-8 | C++ | false | false | 8,736 | cc | /* Copyright 2017 The TensorFlow Authors. All Rights Reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
==============================================================================*/
#include "tensorflow/compiler/jit/xla_device_context.h"
#include "tensorflow/compiler/jit/xla_launch_util.h"
#include "tensorflow/compiler/tf2xla/literal_util.h"
#include "tensorflow/compiler/tf2xla/shape_util.h"
#include "tensorflow/compiler/xla/util.h"
#include "tensorflow/core/common_runtime/device.h"
#include "tensorflow/core/common_runtime/dma_helper.h"
#include "tensorflow/core/platform/mem.h"
namespace tensorflow {
// The allocator used for Tensors assigned to the XLA device.
XlaDeviceAllocator::XlaDeviceAllocator() {}
XlaDeviceAllocator::~XlaDeviceAllocator() = default;
string XlaDeviceAllocator::Name() { return "xla"; }
void* XlaDeviceAllocator::AllocateRaw(size_t alignment, size_t num_bytes) {
// We always return an empty XlaTensor object, encoded as an opaque tagged
// pointer. We can return an empty object and ignore num_bytes here because we
// have control over all of the uses of this device tensor, and can lazily
// allocate memory when used. This allows us to also know the shape of the
// allocated Tensor, which is useful if the device's tensor representation
// differs from the host.
return XlaTensor::ToOpaquePointer(new XlaTensor());
}
void XlaDeviceAllocator::DeallocateRaw(void* ptr) {
delete XlaTensor::FromOpaquePointer(ptr);
}
void XlaDeviceAllocator::GetStats(AllocatorStats* stats) { stats->Clear(); }
XlaTransferManager::XlaTransferManager(
se::Stream* stream, xla::LocalClient* client, bool transfer_as_literal,
XlaCompiler::ShapeRepresentationFn shape_representation_fn)
: stream_(stream),
client_(client),
transfer_manager_(client->backend().transfer_manager()),
transfer_as_literal_(transfer_as_literal),
shape_representation_fn_(std::move(shape_representation_fn)) {}
Status XlaTransferManager::TransferLiteralToDevice(
const Tensor& host_tensor, Tensor* device_tensor) const {
xla::Literal literal;
TF_RETURN_IF_ERROR(HostTensorToLiteral(host_tensor, &literal));
VLOG(1) << "Transfer to device as literal: " << literal.ToString();
const xla::ShapedBuffer& shaped_buffer =
XlaTensor::FromTensor(device_tensor)->shaped_buffer();
return transfer_manager_->TransferLiteralToDevice(stream_->parent(), literal,
shaped_buffer);
}
Status XlaTransferManager::TransferLiteralFromDevice(
Tensor* host_tensor, const Tensor& device_tensor) const {
const xla::ShapedBuffer& shaped_buffer =
XlaTensor::FromTensor(&device_tensor)->shaped_buffer();
TF_ASSIGN_OR_RETURN(std::unique_ptr<xla::Literal> literal,
transfer_manager_->TransferLiteralFromDevice(
stream_->parent(), shaped_buffer));
VLOG(1) << "Transfer from device as literal: " << literal->ToString();
Tensor tensor;
TF_RETURN_IF_ERROR(
LiteralToHostTensor(*literal, host_tensor->dtype(), &tensor));
// Reshape the tensor back to its declared shape.
if (!host_tensor->CopyFrom(tensor, device_tensor.shape())) {
return errors::Internal(
"Tensor::CopyFrom failed when copying from XLA device to CPU");
}
return Status::OK();
}
void XlaTransferManager::CopyCPUTensorToDevice(const Tensor* cpu_tensor,
Device* device,
Tensor* device_tensor,
StatusCallback done) const {
if (cpu_tensor->NumElements() > 0) {
VLOG(2) << "CopyCPUTensorToDevice "
<< reinterpret_cast<const void*>(cpu_tensor->tensor_data().data())
<< " "
<< reinterpret_cast<const void*>(
device_tensor->tensor_data().data())
<< " " << cpu_tensor->NumElements();
void* src_ptr = const_cast<void*>(DMAHelper::base(cpu_tensor));
const int64 total_bytes = cpu_tensor->TotalBytes();
XlaTensor* xla_tensor = XlaTensor::FromTensor(device_tensor);
CHECK(xla_tensor);
TensorShape shape;
if (shape_representation_fn_) {
shape = shape_representation_fn_(device_tensor->shape(),
device_tensor->dtype());
} else {
shape = device_tensor->shape();
}
if (!xla_tensor->has_shaped_buffer()) {
Status s = xla_tensor->AllocateShapedBuffer(
device_tensor->dtype(), shape, client_,
stream_->parent()->device_ordinal());
if (!s.ok()) {
done(s);
return;
}
}
Status status;
if (transfer_as_literal_) {
Tensor reshaped_cpu_tensor;
if (!reshaped_cpu_tensor.CopyFrom(*cpu_tensor, shape)) {
done(errors::Internal(
"Tensor::CopyFrom failed when copying from CPU to XLA device"));
return;
}
status = TransferLiteralToDevice(reshaped_cpu_tensor, device_tensor);
} else {
se::DeviceMemoryBase dev_dst_ptr =
XlaTensor::DeviceMemoryFromTensor(*device_tensor);
stream_->ThenMemcpy(&dev_dst_ptr, src_ptr, total_bytes);
// TODO(hpucha): Make this asynchronous.
Status block_status = stream_->BlockHostUntilDone();
if (!block_status.ok()) {
status = xla::InternalError(
"Failed to complete data transfer on stream %p: %s", stream_,
block_status.error_message().c_str());
}
}
xla_tensor->set_host_tensor(*cpu_tensor);
done(status);
return;
}
VLOG(2) << "CopyCPUTensorToDevice empty tensor";
done(Status::OK());
}
void XlaTransferManager::CopyDeviceTensorToCPU(const Tensor* device_tensor,
StringPiece tensor_name,
Device* device,
Tensor* cpu_tensor,
StatusCallback done) {
if (device_tensor->NumElements() > 0) {
VLOG(2) << "CopyDeviceTensorToCPU "
<< reinterpret_cast<const void*>(
device_tensor->tensor_data().data())
<< " "
<< reinterpret_cast<const void*>(cpu_tensor->tensor_data().data())
<< device_tensor->NumElements();
const int64 total_bytes = cpu_tensor->TotalBytes();
se::DeviceMemoryBase dev_src_ptr =
XlaTensor::DeviceMemoryFromTensor(*device_tensor);
void* dst_ptr = DMAHelper::base(cpu_tensor);
Status status;
if (transfer_as_literal_) {
status = TransferLiteralFromDevice(cpu_tensor, *device_tensor);
} else {
stream_->ThenMemcpy(dst_ptr, dev_src_ptr, total_bytes);
// TODO(hpucha): Make this asynchronous.
Status block_status = stream_->BlockHostUntilDone();
if (!block_status.ok()) {
status = xla::InternalError(
"Failed to complete data transfer on stream %p: %s", stream_,
block_status.error_message().c_str());
}
}
done(status);
return;
}
VLOG(2) << "CopyDeviceTensorToCPU empty tensor";
done(Status::OK());
}
XlaDeviceContext::XlaDeviceContext(
se::Stream* stream, xla::LocalClient* client, bool transfer_as_literal,
XlaCompiler::ShapeRepresentationFn shape_representation_fn)
: manager_(stream, client, transfer_as_literal,
std::move(shape_representation_fn)) {}
void XlaDeviceContext::CopyCPUTensorToDevice(const Tensor* cpu_tensor,
Device* device,
Tensor* device_tensor,
StatusCallback done) const {
manager_.CopyCPUTensorToDevice(cpu_tensor, device, device_tensor, done);
}
void XlaDeviceContext::CopyDeviceTensorToCPU(const Tensor* device_tensor,
StringPiece tensor_name,
Device* device, Tensor* cpu_tensor,
StatusCallback done) {
manager_.CopyDeviceTensorToCPU(device_tensor, tensor_name, device, cpu_tensor,
done);
}
} // namespace tensorflow
| [
"gardener@tensorflow.org"
] | gardener@tensorflow.org |
b4ed4c31a7388377ba32c2c3f16b2bdffe58c7de | ea5abb606afbae6e5774072ffd9b69e6418d0389 | /source/io/fs/detail/FsCommon.h | 01ecfe4b23d8cabd1575c7618951d617b27bdfe8 | [
"MIT"
] | permissive | stormlord/tarm-io | a4487316a4034b654f89fb081e880bb4f3e4a928 | 6aebd85573f65017decf81be073c8b13ce6ac12c | refs/heads/master | 2023-07-01T11:24:38.077682 | 2021-08-08T08:02:37 | 2021-08-08T08:02:37 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,462 | h | /*----------------------------------------------------------------------------------------------
* Copyright (c) 2020 - present Alexander Voitenko
* Licensed under the MIT License. See License.txt in the project root for license information.
*----------------------------------------------------------------------------------------------*/
#pragma once
#include "Error.h"
#include "EventLoop.h"
namespace tarm {
namespace io {
namespace fs {
namespace detail {
template<typename T, typename OpenCallback>
bool open(EventLoop& loop, T& fs_object, const Path& path, const OpenCallback& callback) {
if (fs_object.state() == T::State::OPENED) {
fs_object.close([&fs_object, &loop, path, callback](typename T::ParentType& dir, const Error& error) {
if (error) {
if(callback) {
callback(dir, error);
}
} else {
loop.schedule_callback([&fs_object, path, callback](EventLoop&) {
fs_object.open(path, callback);
});
}
});
return false;
} else if (!(fs_object.state() == T::State::INITIAL || fs_object.state() == T::State::CLOSED)) {
loop.schedule_callback([&fs_object, path, callback](EventLoop&) {
fs_object.open(path, callback);
});
return false;
}
return true;
}
} // namespace detail
} // namespace fs
} // namespace io
} // namespace tarm
| [
"av@tarm.io"
] | av@tarm.io |
8fc7f5129112f70d52809d71eb3909299a6cc45f | 6be30dd43e374450d7abacbdca638aacb8eb4c97 | /Src/HMCAD/dxflib/dl_writer.h | ba7718271714d73dcb797c202b35c4baeb986e3c | [] | no_license | 15831944/Main | 471bc3e91a22ccd888ca1351e23bf6982a26d4d6 | 971ba925c261a27ea62f4b6708c7b8ac22298195 | refs/heads/master | 2021-10-26T22:32:09.617567 | 2019-04-14T12:21:29 | 2019-04-14T12:21:29 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 13,998 | h | /****************************************************************************
** Copyright (C) 2001-2013 RibbonSoft, GmbH. All rights reserved.
** Copyright (C) 2001 Robert J. Campbell Jr.
**
** This file is part of the dxflib project.
**
** This file 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.
**
** Licensees holding valid dxflib Professional Edition licenses may use
** this file in accordance with the dxflib Commercial License
** Agreement provided with the Software.
**
** This file is provided AS IS with NO WARRANTY OF ANY KIND, INCLUDING THE
** WARRANTY OF DESIGN, MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE.
**
** See http://www.ribbonsoft.com for further details.
**
** Contact info@ribbonsoft.com if any conditions of this licensing are
** not clear to you.
**
**********************************************************************/
#ifndef DL_WRITER_H
#define DL_WRITER_H
#ifndef _WIN32
#include <strings.h>
#endif
#if _MSC_VER > 1000
#pragma once
#endif // _MSC_VER > 1000
#include <iostream>
#include <algorithm>
#include "dl_attributes.h"
#include "dl_codes.h"
_HM_CAD_BEGIN
/**
* Defines interface for writing low level DXF constructs to
* a file. Implementation is defined in derived classes that write
* to binary or ASCII files.
*
* Implements functions that write higher level constructs in terms of
* the low level ones.
*
* @todo Add error checking for string/entry length.
*/
class HM_CAD_EXT DL_Writer {
public:
/**
* @param version DXF version. Defaults to DL_VERSION_2002.
*/
DL_Writer(DL_Codes::version version) : m_handle(0x30) {
this->version = version;
modelSpaceHandle = 0;
paperSpaceHandle = 0;
paperSpace0Handle = 0;
}
virtual ~DL_Writer() {}
;
/** Generic section for section 'name'.
*
* <pre>
* 0
* SECTION
* 2
* name
* </pre>
*/
void section(const char* name) const {
dxfString(0, "SECTION");
dxfString(2, name);
}
/**
* Section HEADER
*
* <pre>
* 0
* SECTION
* 2
* HEADER
* </pre>
*/
void sectionHeader() const {
section("HEADER");
}
/**
* Section TABLES
*
* <pre>
* 0
* SECTION
* 2
* TABLES
* </pre>
*/
void sectionTables() const {
section("TABLES");
}
/**
* Section BLOCKS
*
* <pre>
* 0
* SECTION
* 2
* BLOCKS
* </pre>
*/
void sectionBlocks() const {
section("BLOCKS");
}
/**
* Section ENTITIES
*
* <pre>
* 0
* SECTION
* 2
* ENTITIES
* </pre>
*/
void sectionEntities() const {
section("ENTITIES");
}
/**
* Section CLASSES
*
* <pre>
* 0
* SECTION
* 2
* CLASSES
* </pre>
*/
void sectionClasses() const {
section("CLASSES");
}
/**
* Section OBJECTS
*
* <pre>
* 0
* SECTION
* 2
* OBJECTS
* </pre>
*/
void sectionObjects() const {
section("OBJECTS");
}
/**
* End of a section.
*
* <pre>
* 0
* ENDSEC
* </pre>
*/
void sectionEnd() const {
dxfString(0, "ENDSEC");
}
/**
* Generic table for table 'name' with 'num' entries:
*
* <pre>
* 0
* TABLE
* 2
* name
* 70
* num
* </pre>
*/
void table(const char* name, int num, int h=0) const {
dxfString(0, "TABLE");
dxfString(2, name);
if (version>=DL_VERSION_2000) {
if (h==0) {
handle();
}
else {
dxfHex(5, h);
}
dxfString(100, "AcDbSymbolTable");
}
dxfInt(70, num);
}
/** Table for layers.
*
* @param num Number of layers in total.
*
* <pre>
* 0
* TABLE
* 2
* LAYER
* 70
* num
* </pre>
*/
void tableLayers(int num) const {
table("LAYER", num, 2);
}
/** Table for line types.
*
* @param num Number of line types in total.
*
* <pre>
* 0
* TABLE
* 2
* LTYPE
* 70
* num
* </pre>
*/
void tableLinetypes(int num) const {
//linetypeHandle = 5;
table("LTYPE", num, 5);
}
/** Table for application id.
*
* @param num Number of registered applications in total.
*
* <pre>
* 0
* TABLE
* 2
* APPID
* 70
* num
* </pre>
*/
void tableAppid(int num) const {
table("APPID", num, 9);
}
/** Table for text style.
*
* @param num Number of text styles.
*
* <pre>
* 0
* TABLE
* 2
* STYLE
* 70
* num
* </pre>
*/
void tableStyle(int num) const {
table("STYLE", num, 3);
}
/**
* End of a table.
*
* <pre>
* 0
* ENDTAB
* </pre>
*/
void tableEnd() const {
dxfString(0, "ENDTAB");
}
/**
* End of the DXF file.
*
* <pre>
* 0
* EOF
* </pre>
*/
void dxfEOF() const {
dxfString(0, "EOF");
}
/**
* Comment.
*
* <pre>
* 999
* text
* </pre>
*/
void comment(const char* text) const {
dxfString(999, text);
}
/**
* Entity.
*
* <pre>
* 0
* entTypeName
* </pre>
*
* @return Unique handle or 0.
*/
void entity(const char* entTypeName) const {
dxfString(0, entTypeName);
if (version>=DL_VERSION_2000) {
handle();
}
}
/**
* Attributes of an entity.
*
* <pre>
* 8
* layer
* 62
* color
* 39
* width
* 6
* linetype
* </pre>
*/
void entityAttributes(const DL_Attributes& attrib) const {
// layer name:
dxfString(8, attrib.getLayer());
// R12 doesn't accept BYLAYER values. The value has to be missing
// in that case.
if (version>=DL_VERSION_2000 || attrib.getColor()!=256) {
dxfInt(62, attrib.getColor());
}
if (version>=DL_VERSION_2000 && attrib.getColor24()!=-1) {
dxfInt(420, attrib.getColor24());
}
if (version>=DL_VERSION_2000) {
dxfInt(370, attrib.getWidth());
}
if (version>=DL_VERSION_2000) {
dxfReal(48, attrib.getLinetypeScale());
}
std::string linetype = attrib.getLinetype();
std::transform(linetype.begin(), linetype.end(), linetype.begin(), ::toupper);
if (version>=DL_VERSION_2000 || linetype=="BYLAYER") {
dxfString(6, attrib.getLinetype());
}
}
/**
* Subclass.
*/
void subClass(const char* sub) const {
dxfString(100, sub);
}
/**
* Layer (must be in the TABLES section LAYER).
*
* <pre>
* 0
* LAYER
* </pre>
*/
void tableLayerEntry(unsigned long int h=0) const {
dxfString(0, "LAYER");
if (version>=DL_VERSION_2000) {
if (h==0) {
handle();
} else {
dxfHex(5, h);
}
dxfString(100, "AcDbSymbolTableRecord");
dxfString(100, "AcDbLayerTableRecord");
}
}
/**
* Line type (must be in the TABLES section LTYPE).
*
* <pre>
* 0
* LTYPE
* </pre>
*/
void tableLinetypeEntry(unsigned long int h=0) const {
dxfString(0, "LTYPE");
if (version>=DL_VERSION_2000) {
if (h==0) {
handle();
} else {
dxfHex(5, h);
}
//dxfHex(330, 0x5);
dxfString(100, "AcDbSymbolTableRecord");
dxfString(100, "AcDbLinetypeTableRecord");
}
}
/**
* Appid (must be in the TABLES section APPID).
*
* <pre>
* 0
* APPID
* </pre>
*/
void tableAppidEntry(unsigned long int h=0) const {
dxfString(0, "APPID");
if (version>=DL_VERSION_2000) {
if (h==0) {
handle();
} else {
dxfHex(5, h);
}
//dxfHex(330, 0x9);
dxfString(100, "AcDbSymbolTableRecord");
dxfString(100, "AcDbRegAppTableRecord");
}
}
/**
* Block (must be in the section BLOCKS).
*
* <pre>
* 0
* BLOCK
* </pre>
*/
void sectionBlockEntry(unsigned long int h=0) const {
dxfString(0, "BLOCK");
if (version>=DL_VERSION_2000) {
if (h==0) {
handle();
} else {
dxfHex(5, h);
}
//dxfHex(330, blockHandle);
dxfString(100, "AcDbEntity");
if (h==0x1C) {
dxfInt(67, 1);
}
dxfString(8, "0"); // TODO: Layer for block
dxfString(100, "AcDbBlockBegin");
}
}
/**
* End of Block (must be in the section BLOCKS).
*
* <pre>
* 0
* ENDBLK
* </pre>
*/
void sectionBlockEntryEnd(unsigned long int h=0) const {
dxfString(0, "ENDBLK");
if (version>=DL_VERSION_2000) {
if (h==0) {
handle();
} else {
dxfHex(5, h);
}
//dxfHex(330, blockHandle);
dxfString(100, "AcDbEntity");
if (h==0x1D) {
dxfInt(67, 1);
}
dxfString(8, "0"); // TODO: Layer for block
dxfString(100, "AcDbBlockEnd");
}
}
void color(int col=256) const {
dxfInt(62, col);
}
void linetype(const char *lt) const {
dxfString(6, lt);
}
void linetypeScale(double scale) const {
dxfReal(48, scale);
}
void lineWeight(int lw) const {
dxfInt(370, lw);
}
void coord(int gc, double x, double y, double z=0) const {
dxfReal(gc, x);
dxfReal(gc+10, y);
dxfReal(gc+20, z);
}
void coordTriplet(int gc, const double* value) const {
if (value) {
dxfReal(gc, *value++);
dxfReal(gc+10, *value++);
dxfReal(gc+20, *value++);
}
}
void resetHandle() const {
m_handle = 1;
}
/**
* Writes a unique handle and returns it.
*/
unsigned long handle(int gc=5) const {
// handle has to be hex
dxfHex(gc, m_handle);
return m_handle++;
}
/**
* @return Next handle that will be written.
*/
unsigned long getNextHandle() const {
return m_handle;
}
/**
* Increases handle, so that the handle returned remains available.
*/
unsigned long incHandle() const {
return m_handle++;
}
/**
* Sets the handle of the model space. Entities refer to
* this handle.
*/
void setModelSpaceHandle(unsigned long h) {
modelSpaceHandle = h;
}
unsigned long getModelSpaceHandle() {
return modelSpaceHandle;
}
/**
* Sets the handle of the paper space. Some special blocks refer to
* this handle.
*/
void setPaperSpaceHandle(unsigned long h) {
paperSpaceHandle = h;
}
unsigned long getPaperSpaceHandle() {
return paperSpaceHandle;
}
/**
* Sets the handle of the paper space 0. Some special blocks refer to
* this handle.
*/
void setPaperSpace0Handle(unsigned long h) {
paperSpace0Handle = h;
}
unsigned long getPaperSpace0Handle() {
return paperSpace0Handle;
}
/**
* Must be overwritten by the implementing class to write a
* real value to the file.
*
* @param gc Group code.
* @param value The real value.
*/
virtual void dxfReal(int gc, double value) const = 0;
/**
* Must be overwritten by the implementing class to write an
* int value to the file.
*
* @param gc Group code.
* @param value The int value.
*/
virtual void dxfInt(int gc, int value) const = 0;
/**
* Can be overwritten by the implementing class to write a
* bool value to the file.
*
* @param gc Group code.
* @param value The bool value.
*/
virtual void dxfBool(int gc, bool value) const {
dxfInt(gc, (int)value);
}
/**
* Must be overwritten by the implementing class to write an
* int value (hex) to the file.
*
* @param gc Group code.
* @param value The int value.
*/
virtual void dxfHex(int gc, int value) const = 0;
/**
* Must be overwritten by the implementing class to write a
* string to the file.
*
* @param gc Group code.
* @param value The string.
*/
virtual void dxfString(int gc, const char* value) const = 0;
/**
* Must be overwritten by the implementing class to write a
* string to the file.
*
* @param gc Group code.
* @param value The string.
*/
virtual void dxfString(int gc, const std::string& value) const = 0;
protected:
mutable unsigned long m_handle;
mutable unsigned long modelSpaceHandle;
mutable unsigned long paperSpaceHandle;
mutable unsigned long paperSpace0Handle;
/**
* DXF version to be created.
*/
DL_Codes::version version;
private:
};
_HM_CAD_END
#endif
| [
"960902471@qq.com"
] | 960902471@qq.com |
95bae46918c21c1cf52babb05a818050eee19f09 | c676bcf38a8e3833699752cf03f361b74fcc3e20 | /src/canvascv/widgets/hframe.cpp | 4130562d7f6f28916fa81282ca68d71e7665fbe6 | [
"BSD-3-Clause"
] | permissive | rocee/CanvasCV | 9fa619e9a5f6398f28cad76682f8c9364ac33e15 | 85235e5c6270df0feb6f960254b67a04653f1221 | refs/heads/master | 2021-04-15T10:31:51.462153 | 2017-07-26T11:41:40 | 2017-07-26T11:41:40 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 536 | cpp | #include "hframe.h"
#include "widgetfactory.h"
using namespace cv;
using namespace std;
namespace canvascv
{
const char * HFrame::type = "HFrame";
HFrame::HFrame(const Point &pos)
: HorizontalLayout(pos)
{
fillBG = true;
}
shared_ptr<HFrame> HFrame::create(Layout &layout, const Point &pos)
{
shared_ptr<HFrame> widget(WidgetFactoryT<HFrame>::newWidget(layout, pos));
return widget;
}
void HFrame::setFrameRelief(Relief value)
{
setRelief(value);
}
const char *HFrame::getType() const
{
return type;
}
}
| [
"sagi.zeevi@gmail.com"
] | sagi.zeevi@gmail.com |
7eb160471a88085df3efc9141b75dd84e9e11efa | c32ee8ade268240a8064e9b8efdbebfbaa46ddfa | /Libraries/m2sdk/ue/ai/framework/C_ObjectCreator_TPL_75E6C06E.h | ea3e3e1ffffbccda496262b1c31c13681acbdc75 | [] | no_license | hopk1nz/maf2mp | 6f65bd4f8114fdeb42f9407a4d158ad97f8d1789 | 814cab57dc713d9ff791dfb2a2abeb6af0e2f5a8 | refs/heads/master | 2021-03-12T23:56:24.336057 | 2015-08-22T13:53:10 | 2015-08-22T13:53:10 | 41,209,355 | 19 | 21 | null | 2015-08-31T05:28:13 | 2015-08-22T13:56:04 | C++ | UTF-8 | C++ | false | false | 539 | h | // auto-generated file (rttidump-exporter by h0pk1nz)
#pragma once
#include <ue/ai/framework/C_Functor_TPL_DC332828.h>
namespace ue
{
namespace ai
{
namespace framework
{
/** ue::ai::framework::C_ObjectCreator<game::ai::C_Behaviour_AvoidingCarJump> (VTable=0x01E43590) */
class C_ObjectCreator_TPL_75E6C06E : public C_Functor_TPL_DC332828
{
public:
virtual void vfn_0001_60D76610() = 0;
virtual void vfn_0002_60D76610() = 0;
virtual void vfn_0003_60D76610() = 0;
};
} // namespace framework
} // namespace ai
} // namespace ue
| [
"hopk1nz@gmail.com"
] | hopk1nz@gmail.com |
8e826754a06111c93a000e9f9d627904416f3b77 | ff43563cca42c1cf2f48f3273d445cc8ed004edd | /src/game/scene/StartMenu.cc | 64f75298f17f0422219fcc0df50fe07afad4e608 | [] | no_license | MatthewSuttles/galaxy-demo-app | d800280df81f8aff7fd5aaccac161f2006fb0159 | c8aea4db4f525bc28961b6d82924ccf2eb98e72d | refs/heads/master | 2021-01-18T06:13:06.411905 | 2016-04-11T09:36:30 | 2016-04-11T09:36:30 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,914 | cc | #include "StartMenu.h"
#include <game/IGame.h>
#include <engine/system/Button.h>
#include <engine/core/SDLResourceManager.h>
#include <SDL_opengl.h>
using namespace gogtron;
using namespace gogtron::system;
using namespace gogtron::scene;
using namespace gogtron::networking;
StartMenu::StartMenu(const IGamePtr& _game)
: GameState(_game)
{
}
bool StartMenu::Init()
{
glViewport(0, 0, 1280, 720);
glMatrixMode(GL_PROJECTION);
glLoadIdentity();
glOrtho(0.0, 1280, 720, 1.0, -1.0, 1.0);
glClearColor(0.0, 0.0, 0.0, 0.0);
glMatrixMode(GL_PROJECTION);
glLoadIdentity();
glOrtho(0.0, 1280, 720, 1.0, -1.0, 1.0);
glEnable(GL_BLEND);
glEnable(GL_TEXTURE_2D);
glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
if (!core::SDLResourceManager::GetInstance().LoadTexture("res//images//button.png", "button"))
return false;
if (!core::SDLResourceManager::GetInstance().LoadTexture("res//images//selectedbutton.png", "selectedbutton"))
return false;
if (!core::SDLResourceManager::GetInstance().LoadFont("res//fonts//FreeSans.ttf", "FreeSans"))
return false;
GUIElementPtr playButton(std::make_shared<Button>(
"button",
"selectedbutton",
renderer::Sprite(1280 / 2 - 150, 50, 300, 100),
/*Sprite(400, 100, 400, 224),*/
[&](){ game->SetGameState(GameState::State::LOBBY_MENU); }));
guiElements.push_back(playButton);
GUIElementPtr statsButton(std::make_shared<Button>(
"button",
"selectedbutton",
renderer::Sprite(1280 / 2 - 150, 200, 300, 100),
[&]() { game->SetGameState(GameState::State::STATS_VIEW); }));
guiElements.push_back(statsButton);
GUIElementPtr leaderboardsButton(std::make_shared<Button>(
"button",
"selectedbutton",
renderer::Sprite(1280 / 2 - 150, 350, 300, 100),
[&]() { game->SetGameState(GameState::State::LEADERBOARDS_VIEW); }));
guiElements.push_back(leaderboardsButton);
GUIElementPtr quitButton(std::make_shared<Button>(
"button",
"selectedbutton",
renderer::Sprite(1280 / 2 - 150, 500, 300, 100),
/*Sprite(400, 400, 400, 224),*/
[&](){ game->Close(); }));
guiElements.push_back(quitButton);
return true;
}
bool StartMenu::Release()
{
return true;
}
void StartMenu::OnMouseDown(std::uint32_t x, std::uint32_t y)
{
for (const auto& element : guiElements)
{
element->OnMouseDown(x, y);
}
}
void StartMenu::OnMouseMotion(std::uint32_t x, std::uint32_t y)
{
for (const auto& element : guiElements)
{
element->OnMouseMotion(x, y);
}
}
void StartMenu::OnKeyDown(SDL_Keysym key)
{
switch (key.sym)
{
case SDLK_UP:
guiElements[0]->OnMouseMotion(450, 150);
break;
case SDLK_DOWN:
break;
case SDLK_KP_ENTER:
guiElements[0]->OnMouseDown(450, 150);
break;
default:
break;
}
}
void StartMenu::OnLobbyEvent(const LobbyEvent& lobbyEvent)
{
}
bool StartMenu::Update()
{
return true;
}
bool StartMenu::Display(const renderer::OGLRendererPtr& renderEngine)
{
glViewport(0, 0, 1280, 720);
glMatrixMode(GL_PROJECTION);
glLoadIdentity();
glOrtho(0.0, 1280, 720, 1.0, -1.0, 1.0);
glClearColor(0.0, 0.0, 0.0, 0.0);
glMatrixMode(GL_PROJECTION);
glLoadIdentity();
glOrtho(0.0, 1280, 720, 1.0, -1.0, 1.0);
glEnable(GL_BLEND);
glEnable(GL_TEXTURE_2D);
glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
renderEngine->StartScene();
for (const auto& element : guiElements)
{
element->Display(renderEngine);
}
renderEngine->DisplayText("PLAY", renderer::Sprite(1280 / 2 - 50, 50, 100, 100), "FreeSans_Play", SDL_Color{ 255, 0, 0, 255 });
renderEngine->DisplayText("STATS", renderer::Sprite(1280 / 2 - 50, 200, 100, 100), "FreeSans_Stats", SDL_Color{ 255, 0, 0, 255 });
renderEngine->DisplayText("LEADERBOARDS", renderer::Sprite(1280 / 2 - 100, 350, 200, 100), "FreeSans_Leaderboards", SDL_Color{ 255, 0, 0, 255 });
renderEngine->DisplayText("QUIT", renderer::Sprite(1280 / 2 - 50, 500, 100, 100), "FreeSans_Quit", SDL_Color{ 255, 0, 0, 255 });
renderEngine->EndScene();
return true;
} | [
"tjaskolski@gog.com"
] | tjaskolski@gog.com |
2f8929eade7f9d319af392268172fdf7a02701e4 | a759c6611c855925e2a73ca437ed004d74c4c611 | /백준문제/자료구조 - Data Structures/백준 10872.cpp | 9cb3482b3f81ab14d7c1bfb5ba4554ae22d121c0 | [] | no_license | yugo9081/My-Codes | dafcfb7428256b9bad06d4221cec6e208241d151 | 84bfe92865d854f9aa6a201a2ba66dae1c2abe27 | refs/heads/master | 2023-01-20T22:50:39.828481 | 2020-11-23T09:47:05 | 2020-11-23T09:47:05 | 283,927,861 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 649 | cpp | /******************************************************************************
Online C++ Compiler.
Code, Compile, Run and Debug C++ program online.
Write your code in this editor and press "Run" button to compile and execute it.
*******************************************************************************/
#include <iostream>
using namespace std;
int factorial(int n){ //recursion
if(n<=1){
return 1;
}
return n*factorial(n-1);
}
int main(void)
{
cin.tie(NULL);
cout.tie(NULL);
ios_base :: sync_with_stdio(false);
int n;
cin>>n;
cout << factorial(n)<<"\n";
}
| [
"yugo9081@colorado.edu"
] | yugo9081@colorado.edu |
c774bfeab29bec9759f932410ff545fd298709eb | 46367579a54a09dd220dd9a678b1452f06897f11 | /tags/hdf5-1_4_3/c++/src/H5Library.h | f0d2e022702ec08d16b23d45501c7ef8f9f58be3 | [
"LicenseRef-scancode-llnl",
"LicenseRef-scancode-warranty-disclaimer"
] | permissive | TPLink32/hdf5 | 33ff24c9b6133f0f51cb6cc2b722fba7bb1777dd | 0d6987c15284bd9f34c7e44452a152833d42a738 | refs/heads/master | 2021-05-31T01:15:39.463663 | 2016-04-14T23:02:09 | 2016-04-14T23:02:09 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,220 | h | // C++ informative line for the emacs editor: -*- C++ -*-
#ifndef _H5Library_H
#define _H5Library_H
#ifndef H5_NO_NAMESPACE
namespace H5 {
#endif
#define NOTATEXIT (-10) // just in case the HDF5 library use more
// negative constants. Note: the solution used for the atexit/global
// destructors is not reliable, and desperately needs improvement
// It is not even working, inifiteloop message still printed when
// calling H5close
class __DLLCPP__ H5Library {
public:
static bool need_cleanup; // indicates if H5close should be called
// Initializes the HDF5 library.
static void open();
// Flushes all data to disk, closes files, and cleans up memory.
static void close();
// Instructs library not to install atexit cleanup routine
static void dontAtExit();
// Returns the HDF library release number.
static void getLibVersion( unsigned& majnum, unsigned& minnum, unsigned& relnum );
// Verifies that the arguments match the version numbers compiled
// into the library
static void checkVersion( unsigned majnum, unsigned minnum, unsigned relnum );
private:
// Default constructor - no instance ever created
H5Library() {};
};
#ifndef H5_NO_NAMESPACE
}
#endif
#endif
| [
"(no author)@dab4d1a6-ed17-0410-a064-d1ae371a2980"
] | (no author)@dab4d1a6-ed17-0410-a064-d1ae371a2980 |
f7b5afa95d321aefe346b4081a73fbc3d9358b39 | d1f42089ef7f2976bcfba27253860df394fe6221 | /02/lab02/Dispencer/Dispencer.cpp | a954ddbe3cd4f4b6677d66c54df1e2f02a818eb4 | [] | no_license | petaryanakiev-py/oop-2020 | e4f756541fe6ffdcc1cea55d501f261911934d79 | ec9388d2b81325cbf43f5944eb76f7459a2c8b0a | refs/heads/master | 2022-09-10T22:18:23.191298 | 2020-06-03T14:39:26 | 2020-06-03T14:39:26 | 241,456,321 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 496 | cpp | #include "Dispencer.hpp"
#include <iostream>
void Dispencer::fill(const double litres)
{
this->litres = litres;
}
void Dispencer::fillGlass(const double mililitres)
{
const double MILILITRES_IN_LITRE = 1000;
if (this->litres * MILILITRES_IN_LITRE < mililitres)
{
std::cout << "Not enough water. Fill me first." << std::endl;
}
this->litres -= mililitres / MILILITRES_IN_LITRE;
}
void Dispencer::fillBottle(const double mililitres)
{
fillGlass(mililitres);
} | [
"petaryanakiev.py@gmail.com"
] | petaryanakiev.py@gmail.com |
e6e5a38020fa86f64eebcb18d11fe432a47a8949 | 31665642ed578801e684eb0e71526707416f6c7b | /osca/xiinux/src/web/web.hpp | 07f8b73e306027d9881615af48c387a59187c780 | [] | no_license | calint/a | 79fb449e4e9baf4b19da6b1cbf925235254ba981 | 50c8d03e0115cd52737a0f95e86b9043e731f419 | refs/heads/master | 2023-02-02T14:30:44.406050 | 2023-01-29T04:57:04 | 2023-01-29T04:57:04 | 32,960,630 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 717 | hpp | #pragma once
//-- generated
#include"hello.hpp"
#include"typealine.hpp"
#include"counter.hpp"
#include"page.hpp"
#include"chunked.hpp"
#include"chunkedbig.hpp"
#include"chunkedbigger.hpp"
#include"notfound.hpp"
namespace xiinux{
static inline widget*widgetget(const char*qs){
if(!strcmp("hello",qs))return new web::hello();
if(!strcmp("typealine",qs))return new web::typealine();
if(!strcmp("counter",qs))return new web::counter();
if(!strcmp("page",qs))return new web::page(nullptr,nullptr);
if(!strcmp("chunked",qs))return new web::chunked();
if(!strcmp("chunkedbig",qs))return new web::chunkedbig();
if(!strcmp("chunkedbigger",qs))return new web::chunkedbigger();
return new web::notfound();
}
}
| [
"calin.tenitchi@gmail.com"
] | calin.tenitchi@gmail.com |
43bb556f65c566e003c75690398531f764bbe28b | f6761bd4b74ed9c3bc0e8f62e5a1db70c03096f0 | /aten/src/ATen/native/cpu/PointwiseOpsKernel.cpp | 248392ec0aa5e67c9c76138a6e49deb464184f43 | [
"BSD-2-Clause",
"BSD-3-Clause",
"LicenseRef-scancode-generic-cla",
"Apache-2.0"
] | permissive | MarisaKirisame/pytorch | b638790a0997d776ad4c5e4c77badc77e5dc94f9 | 59c5de4d0eda8d4f5494602034093933600d0a3d | refs/heads/master | 2021-06-19T10:44:33.846286 | 2019-10-31T22:56:55 | 2019-10-31T22:58:28 | 218,881,408 | 2 | 0 | NOASSERTION | 2019-11-01T00:02:51 | 2019-11-01T00:02:51 | null | UTF-8 | C++ | false | false | 3,095 | cpp | // Ternary and higher-order pointwise operations
#include <ATen/ATen.h>
#include <ATen/Dispatch.h>
#include <ATen/native/PointwiseOps.h>
#include <ATen/native/TensorIterator.h>
#include <ATen/native/cpu/Loops.h>
namespace at {
namespace native {
namespace {
static void addcmul_cpu_kernel(TensorIterator& iter, Scalar value) {
ScalarType dtype = iter.dtype(0);
AT_DISPATCH_ALL_TYPES_AND_COMPLEX(dtype, "addcmul_cpu_out", [&] {
scalar_t scalar_val = value.to<scalar_t>();
auto scalar_vec = Vec256<scalar_t>(scalar_val);
cpu_kernel_vec(
iter,
[=](scalar_t self_val, scalar_t t1_val, scalar_t t2_val) -> scalar_t {
return self_val + scalar_val * t1_val * t2_val;
},
[=](Vec256<scalar_t> self_vec,
Vec256<scalar_t> t1_vec,
Vec256<scalar_t> t2_vec) {
return self_vec + scalar_vec * t1_vec * t2_vec;
});
});
}
static void addcdiv_cpu_kernel(TensorIterator& iter, Scalar value) {
ScalarType dtype = iter.dtype(0);
AT_DISPATCH_ALL_TYPES_AND_COMPLEX(dtype, "addcdiv_cpu_out", [&] {
scalar_t scalar_val = value.to<scalar_t>();
auto scalar_vec = Vec256<scalar_t>(scalar_val);
cpu_kernel_vec(
iter,
[=](scalar_t self_val, scalar_t t1_val, scalar_t t2_val) -> scalar_t {
return self_val + scalar_val * t1_val / t2_val;
},
[=](Vec256<scalar_t> self_vec,
Vec256<scalar_t> t1_vec,
Vec256<scalar_t> t2_vec) {
return self_vec + scalar_vec * t1_vec / t2_vec;
});
});
}
static void smooth_l1_backward_cpu_kernel(TensorIterator& iter, Scalar norm) {
ScalarType dtype = iter.dtype(0);
AT_DISPATCH_ALL_TYPES(dtype, "smooth_l1_backward_cpu_out", [&] {
auto norm_val = norm.to<scalar_t>();
cpu_kernel(iter,
[=](scalar_t input, scalar_t target, scalar_t grad_output) -> scalar_t {
const auto x = input - target;
if (x < -1.)
return -norm_val * grad_output;
else if (x > 1.)
return norm_val * grad_output;
else
return norm_val * x * grad_output;
}
);
});
}
static void mse_backward_cpu_kernel(TensorIterator& iter, Scalar value) {
ScalarType dtype = iter.dtype(0);
AT_DISPATCH_ALL_TYPES(dtype, "mse_backward_cpu_out", [&] {
scalar_t scalar_val = value.to<scalar_t>();
auto scalar_vec = Vec256<scalar_t>(scalar_val);
cpu_kernel_vec(
iter,
[=](scalar_t self_val, scalar_t t1_val, scalar_t t2_val) -> scalar_t {
return scalar_val * (self_val - t1_val) * t2_val;
},
[=](Vec256<scalar_t> self_vec,
Vec256<scalar_t> t1_vec,
Vec256<scalar_t> t2_vec) {
return scalar_vec * (self_vec - t1_vec) * t2_vec;
});
});
}
} // anonymous namespace
REGISTER_DISPATCH(addcmul_stub, &addcmul_cpu_kernel);
REGISTER_DISPATCH(addcdiv_stub, &addcdiv_cpu_kernel);
REGISTER_DISPATCH(smooth_l1_backward_stub, &smooth_l1_backward_cpu_kernel);
REGISTER_DISPATCH(mse_backward_stub, &mse_backward_cpu_kernel);
} // namespace native
} // namespace at
| [
"facebook-github-bot@users.noreply.github.com"
] | facebook-github-bot@users.noreply.github.com |
83abd328f151249aaa1a0f7e97caf23eb3f3f08a | 1dbbd823d470a10b1e122f99edff5a5e1b94a7a8 | /dependency/Shared/LogModule.h | ebe69aaca8b00921d2516490d97cd8208a6139f0 | [] | no_license | iwifigame/zhajinhua-project | ee99b31199af45985adb409f9bca9bccbeb99c7c | 85c1398f56e16c645fad4760a5c5f9abe3495781 | refs/heads/master | 2021-01-19T13:11:14.723484 | 2013-03-22T13:42:07 | 2013-03-22T13:42:07 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,920 | h | /********************************************************************
Copyright (C) 2013 by Alden Pang
@date: 2012-1-20 16:03
@file: LogModule.h
@author: Alden Pang
@desc:
*********************************************************************/
#ifndef _LOGMODULE_H_
#define _LOGMODULE_H_
#include <QString>
#include <QList>
#include <QQueue>
#include <QFile>
#include <QThread>
#include <QtNetwork>
#include <QSharedPointer>
/** */
enum LogLevel
{
LL_INFO=0,
LL_WARN,
LL_ERROR,
LL_TOTAL
};
class LogModule : public QObject
{
Q_OBJECT
public:
~LogModule(){};
static LogModule& GetSingleton()
{
static LogModule singleton;
return singleton;
}
public slots:
void SetOutputLevel(LogLevel _level){mLevel = _level;}
void StInfo(const QString& _text);
void StWarn(const QString& _text);
void StError(const QString& _text);
public:
void SetModuleName(const QString _fileName){ mLogFileName = _fileName; }
protected:
private:
LogModule();
LogLevel mLevel;
QString mLogDir;
QString mLogFileName;
QString mTodayStr;
void writeToFile(LogLevel _level, QString _log);
};
#define LOG LogModule::GetSingleton()
//#define DEF_LOG signals: void SiInfo(const QString& _text);void SiWarn(const QString& _text);void SiError(const QString& _text);
#define LOG_INFO(x) emit SiInfo(QString("[%1]-%2").arg(__FUNCTION__).arg(x))
#define LOG_WARN(x) emit SiWarn(QString("[%1]-%2").arg(__FUNCTION__).arg(x))
#define LOG_ERR(x) emit SiError(QString("[%1]-%2").arg(__FUNCTION__).arg(x))
#define LOG_D_INFO(x) LOG.StInfo(QString("[%1]-%2").arg(__FUNCTION__).arg(x))
#define LOG_D_WARN(x) LOG.StWarn(QString("[%1]-%2").arg(__FUNCTION__).arg(x))
#define LOG_D_ERR(x) LOG.StError(QString("[%1]-%2").arg(__FUNCTION__).arg(x))
#endif //_LOGMODULE_H_
/*
*
* [Revision 1.0 2012-1-20 16:03 Administrator] Created
*
*/ | [
"pangshuo1981@gmail.com@d8f4ed1e-bbb0-a400-853e-1b27d4c80825"
] | pangshuo1981@gmail.com@d8f4ed1e-bbb0-a400-853e-1b27d4c80825 |
a7db9b26ecd045926a29624c8c1852cb85bd3f23 | 950b506e3f8fd978f076a5b9a3a950f6f4d5607b | /cf/vkcup-2018/qual-1/C.cpp | d636a75893510e816f94adc054bdce9847c6961d | [] | no_license | Mityai/contests | 2e130ebb8d4280b82e7e017037fc983063228931 | 5b406b2a94cc487b0c71cb10386d1b89afd1e143 | refs/heads/master | 2021-01-09T06:09:17.441079 | 2019-01-19T12:47:20 | 2019-01-19T12:47:20 | 80,909,953 | 4 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,637 | cpp | #include <bits/stdc++.h>
#define proj asdajslkdjalskd
using namespace std;
using proj = pair<string, int>;
int main() {
#if __APPLE__
freopen("C.in", "r", stdin);
freopen("C.out", "w", stdout);
#endif
ios_base::sync_with_stdio(false);
size_t n;
while (cin >> n) {
map<proj, vector<proj>> g;
proj polycarp;
for (size_t i = 0; i < n; ++i) {
proj current;
cin >> current.first >> current.second;
if (i == 0) polycarp = current;
size_t deps;
cin >> deps;
auto& cur_g = g[current];
cur_g.resize(deps);
for (size_t j = 0; j < deps; ++j) {
cin >> cur_g[j].first >> cur_g[j].second;
}
}
set<proj> alldeps;
set<string> used = {polycarp.first};
map<string, int> cur_lvl = {polycarp};
while (!cur_lvl.empty()) {
map<string, int> next_lvl;
for (const auto& cur_proj : cur_lvl) {
for (const auto& [name, version] : g[cur_proj]) {
if (used.find(name) == used.end()) {
next_lvl[name] = max(next_lvl[name], version);
}
}
}
alldeps.insert(next_lvl.begin(), next_lvl.end());
for (const auto& [name, version] : next_lvl) {
used.insert(name);
}
cur_lvl.swap(next_lvl);
}
cout << alldeps.size() << '\n';
for (const auto& [name, version] : alldeps) {
cout << name << ' ' << version << '\n';
}
}
}
| [
"dimaz1301@gmail.com"
] | dimaz1301@gmail.com |
bb29049e91202ff876eab9978357858985addbb9 | eab27b0a2cf9e4ea42ba305c771bd4272a58a518 | /src/cloud_filters/radius_outlier_removal.cpp | a9d2cf91212c8ee10d88e561106a5ecbfc7d478e | [
"BSD-3-Clause"
] | permissive | myalfred03/dynamic_robot_localization | fa1ce87d23dba8f40d763bac73aec53d6e74b9c8 | d26e4563ab98171ae724a527a2c63d1b1abb1843 | refs/heads/kinetic-devel | 2020-04-03T14:28:48.608738 | 2018-10-17T17:48:36 | 2018-10-17T17:48:36 | 155,323,125 | 0 | 0 | BSD-3-Clause | 2019-01-12T22:57:23 | 2018-10-30T04:12:11 | C++ | UTF-8 | C++ | false | false | 1,262 | cpp | /**\file radius_outlier_removal.cpp
* \brief Description...
*
* @version 1.0
* @author Carlos Miguel Correia da Costa
*/
// >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>> <includes> <<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<
#include <dynamic_robot_localization/common/common.h>
#include <dynamic_robot_localization/cloud_filters/impl/radius_outlier_removal.hpp>
// >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>> </includes> <<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<
// >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>> <template instantiations> <<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<
#ifndef DRL_NO_PRECOMPILE
#include <pcl/impl/instantiate.hpp>
#include <pcl/point_types.h>
#define PCL_INSTANTIATE_DRLRadiusOutlierRemoval(T) template class PCL_EXPORTS dynamic_robot_localization::RadiusOutlierRemoval<T>;
PCL_INSTANTIATE(DRLRadiusOutlierRemoval, DRL_POINT_TYPES)
#endif
// >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>> </template instantiations> <<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<
| [
"carloscosta.cmcc@gmail.com"
] | carloscosta.cmcc@gmail.com |
361e83aed4895ff69b67636e7141a3203c966ad7 | 39320b80b4aa862c0d545e85bd2dd88f2585bdce | /src/server/scripts/EasternKingdoms/ZulGurub/instance_zulgurub.cpp | 0b1deea43223d6e9d9bc256e036edf82ad359e47 | [] | no_license | ProjectStarGate/StarGate-Plus-EMU | ec8c8bb4fab9f6d3432d76b2afac1e1e7ec3249f | 8e75d2976ae863557992e69353a23af759346eae | refs/heads/master | 2021-01-15T12:25:53.949001 | 2011-12-21T06:04:07 | 2011-12-21T06:04:07 | 3,004,543 | 3 | 2 | null | null | null | null | UTF-8 | C++ | false | false | 5,642 | cpp | /*
* Copyright (C) 2005-2011 MaNGOS <http://www.getmangos.com/>
*
* Copyright (C) 2008-2011 Trinity <http://www.trinitycore.org/>
*
* Copyright (C) 2006-2011 ScriptDev2 <http://www.scriptdev2.com/>
*
* Copyright (C) 2010-2011 ProjectSkyfire <http://www.projectskyfire.org/>
*
* Copyright (C) 2010-2012 Project-StarGate-Emu
*
* 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
*/
/* ScriptData
SDName: Instance_ZulGurub
SD%Complete: 80
SDComment: Missing reset function after killing a boss for Ohgan, Thekal.
SDCategory: Zul'Gurub
EndScriptData */
#include "ScriptPCH.h"
#include "zulgurub.h"
class instance_zulgurub : public InstanceMapScript
{
public:
instance_zulgurub()
: InstanceMapScript("instance_zulgurub", 309)
{
}
struct instance_zulgurub_InstanceMapScript : public InstanceScript
{
instance_zulgurub_InstanceMapScript(Map* pMap) : InstanceScript(pMap) {Initialize();};
//If all High Priest bosses were killed. Lorkhan, Zath and Ohgan are added too.
uint32 m_auiEncounter[MAX_ENCOUNTERS];
//Storing Lorkhan, Zath and Thekal because we need to cast on them later. Jindo is needed for healfunction too.
uint64 m_uiLorKhanGUID;
uint64 m_uiZathGUID;
uint64 m_uiThekalGUID;
uint64 m_uiJindoGUID;
void Initialize()
{
memset(&m_auiEncounter, 0, sizeof(m_auiEncounter));
m_uiLorKhanGUID = 0;
m_uiZathGUID = 0;
m_uiThekalGUID = 0;
m_uiJindoGUID = 0;
}
bool IsEncounterInProgress() const
{
//not active in Zul'Gurub
return false;
}
void OnCreatureCreate(Creature* creature)
{
switch(creature->GetEntry())
{
case 11347: m_uiLorKhanGUID = creature->GetGUID(); break;
case 11348: m_uiZathGUID = creature->GetGUID(); break;
case 14509: m_uiThekalGUID = creature->GetGUID(); break;
case 11380: m_uiJindoGUID = creature->GetGUID(); break;
}
}
void SetData(uint32 uiType, uint32 uiData)
{
switch(uiType)
{
case TYPE_ARLOKK:
m_auiEncounter[0] = uiData;
break;
case TYPE_JEKLIK:
m_auiEncounter[1] = uiData;
break;
case TYPE_VENOXIS:
m_auiEncounter[2] = uiData;
break;
case TYPE_MARLI:
m_auiEncounter[3] = uiData;
break;
case TYPE_THEKAL:
m_auiEncounter[4] = uiData;
break;
case TYPE_LORKHAN:
m_auiEncounter[5] = uiData;
break;
case TYPE_ZATH:
m_auiEncounter[6] = uiData;
break;
case TYPE_OHGAN:
m_auiEncounter[7] = uiData;
break;
}
}
uint32 GetData(uint32 uiType)
{
switch(uiType)
{
case TYPE_ARLOKK:
return m_auiEncounter[0];
case TYPE_JEKLIK:
return m_auiEncounter[1];
case TYPE_VENOXIS:
return m_auiEncounter[2];
case TYPE_MARLI:
return m_auiEncounter[3];
case TYPE_THEKAL:
return m_auiEncounter[4];
case TYPE_LORKHAN:
return m_auiEncounter[5];
case TYPE_ZATH:
return m_auiEncounter[6];
case TYPE_OHGAN:
return m_auiEncounter[7];
}
return 0;
}
uint64 GetData64(uint32 uiData)
{
switch(uiData)
{
case DATA_LORKHAN:
return m_uiLorKhanGUID;
case DATA_ZATH:
return m_uiZathGUID;
case DATA_THEKAL:
return m_uiThekalGUID;
case DATA_JINDO:
return m_uiJindoGUID;
}
return 0;
}
};
InstanceScript* GetInstanceScript(InstanceMap* pMap) const
{
return new instance_zulgurub_InstanceMapScript(pMap);
}
};
void AddSC_instance_zulgurub()
{
new instance_zulgurub();
} | [
"sharkipaust@web.de"
] | sharkipaust@web.de |
614a9037776bfda2a144fe0a646c5ae41b3125c8 | 4e0a2e6e8136b54995594b43b2a71d75614a52bf | /ACM-2011-practise/ZOJ/The_8th_Zhejiang_Provincial_Collegiate_Programming_Contest/ProF.cpp | 16a21efccae41a033201608a88c7694fdbab0ab8 | [] | no_license | AlbertWang0116/KrwlngsACMFile | 884c84ba0afff0727448fc5b5b27b5cb76330936 | 23f0d9f6834f2b4fb2604ecbd50d5c41dd994b8f | refs/heads/master | 2023-06-21T09:25:28.528059 | 2023-06-11T19:18:40 | 2023-06-11T19:18:40 | 2,345,592 | 1 | 2 | null | null | null | null | UTF-8 | C++ | false | false | 666 | cpp | #include<iostream>
#include<cstdio>
#include<string>
#include<cstring>
#include<cstdlib>
#include<ctime>
#include<cmath>
#include<algorithm>
using namespace std;
#define N 110
#define M 30
char name[N][M], frt[M];
int n, idx;
void input()
{
int i;
scanf("%d", &n);
scanf("%s", frt);
for (i = 0; i < n; ++i)
{
scanf("%s", name[i]);
if (!strcmp(name[i], frt)) idx = i;
}
}
void conduct()
{
idx = (idx + n / 2) % n;
cout << name[idx] << endl;
}
int main()
{
//freopen("input.txt", "r", stdin);
//freopen("output.txt", "w", stdout);
int time;
scanf("%d", &time);
while (time--)
{
input();
conduct();
}
//fclose(stdin);
//fclose(stdout);
}
| [
"st.krwlng@gmail.com"
] | st.krwlng@gmail.com |
cf6e44baa7f53e472f5cd3e7a69f2dc8b4ffa729 | 9a234fe9a4c333a80af259de73223554adc9cdec | /integration/jnifuse/native/src/main/native/libjnifuse/jnifuse_helper.cc | f3fa5d879d9e9f1c12921262329d9c91e530f246 | [
"MIT",
"EPL-1.0",
"LicenseRef-scancode-proprietary-license",
"CC0-1.0",
"Apache-2.0",
"Unlicense",
"LicenseRef-scancode-warranty-disclaimer",
"BSD-2-Clause",
"BSD-3-Clause",
"CC-PDDC",
"LicenseRef-scancode-public-domain",
"LicenseRef-scancode-free-unknown"
] | permissive | Xaprice/alluxio | 442d81d02a95f1e0ad10ebfb44b9ed225f385775 | 3b533206f57f4c5c4b82fc5e0ba30d6d3483ef6b | refs/heads/master | 2022-02-06T12:39:28.023369 | 2022-01-13T03:25:53 | 2022-01-13T03:25:53 | 177,709,387 | 0 | 0 | Apache-2.0 | 2019-03-26T03:37:03 | 2019-03-26T03:37:03 | null | UTF-8 | C++ | false | false | 3,265 | cc | /*
* The Alluxio Open Foundation licenses this work under the Apache License, version 2.0
* (the "License"). You may not use this work except in compliance with the License, which is
* available at www.apache.org/licenses/LICENSE-2.0
*
* This software is distributed on an "AS IS" basis, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND,
* either express or implied, as more fully set forth in the License.
*
* See the NOTICE file distributed with this work for information regarding copyright ownership.
*/
#ifndef FUSE_USE_VERSION
#define FUSE_USE_VERSION 26
#endif
#include <errno.h>
#include <fcntl.h>
#include <fuse.h>
#include <jni.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "debug.h"
#include "jnifuse_fs.h"
#include "jnifuse_impls.h"
#ifdef __cplusplus
extern "C" {
#endif
static struct fuse_operations jnifuse_oper;
JNIEXPORT jint JNICALL Java_alluxio_jnifuse_LibFuse_fuse_1main_1real(
JNIEnv *env, jobject libfuseobj, jobject obj, jint jargc,
jobjectArray jargv) {
LOGD("enter fuse_main_real");
jnifuse::JniFuseFileSystem::init(env, obj);
int argc = jargc;
LOGD("argc=%d", argc);
char **argv = (char **)malloc(sizeof(char *) * argc);
for (int i = 0; i < argc; i++) {
jstring str = (jstring)env->GetObjectArrayElement(jargv, i);
argv[i] = (char *)env->GetStringUTFChars(str, 0);
LOGD("argv[%d]=%s", i, argv[i]);
}
jnifuse_oper.chmod = chmod_wrapper;
jnifuse_oper.chown = chown_wrapper;
jnifuse_oper.create = create_wrapper;
jnifuse_oper.flush = flush_wrapper;
jnifuse_oper.getattr = getattr_wrapper;
jnifuse_oper.getxattr = getxattr_wrapper;
jnifuse_oper.listxattr = listxattr_wrapper;
jnifuse_oper.mkdir = mkdir_wrapper;
jnifuse_oper.open = open_wrapper;
jnifuse_oper.read = read_wrapper;
jnifuse_oper.readdir = readdir_wrapper;
jnifuse_oper.release = release_wrapper;
jnifuse_oper.removexattr = removexattr_wrapper;
jnifuse_oper.rename = rename_wrapper;
jnifuse_oper.rmdir = rmdir_wrapper;
jnifuse_oper.setxattr = setxattr_wrapper;
jnifuse_oper.symlink = symlink_wrapper;
jnifuse_oper.truncate = truncate_wrapper;
jnifuse_oper.unlink = unlink_wrapper;
jnifuse_oper.utimens = utimens_wrapper;
jnifuse_oper.write = write_wrapper;
int ret = fuse_main_real(argc, argv, &jnifuse_oper,
sizeof(struct fuse_operations), NULL);
free(argv);
return ret;
}
jint JNICALL Java_alluxio_jnifuse_FuseFillDir_fill(JNIEnv *env, jclass cls,
jlong address, jlong bufaddr,
jstring name, jobject stbuf,
jlong off) {
LOGD("enter fill");
fuse_fill_dir_t filler = (fuse_fill_dir_t)(void *)address;
const char *fn = env->GetStringUTFChars(name, 0);
int ret = filler((void *)bufaddr, fn, NULL, 0);
env->ReleaseStringUTFChars(name, fn);
return ret;
}
jobject JNICALL Java_alluxio_jnifuse_LibFuse_fuse_1get_1context(JNIEnv *env, jobject obj) {
LOGD("enter get_fuse_context");
struct fuse_context *cxt = fuse_get_context();
jobject fibuf =
env->NewDirectByteBuffer((void *)cxt, sizeof(struct fuse_context));
return fibuf;
}
#ifdef __cplusplus
}
#endif
| [
"noreply@github.com"
] | Xaprice.noreply@github.com |
39fdcca7269687757c9612d145d3e719b9c4ab4d | 93183bb5313c7eb85268fdeb1ebfde02f26cca75 | /src/rpc/rawtransaction.cpp | ee1817c1dcfee361e2e20a286606a8380222c9bc | [] | no_license | puzcoin/stakework | 9e600a6ace0c8f5a22842478d657fd940564aee7 | 97725197706b86a6ae3816bc5ffbbe87a57e8d96 | refs/heads/master | 2021-01-08T23:13:21.772438 | 2020-02-21T18:20:43 | 2020-02-21T18:20:43 | 242,171,332 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 47,803 | cpp | // Copyright (c) 2010 Satoshi Nakamoto
// Copyright (c) 2009-2015 The Bitcoin Core developers
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include <base58.h>
#include <chain.h>
#include <coins.h>
#include <consensus/validation.h>
#include <core_io.h>
#include <init.h>
#include <keystore.h>
#include <main.h>
#include <merkleblock.h>
#include <net.h>
#include <policy/policy.h>
#include <primitives/transaction.h>
#include <rpc/server.h>
#include <script/script.h>
#include <script/script_error.h>
#include <script/sign.h>
#include <script/standard.h>
#include <txmempool.h>
#include <uint256.h>
#include <timedata.h>
#include <utilstrencodings.h>
#ifdef ENABLE_WALLET
#include <wallet/wallet.h>
#endif
#include <stdint.h>
#include <boost/assign/list_of.hpp>
#include <univalue.h>
using namespace std;
void ScriptPubKeyToJSON(const CScript& scriptPubKey, UniValue& out, bool fIncludeHex)
{
txnouttype type;
vector<CTxDestination> addresses;
int nRequired;
out.pushKV("asm", ScriptToAsmStr(scriptPubKey));
if (fIncludeHex)
out.pushKV("hex", HexStr(scriptPubKey.begin(), scriptPubKey.end()));
if (!ExtractDestinations(scriptPubKey, type, addresses, nRequired)) {
out.pushKV("type", GetTxnOutputType(type));
return;
}
out.pushKV("reqSigs", nRequired);
out.pushKV("type", GetTxnOutputType(type));
if (type == TX_PAYMENTREQUESTNOVOTE || type == TX_PAYMENTREQUESTYESVOTE
|| type == TX_PROPOSALNOVOTE || type == TX_PROPOSALYESVOTE)
{
vector<std::vector<unsigned char>> vSolutions;
txnouttype whichType;
if (Solver(scriptPubKey, whichType, vSolutions))
{
out.pushKV("hash", uint256(vSolutions[0]).ToString());
}
}
else
{
UniValue a(UniValue::VARR);
for(const CTxDestination& addr: addresses)
a.push_back(CStakeWorkAddress(addr).ToString());
out.pushKV("addresses", a);
}
}
void TxToJSONExpanded(const CTransaction& tx, const uint256 hashBlock, UniValue& entry,
int nHeight = 0, int nConfirmations = 0, int nBlockTime = 0)
{
uint256 txid = tx.GetHash();
entry.pushKV("txid", txid.GetHex());
entry.pushKV("hash", tx.GetWitnessHash().GetHex());
entry.pushKV("size", (int)::GetSerializeSize(tx, SER_NETWORK, PROTOCOL_VERSION));
entry.pushKV("vsize", (int)::GetVirtualTransactionSize(tx));
entry.pushKV("version", tx.nVersion);
entry.pushKV("locktime", (int64_t)tx.nLockTime);
entry.pushKV("strdzeel", tx.strDZeel);
UniValue vin(UniValue::VARR);
for (unsigned int i = 0; i < tx.vin.size(); i++) {
const CTxIn& txin = tx.vin[i];
UniValue in(UniValue::VOBJ);
if (tx.IsCoinBase())
in.pushKV("coinbase", HexStr(txin.scriptSig.begin(), txin.scriptSig.end()));
else {
in.pushKV("txid", txin.prevout.hash.GetHex());
in.pushKV("vout", (int64_t)txin.prevout.n);
UniValue o(UniValue::VOBJ);
o.pushKV("asm", ScriptToAsmStr(txin.scriptSig, true));
o.pushKV("hex", HexStr(txin.scriptSig.begin(), txin.scriptSig.end()));
in.pushKV("scriptSig", o);
// Add address and value info if spentindex enabled
CSpentIndexValue spentInfo;
CSpentIndexKey spentKey(txin.prevout.hash, txin.prevout.n);
if (GetSpentIndex(spentKey, spentInfo)) {
in.pushKV("value", ValueFromAmount(spentInfo.satoshis));
in.pushKV("valueSat", spentInfo.satoshis);
if (spentInfo.addressType == 1) {
in.pushKV("address", CStakeWorkAddress(CKeyID(spentInfo.addressHash)).ToString());
} else if (spentInfo.addressType == 2) {
in.pushKV("address", CStakeWorkAddress(CScriptID(spentInfo.addressHash)).ToString());
}
}
}
if (!tx.wit.IsNull()) {
if (!tx.wit.vtxinwit[i].IsNull()) {
UniValue txinwitness(UniValue::VARR);
for (unsigned int j = 0; j < tx.wit.vtxinwit[i].scriptWitness.stack.size(); j++) {
std::vector<unsigned char> item = tx.wit.vtxinwit[i].scriptWitness.stack[j];
txinwitness.push_back(HexStr(item.begin(), item.end()));
}
in.pushKV("txinwitness", txinwitness);
}
}
in.pushKV("sequence", (int64_t)txin.nSequence);
vin.push_back(in);
}
entry.pushKV("vin", vin);
UniValue vout(UniValue::VARR);
for (unsigned int i = 0; i < tx.vout.size(); i++) {
const CTxOut& txout = tx.vout[i];
UniValue out(UniValue::VOBJ);
out.pushKV("value", ValueFromAmount(txout.nValue));
out.pushKV("valueSat", txout.nValue);
out.pushKV("n", (int64_t)i);
UniValue o(UniValue::VOBJ);
ScriptPubKeyToJSON(txout.scriptPubKey, o, true);
out.pushKV("scriptPubKey", o);
// Add spent information if spentindex is enabled
CSpentIndexValue spentInfo;
CSpentIndexKey spentKey(txid, i);
if (GetSpentIndex(spentKey, spentInfo)) {
out.pushKV("spentTxId", spentInfo.txid.GetHex());
out.pushKV("spentIndex", (int)spentInfo.inputIndex);
out.pushKV("spentHeight", spentInfo.blockHeight);
}
vout.push_back(out);
}
entry.pushKV("vout", vout);
if (!hashBlock.IsNull()) {
entry.pushKV("blockhash", hashBlock.GetHex());
if (nConfirmations > 0) {
entry.pushKV("height", nHeight);
entry.pushKV("confirmations", nConfirmations);
entry.pushKV("time", nBlockTime);
entry.pushKV("blocktime", nBlockTime);
} else {
entry.pushKV("height", -1);
entry.pushKV("confirmations", 0);
}
}
}
void TxToJSON(const CTransaction& tx, const uint256 hashBlock, UniValue& entry)
{
entry.pushKV("txid", tx.GetHash().GetHex());
entry.pushKV("hash", tx.GetWitnessHash().GetHex());
entry.pushKV("size", (int)::GetSerializeSize(tx, SER_NETWORK, PROTOCOL_VERSION));
entry.pushKV("vsize", (int)::GetVirtualTransactionSize(tx));
entry.pushKV("version", tx.nVersion);
entry.pushKV("locktime", (int64_t)tx.nLockTime);
entry.pushKV("time", (int64_t)tx.nTime);
entry.pushKV("strdzeel", tx.strDZeel);
UniValue vin(UniValue::VARR);
for (unsigned int i = 0; i < tx.vin.size(); i++) {
const CTxIn& txin = tx.vin[i];
UniValue in(UniValue::VOBJ);
if (tx.IsCoinBase())
in.pushKV("coinbase", HexStr(txin.scriptSig.begin(), txin.scriptSig.end()));
else {
in.pushKV("txid", txin.prevout.hash.GetHex());
in.pushKV("vout", (int64_t)txin.prevout.n);
UniValue o(UniValue::VOBJ);
o.pushKV("asm", ScriptToAsmStr(txin.scriptSig, true));
o.pushKV("hex", HexStr(txin.scriptSig.begin(), txin.scriptSig.end()));
in.pushKV("scriptSig", o);
}
if (!tx.wit.IsNull()) {
if (!tx.wit.vtxinwit[i].IsNull()) {
UniValue txinwitness(UniValue::VARR);
for (unsigned int j = 0; j < tx.wit.vtxinwit[i].scriptWitness.stack.size(); j++) {
std::vector<unsigned char> item = tx.wit.vtxinwit[i].scriptWitness.stack[j];
txinwitness.push_back(HexStr(item.begin(), item.end()));
}
in.pushKV("txinwitness", txinwitness);
}
}
in.pushKV("sequence", (int64_t)txin.nSequence);
vin.push_back(in);
}
entry.pushKV("vin", vin);
UniValue vout(UniValue::VARR);
for (unsigned int i = 0; i < tx.vout.size(); i++) {
const CTxOut& txout = tx.vout[i];
UniValue out(UniValue::VOBJ);
out.pushKV("value", ValueFromAmount(txout.nValue));
out.pushKV("valueSat", txout.nValue);
out.pushKV("n", (int64_t)i);
UniValue o(UniValue::VOBJ);
ScriptPubKeyToJSON(txout.scriptPubKey, o, true);
out.pushKV("scriptPubKey", o);
vout.push_back(out);
}
entry.pushKV("vout", vout);
if (!hashBlock.IsNull()) {
entry.pushKV("blockhash", hashBlock.GetHex());
BlockMap::iterator mi = mapBlockIndex.find(hashBlock);
if (mi != mapBlockIndex.end() && (*mi).second) {
CBlockIndex* pindex = (*mi).second;
if (chainActive.Contains(pindex)) {
entry.pushKV("height", pindex->nHeight);
entry.pushKV("confirmations", 1 + chainActive.Height() - pindex->nHeight);
entry.pushKV("time", pindex->GetBlockTime());
entry.pushKV("blocktime", pindex->GetBlockTime());
} else {
entry.pushKV("height", -1);
entry.pushKV("confirmations", 0);
}
}
}
}
UniValue getrawtransaction(const UniValue& params, bool fHelp)
{
if (fHelp || params.size() < 1 || params.size() > 2)
throw runtime_error(
"getrawtransaction \"txid\" ( verbose )\n"
"\nNOTE: By default this function only works sometimes. This is when the tx is in the mempool\n"
"or there is an unspent output in the utxo for this transaction. To make it always work,\n"
"you need to maintain a transaction index, using the -txindex command line option.\n"
"\nReturn the raw transaction data.\n"
"\nIf verbose=0, returns a string that is serialized, hex-encoded data for 'txid'.\n"
"If verbose is non-zero, returns an Object with information about 'txid'.\n"
"\nArguments:\n"
"1. \"txid\" (string, required) The transaction id\n"
"2. verbose (numeric|boolean, optional, default=0) If 0|false, return a string, other return a json object\n"
"\nResult (if verbose is not set or set to 0):\n"
"\"data\" (string) The serialized, hex-encoded data for 'txid'\n"
"\nResult (if verbose > 0):\n"
"{\n"
" \"hex\" : \"data\", (string) The serialized, hex-encoded data for 'txid'\n"
" \"txid\" : \"id\", (string) The transaction id (same as provided)\n"
" \"hash\" : \"id\", (string) The transaction hash (differs from txid for witness transactions)\n"
" \"size\" : n, (numeric) The serialized transaction size\n"
" \"vsize\" : n, (numeric) The virtual transaction size (differs from size for witness transactions)\n"
" \"version\" : n, (numeric) The version\n"
" \"locktime\" : ttt, (numeric) The lock time\n"
" \"vin\" : [ (array of json objects)\n"
" {\n"
" \"txid\": \"id\", (string) The transaction id\n"
" \"vout\": n, (numeric) \n"
" \"scriptSig\": { (json object) The script\n"
" \"asm\": \"asm\", (string) asm\n"
" \"hex\": \"hex\" (string) hex\n"
" },\n"
" \"sequence\": n (numeric) The script sequence number\n"
" \"txinwitness\": [\"hex\", ...] (array of string) hex-encoded witness data (if any)\n"
" }\n"
" ,...\n"
" ],\n"
" \"vout\" : [ (array of json objects)\n"
" {\n"
" \"value\" : x.xxx, (numeric) The value in " + CURRENCY_UNIT + "\n"
" \"n\" : n, (numeric) index\n"
" \"scriptPubKey\" : { (json object)\n"
" \"asm\" : \"asm\", (string) the asm\n"
" \"hex\" : \"hex\", (string) the hex\n"
" \"reqSigs\" : n, (numeric) The required sigs\n"
" \"type\" : \"pubkeyhash\", (string) The type, eg 'pubkeyhash'\n"
" \"addresses\" : [ (json array of string)\n"
" \"stakeworkaddress\" (string) stakework address\n"
" ,...\n"
" ]\n"
" }\n"
" }\n"
" ,...\n"
" ],\n"
" \"blockhash\" : \"hash\", (string) the block hash\n"
" \"confirmations\" : n, (numeric) The confirmations\n"
" \"time\" : ttt, (numeric) The transaction time in seconds since epoch (Jan 1 1970 GMT)\n"
" \"blocktime\" : ttt (numeric) The block time in seconds since epoch (Jan 1 1970 GMT)\n"
"}\n"
"\nExamples:\n"
+ HelpExampleCli("getrawtransaction", "\"mytxid\"")
+ HelpExampleCli("getrawtransaction", "\"mytxid\" 1")
+ HelpExampleRpc("getrawtransaction", "\"mytxid\", 1")
+ HelpExampleRpc("getrawtransaction", "\"mytxid\" true")
+ HelpExampleRpc("getrawtransaction", "\"mytxid\", true")
);
uint256 hash = ParseHashV(params[0], "parameter 1");
bool fVerbose = false;
if (params.size() > 1 && !params[1].isNull()) {
if (params[1].isNum()) {
if (params[1].get_int() != 0) {
fVerbose = true;
}
}
else if(params[1].isBool()) {
if (params[1].isTrue()) {
fVerbose = true;
}
}
else {
throw JSONRPCError(RPC_TYPE_ERROR, "Invalid type provided. Verbose parameter must be an int or boolean.");
}
}
CTransaction tx;
uint256 hashBlock;
int nHeight = 0;
int nConfirmations = 0;
int nBlockTime = 0;
{
LOCK(cs_main);
CCoinsViewCache view(pcoinsTip);
if (!GetTransaction(hash, tx, Params().GetConsensus(), hashBlock, view, true))
throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "No information available about transaction");
BlockMap::iterator mi = mapBlockIndex.find(hashBlock);
if (mi != mapBlockIndex.end() && (*mi).second) {
CBlockIndex* pindex = (*mi).second;
if (chainActive.Contains(pindex)) {
nHeight = pindex->nHeight;
nConfirmations = 1 + chainActive.Height() - pindex->nHeight;
nBlockTime = pindex->GetBlockTime();
} else {
nHeight = -1;
nConfirmations = 0;
nBlockTime = pindex->GetBlockTime();
}
}
}
string strHex = EncodeHexTx(tx);
if (!fVerbose)
return strHex;
UniValue result(UniValue::VOBJ);
result.pushKV("hex", strHex);
TxToJSONExpanded(tx, hashBlock, result, nHeight, nConfirmations, nBlockTime);
return result;
}
UniValue gettxoutproof(const UniValue& params, bool fHelp)
{
if (fHelp || (params.size() != 1 && params.size() != 2))
throw runtime_error(
"gettxoutproof [\"txid\",...] ( blockhash )\n"
"\nReturns a hex-encoded proof that \"txid\" was included in a block.\n"
"\nNOTE: By default this function only works sometimes. This is when there is an\n"
"unspent output in the utxo for this transaction. To make it always work,\n"
"you need to maintain a transaction index, using the -txindex command line option or\n"
"specify the block in which the transaction is included manually (by blockhash).\n"
"\nReturn the raw transaction data.\n"
"\nArguments:\n"
"1. \"txids\" (string) A json array of txids to filter\n"
" [\n"
" \"txid\" (string) A transaction hash\n"
" ,...\n"
" ]\n"
"2. \"block hash\" (string, optional) If specified, looks for txid in the block with this hash\n"
"\nResult:\n"
"\"data\" (string) A string that is a serialized, hex-encoded data for the proof.\n"
);
set<uint256> setTxids;
uint256 oneTxid;
UniValue txids = params[0].get_array();
for (unsigned int idx = 0; idx < txids.size(); idx++) {
const UniValue& txid = txids[idx];
if (txid.get_str().length() != 64 || !IsHex(txid.get_str()))
throw JSONRPCError(RPC_INVALID_PARAMETER, string("Invalid txid ")+txid.get_str());
uint256 hash(uint256S(txid.get_str()));
if (setTxids.count(hash))
throw JSONRPCError(RPC_INVALID_PARAMETER, string("Invalid parameter, duplicated txid: ")+txid.get_str());
setTxids.insert(hash);
oneTxid = hash;
}
LOCK(cs_main);
CBlockIndex* pblockindex = nullptr;
uint256 hashBlock;
if (params.size() > 1)
{
hashBlock = uint256S(params[1].get_str());
if (!mapBlockIndex.count(hashBlock))
throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Block not found");
pblockindex = mapBlockIndex[hashBlock];
} else {
CCoins coins;
if (pcoinsTip->GetCoins(oneTxid, coins) && coins.nHeight > 0 && coins.nHeight <= chainActive.Height())
pblockindex = chainActive[coins.nHeight];
}
if (pblockindex == nullptr)
{
CTransaction tx;
CCoinsViewCache view(pcoinsTip);
if (!GetTransaction(oneTxid, tx, Params().GetConsensus(), hashBlock, view, false) || hashBlock.IsNull())
throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Transaction not yet in block");
if (!mapBlockIndex.count(hashBlock))
throw JSONRPCError(RPC_INTERNAL_ERROR, "Transaction index corrupt");
pblockindex = mapBlockIndex[hashBlock];
}
CBlock block;
if(!ReadBlockFromDisk(block, pblockindex, Params().GetConsensus()))
throw JSONRPCError(RPC_INTERNAL_ERROR, "Can't read block from disk");
unsigned int ntxFound = 0;
for(const CTransaction&tx: block.vtx)
if (setTxids.count(tx.GetHash()))
ntxFound++;
if (ntxFound != setTxids.size())
throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "(Not all) transactions not found in specified block");
CDataStream ssMB(SER_NETWORK, PROTOCOL_VERSION | SERIALIZE_TRANSACTION_NO_WITNESS);
CMerkleBlock mb(block, setTxids);
ssMB << mb;
std::string strHex = HexStr(ssMB.begin(), ssMB.end());
return strHex;
}
UniValue verifytxoutproof(const UniValue& params, bool fHelp)
{
if (fHelp || params.size() != 1)
throw runtime_error(
"verifytxoutproof \"proof\"\n"
"\nVerifies that a proof points to a transaction in a block, returning the transaction it commits to\n"
"and throwing an RPC error if the block is not in our best chain\n"
"\nArguments:\n"
"1. \"proof\" (string, required) The hex-encoded proof generated by gettxoutproof\n"
"\nResult:\n"
"[\"txid\"] (array, strings) The txid(s) which the proof commits to, or empty array if the proof is invalid\n"
);
CDataStream ssMB(ParseHexV(params[0], "proof"), SER_NETWORK, PROTOCOL_VERSION | SERIALIZE_TRANSACTION_NO_WITNESS);
CMerkleBlock merkleBlock;
ssMB >> merkleBlock;
UniValue res(UniValue::VARR);
vector<uint256> vMatch;
vector<unsigned int> vIndex;
if (merkleBlock.txn.ExtractMatches(vMatch, vIndex) != merkleBlock.header.hashMerkleRoot)
return res;
LOCK(cs_main);
if (!mapBlockIndex.count(merkleBlock.header.GetHash()) || !chainActive.Contains(mapBlockIndex[merkleBlock.header.GetHash()]))
throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Block not found in chain");
for(const uint256& hash: vMatch)
res.push_back(hash.GetHex());
return res;
}
UniValue createrawtransaction(const UniValue& params, bool fHelp)
{
if (fHelp || params.size() < 2 || params.size() > 5)
throw runtime_error(
"createrawtransaction [{\"txid\":\"id\",\"vout\":n},...] {\"address\":amount,\"data\":\"hex\",...} [strdzeel] [index] [toggle-input-dump]\n"
"\nCreate a transaction spending the given inputs and creating new outputs.\n"
"Outputs can be addresses or data.\n"
"Returns hex-encoded raw transaction.\n"
"Note that the transaction's inputs are not signed, and\n"
"it is not stored in the wallet or transmitted to the network.\n"
"\nArguments:\n"
"1. \"transactions\" (string, required) A json array of json objects\n"
" [\n"
" {\n"
" \"txid\":\"id\", (string, required) The transaction id\n"
" \"vout\":n (numeric, required) The output number\n"
" \"sequence\":n (numeric, optional) The sequence number\n"
" }\n"
" ,...\n"
" ]\n"
"2. \"outputs\" (string, required) a json object with outputs\n"
" {\n"
" \"address\": x.xxx (numeric or string, required) The key is the stakework address, the numeric value (can be string) is the " + CURRENCY_UNIT + " amount\n"
" \"data\": x.xxx, (string, required) The key is hex encoded data, the numeric value (can be string) is the " + CURRENCY_UNIT + " amount\n"
" ...\n"
" }\n"
"3. \"strdzeel\" (string, optional) Attached string metadata \n"
"4. \"index\" (numeric, optional, default=-1) If greater than -1, it will only print the raw data of the output or input on the index \"index\"\n"
"4. \"toggle-input-dump\" (bool, optional, default=false) Sets whether the input (true) or the output (false) at the index \"index\" is dumped \n"
"\nResult:\n"
"\"transaction\" (string) hex string of the transaction\n"
"\nExamples\n"
+ HelpExampleCli("createrawtransaction", "\"[{\\\"txid\\\":\\\"myid\\\",\\\"vout\\\":0}]\" \"{\\\"address\\\":0.01}\"")
+ HelpExampleCli("createrawtransaction", "\"[{\\\"txid\\\":\\\"myid\\\",\\\"vout\\\":0}]\" \"{\\\"00010203\\\":\\\"0.01\\\"}\"")
+ HelpExampleRpc("createrawtransaction", "\"[{\\\"txid\\\":\\\"myid\\\",\\\"vout\\\":0}]\", \"{\\\"address\\\":0.01}\"")
+ HelpExampleRpc("createrawtransaction", "\"[{\\\"txid\\\":\\\"myid\\\",\\\"vout\\\":0}]\", \"{\\\"00010203\\\":\\\"0.01\\\"}\"")
);
RPCTypeCheck(params, boost::assign::list_of(UniValue::VARR)(UniValue::VOBJ)(UniValue::VSTR)(UniValue::VNUM), true);
if (params[0].isNull() || params[1].isNull())
throw JSONRPCError(RPC_INVALID_PARAMETER, "Invalid parameter, arguments 1 and 2 must be non-null");
UniValue inputs = params[0].get_array();
UniValue sendTo = params[1].get_obj();
CMutableTransaction rawTx;
if (params.size() > 2 && !params[2].isNull() && !params[2].get_str().empty()) {
rawTx.strDZeel = params[2].get_str();
}
rawTx.nVersion = IsCommunityFundEnabled(chainActive.Tip(),Params().GetConsensus()) ? CTransaction::TXDZEEL_VERSION_V2 : CTransaction::TXDZEEL_VERSION;
int nout = -1;
if (params.size() > 3 && !params[3].isNull()) {
int nOut = params[3].get_int();
if (nOut < -1 || nOut > std::numeric_limits<int>::max())
throw JSONRPCError(RPC_INVALID_PARAMETER, "Invalid parameter, nout out of range");
nout = nOut;
}
int dumpin = false;
if (params.size() > 4 && !params[4].isNull() && params[4].isBool()) {
dumpin = params[4].getBool();
}
rawTx.nTime = GetAdjustedTime();
for (unsigned int idx = 0; idx < inputs.size(); idx++) {
const UniValue& input = inputs[idx];
const UniValue& o = input.get_obj();
uint256 txid = ParseHashO(o, "txid");
const UniValue& vout_v = find_value(o, "vout");
if (!vout_v.isNum())
throw JSONRPCError(RPC_INVALID_PARAMETER, "Invalid parameter, missing vout key");
int nOutput = vout_v.get_int();
if (nOutput < 0)
throw JSONRPCError(RPC_INVALID_PARAMETER, "Invalid parameter, vout must be positive");
uint32_t nSequence = (rawTx.nLockTime ? std::numeric_limits<uint32_t>::max() - 1 : std::numeric_limits<uint32_t>::max());
// set the sequence number if passed in the parameters object
const UniValue& sequenceObj = find_value(o, "sequence");
if (sequenceObj.isNum()) {
int64_t seqNr64 = sequenceObj.get_int64();
if (seqNr64 < 0 || seqNr64 > std::numeric_limits<uint32_t>::max())
throw JSONRPCError(RPC_INVALID_PARAMETER, "Invalid parameter, sequence number is out of range");
else
nSequence = (uint32_t)seqNr64;
}
CTxIn in(COutPoint(txid, nOutput), CScript(), nSequence);
rawTx.vin.push_back(in);
}
set<CStakeWorkAddress> setAddress;
vector<string> addrList = sendTo.getKeys();
for(const string& name_: addrList) {
CStakeWorkAddress address(name_);
if (address.IsValid()) {
if (setAddress.count(address))
throw JSONRPCError(RPC_INVALID_PARAMETER, string("Invalid parameter, duplicated address: ")+name_);
setAddress.insert(address);
CScript scriptPubKey = GetScriptForDestination(address.Get());
CAmount nAmount = AmountFromValue(sendTo[name_]);
CTxOut out(nAmount, scriptPubKey);
rawTx.vout.push_back(out);
} else {
std::vector<unsigned char> data = ParseHex(name_);
CTxOut out(AmountFromValue(sendTo[name_]), CScript(data.begin(), data.end()));
rawTx.vout.push_back(out);
}
}
if (dumpin) {
if(nout > -1 && (unsigned)nout >= rawTx.vin.size())
throw JSONRPCError(RPC_INVALID_PARAMETER, "Invalid parameter, index out of range");
} else
if(nout > -1 && (unsigned)nout >= rawTx.vout.size())
throw JSONRPCError(RPC_INVALID_PARAMETER, "Invalid parameter, index out of range");
return nout > -1 ? (dumpin ? EncodeHexTxIn(rawTx.vin[nout]) : EncodeHexTxOut(rawTx.vout[nout])) : EncodeHexTx(rawTx);
}
UniValue decoderawtransaction(const UniValue& params, bool fHelp)
{
if (fHelp || params.size() != 1)
throw runtime_error(
"decoderawtransaction \"hexstring\"\n"
"\nReturn a JSON object representing the serialized, hex-encoded transaction.\n"
"\nArguments:\n"
"1. \"hex\" (string, required) The transaction hex string\n"
"\nResult:\n"
"{\n"
" \"txid\" : \"id\", (string) The transaction id\n"
" \"hash\" : \"id\", (string) The transaction hash (differs from txid for witness transactions)\n"
" \"size\" : n, (numeric) The transaction size\n"
" \"vsize\" : n, (numeric) The virtual transaction size (differs from size for witness transactions)\n"
" \"version\" : n, (numeric) The version\n"
" \"locktime\" : ttt, (numeric) The lock time\n"
" \"vin\" : [ (array of json objects)\n"
" {\n"
" \"txid\": \"id\", (string) The transaction id\n"
" \"vout\": n, (numeric) The output number\n"
" \"scriptSig\": { (json object) The script\n"
" \"asm\": \"asm\", (string) asm\n"
" \"hex\": \"hex\" (string) hex\n"
" },\n"
" \"txinwitness\": [\"hex\", ...] (array of string) hex-encoded witness data (if any)\n"
" \"sequence\": n (numeric) The script sequence number\n"
" }\n"
" ,...\n"
" ],\n"
" \"vout\" : [ (array of json objects)\n"
" {\n"
" \"value\" : x.xxx, (numeric) The value in " + CURRENCY_UNIT + "\n"
" \"n\" : n, (numeric) index\n"
" \"scriptPubKey\" : { (json object)\n"
" \"asm\" : \"asm\", (string) the asm\n"
" \"hex\" : \"hex\", (string) the hex\n"
" \"reqSigs\" : n, (numeric) The required sigs\n"
" \"type\" : \"pubkeyhash\", (string) The type, eg 'pubkeyhash'\n"
" \"addresses\" : [ (json array of string)\n"
" \"12tvKAXCxZjSmdNbao16dKXC8tRWfcF5oc\" (string) stakework address\n"
" ,...\n"
" ]\n"
" }\n"
" }\n"
" ,...\n"
" ],\n"
" \"strdzeel\" : \"id\", (string) Attached string metadata\n"
"}\n"
"\nExamples:\n"
+ HelpExampleCli("decoderawtransaction", "\"hexstring\"")
+ HelpExampleRpc("decoderawtransaction", "\"hexstring\"")
);
LOCK(cs_main);
RPCTypeCheck(params, boost::assign::list_of(UniValue::VSTR));
CTransaction tx;
if (!DecodeHexTx(tx, params[0].get_str(), true))
throw JSONRPCError(RPC_DESERIALIZATION_ERROR, "TX decode failed");
UniValue result(UniValue::VOBJ);
TxToJSON(tx, uint256(), result);
return result;
}
UniValue decodescript(const UniValue& params, bool fHelp)
{
if (fHelp || params.size() != 1)
throw runtime_error(
"decodescript \"hex\"\n"
"\nDecode a hex-encoded script.\n"
"\nArguments:\n"
"1. \"hex\" (string) the hex encoded script\n"
"\nResult:\n"
"{\n"
" \"asm\":\"asm\", (string) Script public key\n"
" \"hex\":\"hex\", (string) hex encoded public key\n"
" \"type\":\"type\", (string) The output type\n"
" \"reqSigs\": n, (numeric) The required signatures\n"
" \"addresses\": [ (json array of string)\n"
" \"address\" (string) stakework address\n"
" ,...\n"
" ],\n"
" \"p2sh\",\"address\" (string) script address\n"
"}\n"
"\nExamples:\n"
+ HelpExampleCli("decodescript", "\"hexstring\"")
+ HelpExampleRpc("decodescript", "\"hexstring\"")
);
RPCTypeCheck(params, boost::assign::list_of(UniValue::VSTR));
UniValue r(UniValue::VOBJ);
CScript script;
if (params[0].get_str().size() > 0){
vector<unsigned char> scriptData(ParseHexV(params[0], "argument"));
script = CScript(scriptData.begin(), scriptData.end());
} else {
// Empty scripts are valid
}
ScriptPubKeyToJSON(script, r, false);
r.pushKV("p2sh", CStakeWorkAddress(CScriptID(script)).ToString());
return r;
}
/** Pushes a JSON object for script verification or signing errors to vErrorsRet. */
static void TxInErrorToJSON(const CTxIn& txin, UniValue& vErrorsRet, const std::string& strMessage)
{
UniValue entry(UniValue::VOBJ);
entry.pushKV("txid", txin.prevout.hash.ToString());
entry.pushKV("vout", (uint64_t)txin.prevout.n);
entry.pushKV("scriptSig", HexStr(txin.scriptSig.begin(), txin.scriptSig.end()));
entry.pushKV("sequence", (uint64_t)txin.nSequence);
entry.pushKV("error", strMessage);
vErrorsRet.push_back(entry);
}
UniValue signrawtransaction(const UniValue& params, bool fHelp)
{
if (fHelp || params.size() < 1 || params.size() > 4)
throw runtime_error(
"signrawtransaction \"hexstring\" ( [{\"txid\":\"id\",\"vout\":n,\"scriptPubKey\":\"hex\",\"redeemScript\":\"hex\"},...] [\"privatekey1\",...] sighashtype )\n"
"\nSign inputs for raw transaction (serialized, hex-encoded).\n"
"The second optional argument (may be null) is an array of previous transaction outputs that\n"
"this transaction depends on but may not yet be in the block chain.\n"
"The third optional argument (may be null) is an array of base58-encoded private\n"
"keys that, if given, will be the only keys used to sign the transaction.\n"
#ifdef ENABLE_WALLET
+ HelpRequiringPassphrase() + "\n"
#endif
"\nArguments:\n"
"1. \"hexstring\" (string, required) The transaction hex string\n"
"2. \"prevtxs\" (string, optional) An json array of previous dependent transaction outputs\n"
" [ (json array of json objects, or 'null' if none provided)\n"
" {\n"
" \"txid\":\"id\", (string, required) The transaction id\n"
" \"vout\":n, (numeric, required) The output number\n"
" \"scriptPubKey\": \"hex\", (string, required) script key\n"
" \"redeemScript\": \"hex\", (string, required for P2SH or P2WSH) redeem script\n"
" \"amount\": value (numeric, required) The amount spent\n"
" }\n"
" ,...\n"
" ]\n"
"3. \"privatekeys\" (string, optional) A json array of base58-encoded private keys for signing\n"
" [ (json array of strings, or 'null' if none provided)\n"
" \"privatekey\" (string) private key in base58-encoding\n"
" ,...\n"
" ]\n"
"4. \"sighashtype\" (string, optional, default=ALL) The signature hash type. Must be one of\n"
" \"ALL\"\n"
" \"NONE\"\n"
" \"SINGLE\"\n"
" \"ALL|ANYONECANPAY\"\n"
" \"NONE|ANYONECANPAY\"\n"
" \"SINGLE|ANYONECANPAY\"\n"
"\nResult:\n"
"{\n"
" \"hex\" : \"value\", (string) The hex-encoded raw transaction with signature(s)\n"
" \"complete\" : true|false, (boolean) If the transaction has a complete set of signatures\n"
" \"errors\" : [ (json array of objects) Script verification errors (if there are any)\n"
" {\n"
" \"txid\" : \"hash\", (string) The hash of the referenced, previous transaction\n"
" \"vout\" : n, (numeric) The index of the output to spent and used as input\n"
" \"scriptSig\" : \"hex\", (string) The hex-encoded signature script\n"
" \"sequence\" : n, (numeric) Script sequence number\n"
" \"error\" : \"text\" (string) Verification or signing error related to the input\n"
" }\n"
" ,...\n"
" ]\n"
"}\n"
"\nExamples:\n"
+ HelpExampleCli("signrawtransaction", "\"myhex\"")
+ HelpExampleRpc("signrawtransaction", "\"myhex\"")
);
#ifdef ENABLE_WALLET
LOCK2(cs_main, pwalletMain ? &pwalletMain->cs_wallet : nullptr);
#else
LOCK(cs_main);
#endif
RPCTypeCheck(params, boost::assign::list_of(UniValue::VSTR)(UniValue::VARR)(UniValue::VARR)(UniValue::VSTR), true);
vector<unsigned char> txData(ParseHexV(params[0], "argument 1"));
CDataStream ssData(txData, SER_NETWORK, PROTOCOL_VERSION);
vector<CMutableTransaction> txVariants;
while (!ssData.empty()) {
try {
CMutableTransaction tx;
ssData >> tx;
txVariants.push_back(tx);
}
catch (const std::exception&) {
throw JSONRPCError(RPC_DESERIALIZATION_ERROR, "TX decode failed");
}
}
if (txVariants.empty())
throw JSONRPCError(RPC_DESERIALIZATION_ERROR, "Missing transaction");
// mergedTx will end up with all the signatures; it
// starts as a clone of the rawtx:
CMutableTransaction mergedTx(txVariants[0]);
// Fetch previous transactions (inputs):
CCoinsView viewDummy;
CCoinsViewCache view(&viewDummy);
{
LOCK(mempool.cs);
CCoinsViewCache &viewChain = *pcoinsTip;
CCoinsViewMemPool viewMempool(&viewChain, mempool);
view.SetBackend(viewMempool); // temporarily switch cache backend to db+mempool view
for(const CTxIn& txin: mergedTx.vin) {
const uint256& prevHash = txin.prevout.hash;
CCoins coins;
view.AccessCoins(prevHash); // this is certainly allowed to fail
}
view.SetBackend(viewDummy); // switch back to avoid locking mempool for too long
}
bool fGivenKeys = false;
CBasicKeyStore tempKeystore;
if (params.size() > 2 && !params[2].isNull()) {
fGivenKeys = true;
UniValue keys = params[2].get_array();
for (unsigned int idx = 0; idx < keys.size(); idx++) {
UniValue k = keys[idx];
CStakeWorkSecret vchSecret;
bool fGood = vchSecret.SetString(k.get_str());
if (!fGood)
throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Invalid private key");
CKey key = vchSecret.GetKey();
if (!key.IsValid())
throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Private key outside allowed range");
tempKeystore.AddKey(key);
}
}
#ifdef ENABLE_WALLET
else if (pwalletMain)
EnsureWalletIsUnlocked();
#endif
// Add previous txouts given in the RPC call:
if (params.size() > 1 && !params[1].isNull()) {
UniValue prevTxs = params[1].get_array();
for (unsigned int idx = 0; idx < prevTxs.size(); idx++) {
const UniValue& p = prevTxs[idx];
if (!p.isObject())
throw JSONRPCError(RPC_DESERIALIZATION_ERROR, "expected object with {\"txid'\",\"vout\",\"scriptPubKey\"}");
UniValue prevOut = p.get_obj();
RPCTypeCheckObj(prevOut,
{
{"txid", UniValueType(UniValue::VSTR)},
{"vout", UniValueType(UniValue::VNUM)},
{"scriptPubKey", UniValueType(UniValue::VSTR)},
});
uint256 txid = ParseHashO(prevOut, "txid");
int nOut = find_value(prevOut, "vout").get_int();
if (nOut < 0)
throw JSONRPCError(RPC_DESERIALIZATION_ERROR, "vout must be positive");
vector<unsigned char> pkData(ParseHexO(prevOut, "scriptPubKey"));
CScript scriptPubKey(pkData.begin(), pkData.end());
{
CCoinsModifier coins = view.ModifyCoins(txid);
if (coins->IsAvailable(nOut) && coins->vout[nOut].scriptPubKey != scriptPubKey) {
string err("Previous output scriptPubKey mismatch:\n");
err = err + ScriptToAsmStr(coins->vout[nOut].scriptPubKey) + "\nvs:\n"+
ScriptToAsmStr(scriptPubKey);
throw JSONRPCError(RPC_DESERIALIZATION_ERROR, err);
}
if ((unsigned int)nOut >= coins->vout.size())
coins->vout.resize(nOut+1);
coins->vout[nOut].scriptPubKey = scriptPubKey;
coins->vout[nOut].nValue = 0;
if (prevOut.exists("amount")) {
coins->vout[nOut].nValue = AmountFromValue(find_value(prevOut, "amount"));
}
}
// if redeemScript given and not using the local wallet (private keys
// given), add redeemScript to the tempKeystore so it can be signed:
if (fGivenKeys && (scriptPubKey.IsPayToScriptHash() || scriptPubKey.IsPayToWitnessScriptHash())) {
RPCTypeCheckObj(prevOut,
{
{"txid", UniValueType(UniValue::VSTR)},
{"vout", UniValueType(UniValue::VNUM)},
{"scriptPubKey", UniValueType(UniValue::VSTR)},
{"redeemScript", UniValueType(UniValue::VSTR)},
});
UniValue v = find_value(prevOut, "redeemScript");
if (!v.isNull()) {
vector<unsigned char> rsData(ParseHexV(v, "redeemScript"));
CScript redeemScript(rsData.begin(), rsData.end());
tempKeystore.AddCScript(redeemScript);
}
}
}
}
#ifdef ENABLE_WALLET
const CKeyStore& keystore = ((fGivenKeys || !pwalletMain) ? tempKeystore : *pwalletMain);
#else
const CKeyStore& keystore = tempKeystore;
#endif
int nHashType = SIGHASH_ALL;
if (params.size() > 3 && !params[3].isNull()) {
static map<string, int> mapSigHashValues =
boost::assign::map_list_of
(string("ALL"), int(SIGHASH_ALL))
(string("ALL|ANYONECANPAY"), int(SIGHASH_ALL|SIGHASH_ANYONECANPAY))
(string("NONE"), int(SIGHASH_NONE))
(string("NONE|ANYONECANPAY"), int(SIGHASH_NONE|SIGHASH_ANYONECANPAY))
(string("SINGLE"), int(SIGHASH_SINGLE))
(string("SINGLE|ANYONECANPAY"), int(SIGHASH_SINGLE|SIGHASH_ANYONECANPAY))
;
string strHashType = params[3].get_str();
if (mapSigHashValues.count(strHashType))
nHashType = mapSigHashValues[strHashType];
else
throw JSONRPCError(RPC_INVALID_PARAMETER, "Invalid sighash param");
}
bool fHashSingle = ((nHashType & ~SIGHASH_ANYONECANPAY) == SIGHASH_SINGLE);
// Script verification errors
UniValue vErrors(UniValue::VARR);
// Use CTransaction for the constant parts of the
// transaction to avoid rehashing.
const CTransaction txConst(mergedTx);
// Sign what we can:
for (unsigned int i = 0; i < mergedTx.vin.size(); i++) {
CTxIn& txin = mergedTx.vin[i];
const CCoins* coins = view.AccessCoins(txin.prevout.hash);
if (coins == NULL || !coins->IsAvailable(txin.prevout.n)) {
TxInErrorToJSON(txin, vErrors, "Input not found or already spent");
continue;
}
const CScript& prevPubKey = coins->vout[txin.prevout.n].scriptPubKey;
const CAmount& amount = coins->vout[txin.prevout.n].nValue;
SignatureData sigdata;
// Only sign SIGHASH_SINGLE if there's a corresponding output:
if (!fHashSingle || (i < mergedTx.vout.size()))
ProduceSignature(MutableTransactionSignatureCreator(&keystore, &mergedTx, i, amount, nHashType), prevPubKey, sigdata);
// ... and merge in other signatures:
for(const CMutableTransaction& txv: txVariants) {
sigdata = CombineSignatures(prevPubKey, TransactionSignatureChecker(&txConst, i, amount), sigdata, DataFromTransaction(txv, i));
}
UpdateTransaction(mergedTx, i, sigdata);
ScriptError serror = SCRIPT_ERR_OK;
if (!VerifyScript(txin.scriptSig, prevPubKey, mergedTx.wit.vtxinwit.size() > i ? &mergedTx.wit.vtxinwit[i].scriptWitness : nullptr, STANDARD_SCRIPT_VERIFY_FLAGS, TransactionSignatureChecker(&txConst, i, amount), &serror)) {
TxInErrorToJSON(txin, vErrors, ScriptErrorString(serror));
}
}
bool fComplete = vErrors.empty();
UniValue result(UniValue::VOBJ);
result.pushKV("hex", EncodeHexTx(mergedTx));
result.pushKV("complete", fComplete);
if (!vErrors.empty()) {
result.pushKV("errors", vErrors);
}
return result;
}
UniValue sendrawtransaction(const UniValue& params, bool fHelp)
{
if (fHelp || params.size() < 1 || params.size() > 2)
throw runtime_error(
"sendrawtransaction \"hexstring\" ( allowhighfees )\n"
"\nSubmits raw transaction (serialized, hex-encoded) to local node and network.\n"
"\nAlso see createrawtransaction and signrawtransaction calls.\n"
"\nArguments:\n"
"1. \"hexstring\" (string, required) The hex string of the raw transaction)\n"
"2. allowhighfees (boolean, optional, default=false) Allow high fees\n"
"\nResult:\n"
"\"hex\" (string) The transaction hash in hex\n"
"\nExamples:\n"
"\nCreate a transaction\n"
+ HelpExampleCli("createrawtransaction", "\"[{\\\"txid\\\" : \\\"mytxid\\\",\\\"vout\\\":0}]\" \"{\\\"myaddress\\\":0.01}\"") +
"Sign the transaction, and get back the hex\n"
+ HelpExampleCli("signrawtransaction", "\"myhex\"") +
"\nSend the transaction (signed hex)\n"
+ HelpExampleCli("sendrawtransaction", "\"signedhex\"") +
"\nAs a json rpc call\n"
+ HelpExampleRpc("sendrawtransaction", "\"signedhex\"")
);
LOCK(cs_main);
RPCTypeCheck(params, boost::assign::list_of(UniValue::VSTR)(UniValue::VBOOL));
// parse hex string from parameter
CTransaction tx;
if (!DecodeHexTx(tx, params[0].get_str()))
throw JSONRPCError(RPC_DESERIALIZATION_ERROR, "TX decode failed");
uint256 hashTx = tx.GetHash();
CAmount nMaxRawTxFee = maxTxFee;
if (params.size() > 1 && params[1].get_bool())
nMaxRawTxFee = 0;
CCoinsViewCache &view = *pcoinsTip;
const CCoins* existingCoins = view.AccessCoins(hashTx);
bool fHaveMempool = mempool.exists(hashTx);
bool fHaveChain = existingCoins && existingCoins->nHeight < 1000000000;
if (!fHaveMempool && !fHaveChain) {
// push to local node and sync with wallets
CValidationState state;
bool fMissingInputs;
if (!AcceptToMemoryPool(mempool, state, tx, false, &fMissingInputs, false, nMaxRawTxFee)) {
if (state.IsInvalid()) {
throw JSONRPCError(RPC_TRANSACTION_REJECTED, strprintf("%i: %s", state.GetRejectCode(), state.GetRejectReason()));
} else {
if (fMissingInputs) {
throw JSONRPCError(RPC_TRANSACTION_ERROR, "Missing inputs");
}
throw JSONRPCError(RPC_TRANSACTION_ERROR, state.GetRejectReason());
}
}
} else if (fHaveChain) {
throw JSONRPCError(RPC_TRANSACTION_ALREADY_IN_CHAIN, "transaction already in block chain");
}
RelayTransaction(tx);
return hashTx.GetHex();
}
static const CRPCCommand commands[] =
{ // category name actor (function) okSafeMode
// --------------------- ------------------------ ----------------------- ----------
{ "rawtransactions", "getrawtransaction", &getrawtransaction, true },
{ "rawtransactions", "createrawtransaction", &createrawtransaction, true },
{ "rawtransactions", "decoderawtransaction", &decoderawtransaction, true },
{ "rawtransactions", "decodescript", &decodescript, true },
{ "rawtransactions", "sendrawtransaction", &sendrawtransaction, false },
{ "rawtransactions", "signrawtransaction", &signrawtransaction, false }, /* uses wallet if enabled */
{ "blockchain", "gettxoutproof", &gettxoutproof, true },
{ "blockchain", "verifytxoutproof", &verifytxoutproof, true },
};
void RegisterRawTransactionRPCCommands(CRPCTable &tableRPC)
{
for (unsigned int vcidx = 0; vcidx < ARRAYLEN(commands); vcidx++)
tableRPC.appendCommand(commands[vcidx].name, &commands[vcidx]);
}
| [
"akuma@mud.com.cn"
] | akuma@mud.com.cn |
e585e5d4e332f9c2b79ad5ffedbcc746d1c05eaa | ff1f8e352bcbf059e2c1c0aaafff120c56f3cf49 | /Zhengrui/Zhengrui2193.cpp | d1a1ecf8f411a537b1066b3726c0191324b41c04 | [] | no_license | keywet06/code | 040bc189fbabd06fc3026525ae3553cd4f395bf3 | fe0d570144e580f37281b13fd4106438d3169ab9 | refs/heads/master | 2022-12-19T12:12:16.635994 | 2022-11-27T11:39:29 | 2022-11-27T11:39:29 | 182,518,309 | 6 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 1,258 | cpp | #include <bits/stdc++.h>
#define Deb std::cerr
#define Delin Deb << "[Debug] at Line " << __LINE__
#define Debug Delin << " : "
#define Deline Delin << std::endl;
using int64 = long long;
template <typename Type>
class Fenwick {
protected:
std::vector<Type> a;
public:
Fenwick() {}
Fenwick(size_t n) : a(n + 1) {}
void Resize(size_t n) { a = std::vector<Type>(n + 1); }
void Add(size_t i, Type v) {
while (i < a.size()) a[i] += v, i += i & -i;
}
Type Sum(size_t i) {
Type Ret(0);
while (i) Ret += a[i], i &= i - 1;
return Ret;
}
};
int main() {
std::ios::sync_with_stdio(false);
std::cin.tie(nullptr), std::cout.tie(nullptr);
int n, L, R;
std::cin >> n >> L >> R;
std::vector<int> a(n), DD(n + 3);
DD[1] = n, DD[2] = -2 * n, DD[3] = n;
Fenwick<int> Fen(n);
for (int i = 0, x; i < n; ++i) {
std::cin >> x;
int c = i - Fen.Sum(x), d = n - x - c;
++DD[2], --DD[c + 2], ++DD[2], --DD[d + 2], Fen.Add(x, 1);
}
DD[3] -= n;
for (int i = 3; i <= n + 2; ++i) ++DD[i];
int64 D = 0, S = 0, Ans = 0;
for (int i = 1; i <= R; ++i) S += D += DD[i], Ans ^= i >= L ? S : 0;
std::cout << Ans << std::endl;
return 0;
} | [
"keywet06@tom.com"
] | keywet06@tom.com |
4c8c28e0c991b557e45d93775a7369c4b8ceb8cf | 7bd101aa6d4eaf873fb9813b78d0c7956669c6f0 | /PPTShell/PPTShell/DUI/PencelView.h | 84afd185c7282c373d9e814f26ac3dea684a446c | [] | no_license | useafter/PPTShell-1 | 3cf2dad609ac0adcdba0921aec587e7168ee91a0 | 16d9592e8fa2d219a513e9f8cfbaf7f7f3d3c296 | refs/heads/master | 2021-06-24T13:33:54.039140 | 2017-09-10T06:31:11 | 2017-09-10T06:35:10 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 713 | h | #pragma once
#include "InstrumentView.h"
class CPencelViewUI:
public CInstrumentView,
public INotifyUI
{
public:
CPencelViewUI(void);
virtual ~CPencelViewUI(void);
UIBEGIN_MSG_MAP
EVENT_ID_HANDLER(DUI_MSGTYPE_CLICK, _T("color_item"), OnColorItemClick);
UIEND_MSG_MAP
public:
virtual void Init();
protected:
void CreateColors();
void OnColorItemClick( TNotifyUI& msg );
int GetCurSel();
void SetCurSel(int nSel);
public:
virtual void OnSelected();
virtual void OnUnSelected();
virtual void OnPageChangeBefore();
virtual void OnPageScanneded();
private:
CListUI* m_pList;
CDialogBuilder m_ColorBuilder;
HWND m_hScreenWnd;
bool OnBlackboardColorRequest( void* pObj );
};
| [
"794549193@qq.com"
] | 794549193@qq.com |
567b5fe53f63d1c6732f4b6576ac26fa2a5f7bfc | 268775f0cb11043637273305dbb7e3c61a09f42a | /chocoblack.h | 5965a024042e1e988e8606389d18e12af618cc7c | [] | no_license | Sevenium/ChocolateFactory | d4312d24a46f875827d91f47019a4b44c3cd52f7 | 0731f31edc33cd3eb7f9253411eec2aa73b0b9ab | refs/heads/master | 2020-09-30T00:58:49.318654 | 2019-12-10T16:11:27 | 2019-12-10T16:11:27 | 227,161,809 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 233 | h | #ifndef CHOCOBLACK_H
#define CHOCOBLACK_H
#include "chocolate.h"
// SubClass of Chocolate with real values
class ChocoBlack : public Chocolate
{
public:
ChocoBlack():Chocolate("Black",100,160,10,90){}
};
#endif // CHOCOBLACK_H
| [
"bryanhardy@hotmail.fr"
] | bryanhardy@hotmail.fr |
9f57f926a6a6d6937fa899fe2b25a17460e68f17 | b3a042d294a90a1632d38a498a144129a22e7ade | /autograder/ioutils.cpp | d5f66bb8208cabaf57fce7ab72dcfbe22248f6e9 | [] | no_license | swordcyber/stanford-cpp-library | 4f0dd17397dc086add30b28e5a225d920a8f2e8d | cf5de556c65fff91a18aca4c8bb031dc280d4224 | refs/heads/master | 2020-03-30T02:57:14.809006 | 2018-09-26T01:28:40 | 2018-09-26T01:28:40 | 150,660,069 | 1 | 0 | null | 2018-09-27T23:42:13 | 2018-09-27T23:42:12 | null | UTF-8 | C++ | false | false | 3,811 | cpp | /*
* File: ioutils.cpp
* ---------------
* This file contains implementations of functions to help capture, redirect,
* and feed input to cin/cout/err.
* See ioutils.h for documentation of each function.
*
* @author Marty Stepp
* @version 2016/10/28
* - bug fix for output limit static var
* @version 2016/10/22
* - removed all static variables (replaced with STATIC_VARIABLE macros)
* @version 2014/10/14
* @since 2014/03/01
*/
#include "ioutils.h"
#include <fstream>
#include <iostream>
#include <sstream>
#include "consoletext.h"
#include "error.h"
#include "private/echoinputstreambuf.h"
#include "private/limitoutputstreambuf.h"
#include "private/static.h"
namespace ioutils {
STATIC_VARIABLE_DECLARE_BLANK(std::stringstream, bufferOut)
STATIC_VARIABLE_DECLARE(std::streambuf*, oldOut, nullptr)
STATIC_VARIABLE_DECLARE_BLANK(std::stringstream, bufferErr)
STATIC_VARIABLE_DECLARE(std::streambuf*, oldErr, nullptr)
STATIC_VARIABLE_DECLARE_BLANK(std::stringstream, bufferIn)
STATIC_VARIABLE_DECLARE(std::streambuf*, oldIn, nullptr)
STATIC_VARIABLE_DECLARE(bool, consoleEchoUserInput, false)
STATIC_VARIABLE_DECLARE(int, consoleOutputLimit, 0)
void captureStderrBegin() {
STATIC_VARIABLE(bufferErr).str(std::string());
std::streambuf* newBuf;
int limit = getConsoleOutputLimit();
if (limit > 0) {
newBuf = new stanfordcpplib::LimitOutputStreambuf(STATIC_VARIABLE(bufferErr).rdbuf(), limit);
} else {
newBuf = STATIC_VARIABLE(bufferErr).rdbuf();
}
STATIC_VARIABLE(oldErr) = std::cerr.rdbuf(newBuf);
}
std::string captureStderrEnd() {
if (STATIC_VARIABLE(oldErr)) {
std::cerr.rdbuf(STATIC_VARIABLE(oldErr));
STATIC_VARIABLE(oldErr) = nullptr;
}
return STATIC_VARIABLE(bufferErr).str();
}
void captureStdoutBegin(bool alsoStderr) {
STATIC_VARIABLE(bufferOut).str(std::string());
std::streambuf* newBuf;
int limit = getConsoleOutputLimit();
if (limit > 0) {
newBuf = new stanfordcpplib::LimitOutputStreambuf(STATIC_VARIABLE(bufferOut).rdbuf(), limit);
} else {
newBuf = STATIC_VARIABLE(bufferOut).rdbuf();
}
STATIC_VARIABLE(oldOut) = std::cout.rdbuf(newBuf);
if (alsoStderr) {
STATIC_VARIABLE(bufferErr).str(std::string());
STATIC_VARIABLE(oldErr) = std::cerr.rdbuf(newBuf);
}
}
std::string captureStdoutEnd() {
if (STATIC_VARIABLE(oldOut)) {
std::cout.rdbuf(STATIC_VARIABLE(oldOut));
STATIC_VARIABLE(oldOut) = nullptr;
}
if (STATIC_VARIABLE(oldErr)) {
std::cerr.rdbuf(STATIC_VARIABLE(oldErr));
STATIC_VARIABLE(oldErr) = nullptr;
}
return STATIC_VARIABLE(bufferOut).str();
}
bool getConsoleEchoUserInput() {
return STATIC_VARIABLE(consoleEchoUserInput);
}
int getConsoleOutputLimit() {
return STATIC_VARIABLE(consoleOutputLimit);
}
void redirectStdinBegin(std::string userInput) {
STATIC_VARIABLE(bufferIn).str(std::string());
std::streambuf* newBuf;
if (getConsoleEchoUserInput()) {
newBuf = new stanfordcpplib::EchoInputStreambuf(STATIC_VARIABLE(bufferIn).rdbuf());
} else {
newBuf = STATIC_VARIABLE(bufferIn).rdbuf();
}
STATIC_VARIABLE(oldIn) = std::cin.rdbuf(newBuf);
redirectStdinFeedInput(userInput);
}
void redirectStdinFeedInput(std::string userInput) {
if (!userInput.empty()) {
STATIC_VARIABLE(bufferIn) << userInput << std::endl;
}
}
void redirectStdinEnd() {
if (STATIC_VARIABLE(oldIn)) {
std::cin.rdbuf(STATIC_VARIABLE(oldIn));
STATIC_VARIABLE(oldIn) = nullptr;
}
}
void setConsoleEchoUserInput(bool echo) {
STATIC_VARIABLE(consoleEchoUserInput) = echo;
}
void setConsoleOutputLimit(int limit) {
STATIC_VARIABLE(consoleOutputLimit) = limit;
}
} // namespace ioutils
| [
"stepp@cs.stanford.edu"
] | stepp@cs.stanford.edu |
69d8defcea494a57668b92e7cd6af260edb33e1d | aa463fea7a890456f251d1b55242ef1782a71357 | /mytemplate.cpp | 730df5774fb20733268febad561d53c35ab830b3 | [] | no_license | tariqiitju/Contest-code | 8e18eb8996dd24a877fb9bbcb3593098b2ab91af | 651fe97a134f5c38e278a70723a6f694872d1949 | refs/heads/master | 2021-04-27T01:36:52.229896 | 2018-02-23T22:52:55 | 2018-02-23T22:52:55 | 122,678,847 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 5,179 | cpp | #include <bits/stdc++.h>
using namespace std;
#define output freopen("output.txt","w",stdout)
#define input freopen("input.txt","r",stdin)
///C IO
#define pf printf
#define sc scanf
#define pch putchar
#define ssc sscanf
#define spf sprintf
///functions
#define pb push_back
#define Mid(l,r) ((l+r)>>1)
#define present(c,x) ((c).find(x) != (c).end())
#define cpresent(c,x) (find(all(c),x) != (c).end())
#define mp make_pair
#define xx first
#define yy second
///For loop
#define fr0(i,n) for(i=0;i<n;i++)
#define fr1(i,n) for(i=1;i<=n;i++)
#define FOR(a,n) for(auto a : n)
///memory reset
#define Mem(Array,Val,Size) memset(Array,Val,(Size)*(sizeof(Array[0])))
#define set0(x) memset(x,0,sizeof(x))
#define setn1(x) memset(x,-1,sizeof(x))
#define setinf(x) memset(x,127,sizeof(x))
///misc
#define SZ(v) ((int) (v).size())
#define all(v) (v).begin(), (v).end()
///bit operation single variable :: be careful with LL and ULL
#define On(x,i) (x|=(1<<(i)))
#define Off(x,i) (x&= ~(1<<(i)))
#define isOn(x,i) (x&(1<<(i)))
#define Toggle(x,i) (x^=(1<<(i)))
#define tmod(x,i) (x&(~(-1<<i)))
///inputs
template <class T> inline bool In(T &a) {return (bool)(cin>>a);}
template <class T1,class T2> inline bool In(T1 &a,T2 &b){return (bool) (cin>>a>>b);}
template <class T1,class T2,class T3> inline bool In(T1 &a,T2 &b,T3 &c){return (bool)(cin>>a>>b>>c);}
template <class T1,class T2,class T3,class T4> inline bool In(T1 &a,T2 &b,T3 &c,T4 &d){return (bool)(cin>>a>>b>>c>>d);}
inline bool Line(string &a) {return (bool)(getline(cin,a));}
template <class _T>inline void ina(_T a[],int n) {int i; fr0(i,n)In(a[i]);}
///outputs
template <class T> inline bool Pr(T a) {return (bool)(cout<<a);}
template <class T1,class T2> inline bool Pr(T1 a,T2 b) {return (bool)(cout<<a<<" "<<b);}
template <class T1,class T2,class T3> inline bool Pr(T1 a,T2 b,T3 c){return (bool)(cout<<a<<" "<<b<<" "<<c);}
template <class T1,class T2,class T3,class T4> inline bool Pr(T1 a,T2 b,T3 c,T4 d){return (bool)(cout<<a<<" "<<b<<" "<<c<<" "<<d);}
///debug
template <class T> inline void Cr(T a) {cerr<<a<<endl;}
template <class T1,class T2> inline void Cr(T1 a,T2 b){cerr<<a<<" "<<b<<endl;}
#define nln cout<<"\n"
#define sps cout<<" "
int TEST_CASE=0;
#define tcsp cout<<"Case "<<(++TEST_CASE)<<": "
#define tcnl cout<<"Case "<<(++TEST_CASE)<<":\n"
#define FAST ios_base::sync_with_stdio(false);cin.tie(NULL);
#define precice(n) cout<<setprecision(n)
#define FIX(n) cout<<setprecision(n)<<fixed
//data type
typedef long long ll;
typedef unsigned long long ull;
typedef long double LD;
typedef pair<int,int> pii;
typedef pair<ll,ll> pll;
typedef pair<double,double> pdd;
typedef vector<int> vi;
//BIG MOD / mod inverse
template<class _T>inline _T pow(_T a,_T b,_T m){a%=m;_T ans=1%m;while(b){if(b&1)ans*=a,ans%=m;a*=a;a%=m;b>>=1;}return ans;}
template<class _T>inline _T pow(_T a,_T b) {_T ans=1;while(b){if(b&1)ans*=a;a*=a;b>>=1;}return ans;}
template<class _T>inline _T add(_T a,_T b,_T m){return a>=m-b?a-(m-b):a+b;}//a,b<m
template<class _T>inline _T multiply(_T a,_T b,_T m){_T ans=0;if(b>a)swap(a,b);while(b){if(b&1)ans=add(ans,a,m);b>>=1;a=add(a,a,m);}return ans;}//a,b<m
template<class _T>inline _T bigpow(_T a,_T b,_T m){a%=m;_T ans=1%m;while(b){if(b&1)ans=multiply(ans,a,m);a=multiply(a,a,m);b>>=1;}return ans;}
template<class _T>inline _T modinvers(_T a,_T m){return m>2000000000LL?bigpow(a,m-2,m):pow(a,m-2,m);}//m is prime
//egcd / mod inverse
template<class _T> _T _egcd(_T a, _T b, _T &x,_T &y){if(!b){x=1,y=0;return a;}_T _g=_egcd(b,a%b,x,y);_T xt=x;x=y,y=xt-(a/b)*y;return _g;}
template<class _T>inline _T fmodinvers(_T a,_T m){_T x,y;_egcd(a,m,x,y);x%=m;if(x<0)x+=m;return x;} //a,m co-prime
template<class _T>inline _T _lcm(_T a, _T b){return (a*b)/__gcd(a,b);}
template <class T> inline T SQ(T a) {return a*a;}
ll SQRT(ll n){ll e=sqrt(n*1.0);ll l=max(0LL,e-2),r=min(n,e+2);ll ans=0;while(l<=r){ll m=Mid(l,r);if(m*m<=n)ans=m,l=m+1;else r=m-1;}return ans;}
ll CBRT(ll n){ll e=cbrt(n*1.0);ll l=max(0LL,e-2),r=min(n,e+2);ll ans=0;while(l<=r){ll m=Mid(l,r);if(m*m*m<=n)ans=m,l=m+1;else r=m-1;}return ans;}
//direction array
/*
knight: int dx[]={1,-1,1,-1,2,2,-2,-2}; int dy[]={2,2,-2,-2,1,-1,1,-1};
Grid Side: int dx[]={0,0,1,-1};int dy[]={1,-1,0,0};
*/
///constant
const LD EPS = 1e-9;
const LD PI= acos(-1.0);
const int SIZE= 1e6;
ll mod= 1e9+7;
int main()
{
return 0;
}
/**
Md. Tariqul Islam
IIT,JU
fb/tariqiitju
tarik.amtoly@gmail.com
*/
| [
"tarik.amtoly@gmail.com"
] | tarik.amtoly@gmail.com |
8d650b4b31c3e6a0351a477d64a981f4cf099d54 | 780836c70e0a2649ba8b214f8c7f2e8ef034b9a0 | /File_Factory/File_Factory/CsvFile.h | dc49d638975d1739415399eef0dd1493a9354d79 | [
"Apache-2.0"
] | permissive | kboba/s3_File_Factory | cc3c06bf732599a477f2b43ae51b6060276c14e8 | 5640235c963beb96d9f5f9ca577106fa9bd05edc | refs/heads/master | 2022-10-22T20:17:27.695776 | 2020-06-16T22:23:55 | 2020-06-16T22:23:55 | 271,790,925 | 0 | 0 | Apache-2.0 | 2020-06-16T10:10:07 | 2020-06-12T12:17:49 | null | UTF-8 | C++ | false | false | 386 | h | #pragma once
#include "iFile.h"
class CsvFile : public iFile
{
void writeLine(const Point& p);
std::vector<std::string> split(std::string std, char delim);
public:
CsvFile(std::string path, std::string mode);
~CsvFile();
FileError write(const std::vector<Point>& points);
FileError read(std::vector<Point>& points);
FileError read(Point& p, int idx);
};
| [
"boba.krzysztof98@gmail.com"
] | boba.krzysztof98@gmail.com |
675d991e3a17aa5c5704b07716e762dd9fdcfcc1 | e6e1cd3b41ec37ceda61e2e25e87fbb3c6e6030d | /Lista V (C++) - Aula 22/C1_04/Esportista.h | 93f092ba98eadae800dbf4f03ea6ce97b7938976 | [] | no_license | luizalaquini/POO | 1c27a88574ff7aeb6eba1a5fac2f54c07a19c2be | 4ee77776c1a62494a6dce975344338776c25c8cf | refs/heads/main | 2023-04-30T13:50:49.557998 | 2021-05-24T14:45:38 | 2021-05-24T14:45:38 | 349,272,191 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 445 | h | #ifndef ESPORTISTA_H
#define ESPORTISTA_H
#include <iostream>
#include <string>
#include "Pessoa.h"
using namespace std;
class Esportista: public Pessoa {
private:
string time;
public:
Esportista(const string& nome, int idade, double altura, const string& time);
friend ostream& operator<< (ostream&, const Esportista&);
static bool comparaPorTime(const Esportista*, const Esportista*);
};
#endif /* ESPORTISTA_H */ | [
"noreply@github.com"
] | luizalaquini.noreply@github.com |
3bd6f1e890a2deeb7cfaa5c39d5f1f5e7a198a96 | 04b1803adb6653ecb7cb827c4f4aa616afacf629 | /chrome/browser/extensions/api/i18n/i18n_api.cc | fd5a25ff5b1975d278a15f13ee87815a3633a4c7 | [
"BSD-3-Clause"
] | permissive | Samsung/Castanets | 240d9338e097b75b3f669604315b06f7cf129d64 | 4896f732fc747dfdcfcbac3d442f2d2d42df264a | refs/heads/castanets_76_dev | 2023-08-31T09:01:04.744346 | 2021-07-30T04:56:25 | 2021-08-11T05:45:21 | 125,484,161 | 58 | 49 | BSD-3-Clause | 2022-10-16T19:31:26 | 2018-03-16T08:07:37 | null | UTF-8 | C++ | false | false | 2,272 | cc | // Copyright (c) 2012 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "chrome/browser/extensions/api/i18n/i18n_api.h"
#include <algorithm>
#include <string>
#include <vector>
#include "base/lazy_instance.h"
#include "base/stl_util.h"
#include "base/strings/string_piece.h"
#include "base/strings/string_split.h"
#include "chrome/browser/profiles/profile.h"
#include "chrome/common/extensions/api/i18n.h"
#include "components/language/core/browser/pref_names.h"
#include "components/prefs/pref_service.h"
namespace GetAcceptLanguages = extensions::api::i18n::GetAcceptLanguages;
namespace extensions {
namespace {
// Errors.
static const char kEmptyAcceptLanguagesError[] = "accept-languages is empty.";
}
ExtensionFunction::ResponseAction I18nGetAcceptLanguagesFunction::Run() {
std::string accept_languages =
Profile::FromBrowserContext(browser_context())
->GetPrefs()
->GetString(language::prefs::kAcceptLanguages);
// Currently, there are 2 ways to set browser's accept-languages: through UI
// or directly modify the preference file. The accept-languages set through
// UI is guaranteed to be valid, and the accept-languages string returned from
// profile()->GetPrefs()->GetString(language::prefs::kAcceptLanguages) is
// guaranteed to be valid and well-formed, which means each accept-language is
// a valid code, and accept-languages are separated by "," without
// surrrounding spaces. But we do not do any validation (either the format or
// the validity of the language code) on accept-languages set through editing
// preference file directly. So, here, we're adding extra checks to be
// resistant to crashes caused by data corruption.
if (accept_languages.empty())
return RespondNow(Error(kEmptyAcceptLanguagesError));
std::vector<std::string> languages = base::SplitString(
accept_languages, ",", base::TRIM_WHITESPACE, base::SPLIT_WANT_ALL);
base::Erase(languages, "");
if (languages.empty())
return RespondNow(Error(kEmptyAcceptLanguagesError));
return RespondNow(
ArgumentList(GetAcceptLanguages::Results::Create(languages)));
}
} // namespace extensions
| [
"sunny.nam@samsung.com"
] | sunny.nam@samsung.com |
ee06cb2b9e5ac829d491eddfc159774c8b16866f | 5ebb2fea57c526137bd9b4ef2ac32d2853f3137f | /SwordToOffer/29_TwoSum/main.cpp | c12e24b2144bc18cdeaaa946bc57db308890cf4c | [] | no_license | zshellzhang1993-2025/algorithms | 918024b65c4de83bc100e4cfd45c7788ae2c8999 | c90142d33916840efa872c0390bb1d730b9a21cc | refs/heads/master | 2021-05-30T21:13:44.031788 | 2016-01-03T11:01:25 | 2016-01-03T11:01:25 | 28,854,364 | 3 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 926 | cpp | #include <iostream>
#include <vector>
using namespace std;
class Solution_29 {
public:
vector<int> FindNumbersWithSum ( vector<int> array, int sum ) {
vector<int> result;
if ( array.empty() )
return result;
int begin = 0;
int end = array.size() - 1;
while ( begin < end ) {
if ( array[begin] + array[end] == sum ) {
result.push_back ( array[begin] );
result.push_back ( array[end] );
return result;
} else if ( array[begin] + array[end] > sum )
end--;
else
begin++;
}
return result;
}
};
int main() {
int data[9] = {1, 2, 3, 5, 9, 12, 14, 20, 21};
vector<int> array ( data, data + 9 );
Solution_29 s;
vector<int> result = s.FindNumbersWithSum ( array, 4 );
cout << result[0] << " " << result[1];
return 0;
}
| [
"1557983850@qq.com"
] | 1557983850@qq.com |
339d92a59f1c1d6d01f31bed8ff189e6dcf58455 | 3e0725ebd1e7dcb4bb9cb2af7f86a0dceefffa04 | /chrome/browser/vr/ui_scene_constants.h | 70dadfe300ed47e12caa83267df22a77a74b1889 | [
"BSD-3-Clause"
] | permissive | fajarlabs/chromium | 50a25d9240c013d5b266af2bddea973fa01399ea | dec49c8bcb8089e0aebeb7c217276d486a3f4ff4 | refs/heads/master | 2023-01-12T23:47:44.012639 | 2018-04-19T04:15:59 | 2018-04-19T04:15:59 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 13,878 | h | // Copyright 2017 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#ifndef CHROME_BROWSER_VR_UI_SCENE_CONSTANTS_H_
#define CHROME_BROWSER_VR_UI_SCENE_CONSTANTS_H_
#include "ui/gfx/geometry/angle_conversions.h"
namespace vr {
static constexpr float kExitWarningDistance = 0.6f;
static constexpr float kExitWarningTextWidthDMM = 0.44288f;
static constexpr float kExitWarningFontHeightDMM = 0.024576f;
static constexpr float kExitWarningXPaddingDMM = 0.033f;
static constexpr float kExitWarningYPaddingDMM = 0.023f;
static constexpr float kExitWarningCornerRadiusDMM = 0.008f;
static constexpr float kContentDistance = 2.5f;
static constexpr float kContentWidthDMM = 0.96f;
static constexpr float kContentHeightDMM = 0.64f;
static constexpr float kContentWidth = kContentWidthDMM * kContentDistance;
static constexpr float kContentHeight = kContentHeightDMM * kContentDistance;
static constexpr float kContentVerticalOffsetDMM = -0.1f;
static constexpr float kContentVerticalOffset =
kContentVerticalOffsetDMM * kContentDistance;
static constexpr float kContentCornerRadius = 0.005f * kContentWidth;
static constexpr float kContentShadowOffset = 0.09f;
static constexpr float kContentShadowIntesity = 0.4f;
static constexpr float kBackplaneSize = 1000.0f;
static constexpr float kBackgroundDistanceMultiplier = 1.414f;
static constexpr float kFullscreenDistance = 3.0f;
// Make sure that the aspect ratio for fullscreen is 16:9. Otherwise, we may
// experience visual artefacts for fullscreened videos.
static constexpr float kFullscreenHeightDMM = 0.64f;
static constexpr float kFullscreenHeight =
kFullscreenHeightDMM * kFullscreenDistance;
static constexpr float kFullscreenWidth = 1.138f * kFullscreenDistance;
static constexpr float kFullscreenVerticalOffsetDMM = -0.1f;
static constexpr float kFullscreenVerticalOffset =
kFullscreenVerticalOffsetDMM * kFullscreenDistance;
static constexpr float kUrlBarDistance = 2.4f;
static constexpr float kUrlBarHeightDMM = 0.088f;
// This is the non-DMM relative offset of the URL bar. It is used to position
// the DMM root of the URL bar.
static constexpr float kUrlBarRelativeOffset = -0.45f;
// This is the absolute offset of the URL bar's neutral position in DMM.
static constexpr float kUrlBarVerticalOffsetDMM = -0.516f;
static constexpr float kUrlBarRotationRad = gfx::DegToRad(-10.0f);
static constexpr float kUrlBarFontHeightDMM = 0.027f;
static constexpr float kUrlBarButtonSizeDMM = 0.064f;
static constexpr float kUrlBarButtonIconSizeDMM = 0.038f;
static constexpr float kUrlBarEndButtonIconOffsetDMM = 0.0045f;
static constexpr float kUrlBarEndButtonWidthDMM = 0.088f;
static constexpr float kUrlBarSeparatorWidthDMM = 0.002f;
static constexpr float kUrlBarOriginRegionWidthDMM = 0.492f;
static constexpr float kUrlBarOriginRightMarginDMM = 0.020f;
static constexpr float kUrlBarOriginContentOffsetDMM = 0.020f;
static constexpr float kUrlBarItemCornerRadiusDMM = 0.006f;
static constexpr float kUrlBarUrlWidthDMM = kUrlBarOriginRegionWidthDMM -
kUrlBarEndButtonWidthDMM -
kUrlBarOriginRightMarginDMM;
static constexpr float kUrlBarButtonIconScaleFactor =
kUrlBarButtonIconSizeDMM / kUrlBarButtonSizeDMM;
static constexpr float kIndicatorHeightDMM = 0.064f;
static constexpr float kIndicatorIconScaleFactor = 0.55f;
static constexpr float kIndicatorXPaddingDMM = 0.024f;
static constexpr float kIndicatorYPaddingDMM = 0.018f;
static constexpr float kIndicatorCornerRadiusDMM = 0.006f;
static constexpr float kIndicatorOffsetDMM = -0.008f;
static constexpr float kIndicatorMarginDMM = 0.001f;
static constexpr float kIndicatorVerticalOffset = 0.1f;
static constexpr float kIndicatorDistanceOffset = 0.1f;
static constexpr float kIndicatorDepth = 2.4f;
static constexpr float kWebVrToastDistance = 1.0f;
static constexpr float kToastXPaddingDMM = 0.017f;
static constexpr float kToastYPaddingDMM = 0.02f;
static constexpr float kToastCornerRadiusDMM = 0.004f;
static constexpr float kToastTextFontHeightDMM = 0.023f;
static constexpr int kToastTimeoutSeconds = 6;
static constexpr float kPlatformToastVerticalOffset = 0.5f;
static constexpr float kSplashScreenTextDistance = 2.5f;
static constexpr float kSplashScreenTextFontHeightDMM = 0.05f;
static constexpr float kSplashScreenTextWidthDMM = 0.9f;
static constexpr float kSplashScreenTextVerticalOffsetDMM = -0.072f;
static constexpr float kSplashScreenMinDurationSeconds = 2.0f;
static constexpr float kButtonDiameterDMM = 0.088f;
static constexpr float kButtonZOffsetHoverDMM = 0.048f;
static constexpr float kCloseButtonDistance = 2.4f;
static constexpr float kCloseButtonRelativeOffset = -0.8f;
static constexpr float kCloseButtonVerticalOffset =
kFullscreenVerticalOffset - (kFullscreenHeight * 0.5f) - 0.35f;
static constexpr float kCloseButtonDiameter =
kButtonDiameterDMM * kCloseButtonDistance;
static constexpr float kCloseButtonFullscreenDistance = 2.9f;
static constexpr float kCloseButtonFullscreenVerticalOffset =
kFullscreenVerticalOffset - (kFullscreenHeight / 2) - 0.35f;
static constexpr float kCloseButtonFullscreenDiameter =
kButtonDiameterDMM * kCloseButtonFullscreenDistance;
static constexpr float kLoadingIndicatorWidthDMM = 0.24f;
static constexpr float kLoadingIndicatorHeightDMM = 0.008f;
static constexpr float kLoadingIndicatorVerticalOffsetDMM =
(-kUrlBarVerticalOffsetDMM + kContentVerticalOffsetDMM -
kContentHeightDMM / 2 - kUrlBarHeightDMM / 2) /
2;
static constexpr float kSceneSize = 25.0f;
static constexpr float kSceneHeight = 4.0f;
static constexpr int kFloorGridlineCount = 40;
static constexpr float kVoiceSearchCloseButtonDiameterDMM = 0.096f;
static constexpr float kVoiceSearchCloseButtonDiameter =
kVoiceSearchCloseButtonDiameterDMM * kContentDistance;
static constexpr float kVoiceSearchCloseButtonYOffset =
0.316f * kContentDistance + 0.5f * kVoiceSearchCloseButtonDiameter;
static constexpr float kVoiceSearchRecognitionResultTextHeight =
0.026f * kContentDistance;
static constexpr float kVoiceSearchRecognitionResultTextWidth =
0.4f * kContentDistance;
static constexpr float kTimeoutScreenDisatance = 2.5f;
static constexpr float kTimeoutSpinnerSizeDMM = 0.088f;
static constexpr float kTimeoutSpinnerVerticalOffsetDMM =
kSplashScreenTextVerticalOffsetDMM;
static constexpr float kTimeoutMessageHorizontalPaddingDMM = 0.04f;
static constexpr float kTimeoutMessageVerticalPaddingDMM = 0.024f;
static constexpr float kTimeoutMessageCornerRadiusDMM = 0.008f;
static constexpr float kTimeoutMessageLayoutGapDMM = 0.024f;
static constexpr float kTimeoutMessageIconWidthDMM = 0.056f;
static constexpr float kTimeoutMessageIconHeightDMM = 0.056f;
static constexpr float kTimeoutMessageTextFontHeightDMM = 0.022f;
static constexpr float kTimeoutMessageTextHeightDMM = 0.056f;
static constexpr float kTimeoutMessageTextWidthDMM = 0.4f;
static constexpr float kTimeoutButtonDepthOffset = -0.1f;
static constexpr float kTimeoutButtonRotationRad = kUrlBarRotationRad;
static constexpr float kWebVrTimeoutMessageButtonDiameterDMM = 0.096f;
static constexpr float kTimeoutButtonTextWidthDMM = 0.058f;
static constexpr float kTimeoutButtonTextHeightDMM = 0.024f;
static constexpr float kTimeoutButtonTextVerticalOffsetDMM = 0.024f;
static constexpr float kHostedUiHeightRatio = 0.6f;
static constexpr float kHostedUiWidthRatio = 0.6f;
static constexpr float kHostedUiDepthOffset = 0.3f;
static constexpr float kFloatingHostedUiDistance = 0.01f;
static constexpr float kScreenDimmerOpacity = 0.9f;
static constexpr gfx::Point3F kOrigin = {0.0f, 0.0f, 0.0f};
static constexpr float kLaserWidth = 0.01f;
static constexpr float kReticleWidth = 0.025f;
static constexpr float kReticleHeight = 0.025f;
static constexpr float kOmniboxWidthDMM = 0.848f;
static constexpr float kOmniboxHeightDMM = 0.088f;
static constexpr float kOmniboxVerticalOffsetDMM = -0.2f;
static constexpr float kOmniboxTextHeightDMM = 0.032f;
static constexpr float kOmniboxTextMarginDMM = 0.024f;
static constexpr float kOmniboxCloseButtonDiameterDMM = kButtonDiameterDMM;
static constexpr float kOmniboxCloseButtonVerticalOffsetDMM = -0.75f;
static constexpr float kOmniboxCornerRadiusDMM = 0.006f;
static constexpr float kOmniboxCloseButtonDepthOffset = -0.35f;
static constexpr float kOmniboxShadowOffset = 0.07f;
static constexpr float kOmniboxShadowIntensity = 0.4f;
static constexpr int kOmniboxTransitionMs = 300;
static constexpr float kOmniboxTextFieldIconButtonSizeDMM = 0.064f;
static constexpr float kUrlBarButtonHoverOffsetDMM = 0.012f;
static constexpr float kOmniboxTextFieldRightMargin =
((kOmniboxHeightDMM - kOmniboxTextFieldIconButtonSizeDMM) / 2);
static constexpr float kSuggestionHeightDMM = 0.088f;
static constexpr float kSuggestionGapDMM = 0.0018f;
static constexpr float kSuggestionLineGapDMM = 0.01f;
static constexpr float kSuggestionIconSizeDMM = 0.036f;
static constexpr float kSuggestionIconFieldWidthDMM = 0.104f;
static constexpr float kSuggestionRightMarginDMM = 0.024f;
static constexpr float kSuggestionTextFieldWidthDMM =
kOmniboxWidthDMM - kSuggestionIconFieldWidthDMM - kSuggestionRightMarginDMM;
static constexpr float kSuggestionContentTextHeightDMM = 0.024f;
static constexpr float kSuggestionDescriptionTextHeightDMM = 0.020f;
static constexpr float kSuggestionVerticalPaddingDMM = 0.008f;
static constexpr int kControllerFadeInMs = 200;
static constexpr int kControllerFadeOutMs = 550;
static constexpr float kSpeechRecognitionResultTextYOffset = 0.5f;
static constexpr int kSpeechRecognitionResultTimeoutSeconds = 2;
static constexpr int kSpeechRecognitionOpacityAnimationDurationMs = 200;
static constexpr float kModalPromptFadeOpacity = 0.5f;
static constexpr float kKeyboardDistance = 2.2f;
static constexpr float kKeyboardVerticalOffsetDMM = -0.45f;
static constexpr float kKeyboardWebInputOffset = 1.2f;
static constexpr float kSnackbarDistance = 1.5f;
static constexpr float kSnackbarAngle = -gfx::DegToRad(34.0f);
static constexpr float kSnackbarPaddingDMM = 0.032f;
static constexpr float kSnackbarIconWidthDMM = 0.034f;
static constexpr float kSnackbarFontHeightDMM = 0.024f;
static constexpr float kSnackbarHeightDMM = 0.08f;
static constexpr float kSnackbarMoveInAngle = -base::kPiFloat / 10;
static constexpr int kSnackbarTransitionDurationMs = 300;
static constexpr float kControllerLabelSpacerSize = 0.025f;
static constexpr float kControllerLabelLayoutMargin = -0.005f;
static constexpr float kControllerLabelCalloutWidth = 0.02f;
static constexpr float kControllerLabelCalloutHeight = 0.001f;
static constexpr float kControllerLabelFontHeight = 0.05f;
static constexpr float kControllerLabelScale = 0.2f;
// TODO(vollick): these should be encoded in the controller mesh.
static constexpr float kControllerTrackpadOffset = -0.035f;
static constexpr float kControllerExitButtonOffset = -0.008f;
static constexpr float kControllerBackButtonOffset = -0.008f;
static constexpr int kControllerLabelTransitionDurationMs = 700;
static constexpr float kControllerWidth = 0.035f;
static constexpr float kControllerHeight = 0.016f;
static constexpr float kControllerLength = 0.105f;
static constexpr float kControllerSmallButtonSize = kControllerWidth * 0.306f;
static constexpr float kControllerAppButtonZ = kControllerLength * -0.075f;
static constexpr float kControllerHomeButtonZ = kControllerLength * 0.075f;
static constexpr float kSkyDistance = 1000.0f;
static constexpr float kGridOpacity = 0.5f;
static constexpr float kRepositionContentOpacity = 0.2f;
static constexpr float kWebVrPermissionCornerRadius = 0.006f;
static constexpr float kWebVrPermissionLeftPadding = 0.024f;
static constexpr float kWebVrPermissionRightPadding = 0.032f;
static constexpr float kWebVrPermissionTopPadding = 0.026f;
static constexpr float kWebVrPermissionBottomPadding = 0.026f;
static constexpr float kWebVrPermissionMargin = 0.016f;
static constexpr float kWebVrPermissionIconSize = 0.034f;
static constexpr float kWebVrPermissionFontHeight = 0.024f;
static constexpr float kWebVrPermissionTextWidth = 0.380f;
static constexpr float kWebVrPermissionOuterMargin = 0.008f;
static constexpr float kWebVrPermissionDepth = 0.015f;
static constexpr float kWebVrPermissionOffsetStart = 0.3f;
static constexpr float kWebVrPermissionOffsetOvershoot = -0.01f;
static constexpr float kWebVrPermissionOffsetFinal = 0.0f;
static constexpr int kWebVrPermissionOffsetMs = 250;
static constexpr int kWebVrPermissionAnimationDurationMs = 750;
static constexpr float kPromptWidthDMM = 0.63f;
static constexpr float kPromptHeightDMM = 0.218f;
static constexpr float kPromptVerticalOffsetDMM = -0.1f;
static constexpr float kPromptShadowOffsetDMM = 0.1f;
static constexpr float kPromptDistance = 2.4f;
static constexpr float kRepositionCursorBackgroundSize = 1.85f;
static constexpr float kRepositionCursorSize = 1.5f;
static constexpr float kMinResizerScale = 0.5f;
static constexpr float kMaxResizerScale = 1.5f;
static constexpr float kRepositionFrameTopPadding = 0.25f;
static constexpr float kRepositionFrameEdgePadding = 0.04f;
static constexpr float kRepositionFrameHitPlaneTopPadding = 0.5f;
static constexpr float kRepositionFrameTransitionDurationMs = 300;
static constexpr float kOverflowMenuOffset = 0.016f;
static constexpr float kOverflowMenuMinimumWidth = 0.312f;
static constexpr float kOverflowButtonRegionHeight = 0.088f;
static constexpr float kOverflowButtonXOffset = 0.016f;
static constexpr float kOverflowMenuYPadding = 0.012f;
static constexpr float kOverflowMenuItemHeight = 0.080f;
static constexpr float kOverflowMenuItemXPadding = 0.024f;
} // namespace vr
#endif // CHROME_BROWSER_VR_UI_SCENE_CONSTANTS_H_
| [
"commit-bot@chromium.org"
] | commit-bot@chromium.org |
f68a755d42ebebdb7050fae12f734fc7da7b5a05 | ec4897cce9465140a04fb9947c844ed06178ea53 | /entrywriter.cpp | 57daaa5b258ef9a084f948655ba9cd8ad0e37d3a | [] | no_license | vlitomsk/evlog3 | 998c1c9bafaa1f92474b7bd11b3108f812c8a249 | 5c4d98c1ac8ea7b81cb2cc7a71fdab9a8da09f9c | refs/heads/master | 2020-06-30T23:44:57.350015 | 2016-12-14T02:51:51 | 2016-12-14T02:51:51 | 74,561,989 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 371 | cpp | #include "entrywriter.hpp"
EntryWriter::EntryWriter(std::ostream &os)
: os(os)
, first(true)
{}
EntryWriter::~EntryWriter() {
os << "\n]\n";
}
void EntryWriter::operator <<(const Entry &ent) {
if (first) {
os << "[\n";
first = false;
} else {
os << ",\n";
}
os << ent.getStr();
}
void EntryWriter::endOfSequence() {
}
| [
"kvas.omsk@gmail.com"
] | kvas.omsk@gmail.com |
bb423b99f66827cd8017a6a5e2a262fbc160a83c | 03ffeb8290b24d81e8a0beba53a708fb604bc10d | /code/nepal/cc/src/struct.h | 59addc644227c4617defa804439d5b0ee2de6198 | [] | no_license | skn123/Nepal | ab027a1708884c557521ccd111a79c62a75b9ab6 | d1359862484fbd84625e56c7f9e9486e3499dad7 | refs/heads/master | 2021-09-06T11:33:42.966859 | 2018-02-06T03:56:14 | 2018-02-06T03:56:14 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 168 | h | #ifndef _STRUCT_H_
#define _STRUCT_H_
struct inputdata
{
std::string name;
std::string seq;
std::vector<std::vector<float>> pssm;
std::string alseq="";
};
#endif
| [
"yamada@sb.ecei.tohoku.ac.jp"
] | yamada@sb.ecei.tohoku.ac.jp |
14529b44c7d304427412117ee72ec22eaa2a7a93 | ae346c7428306fb4cd47941199c39969574f3f23 | /CodeForces/CF920-D2-B.cpp | 859b9509560d5a7eaf67081354d65e1780a6ca86 | [] | no_license | moh-na/CompetitiveProgramming | 2c6839d6138908fdbccb26c40911a14e93ca2a69 | 71d19e87032ef863b4b772edb714fa02b8bb8b7e | refs/heads/master | 2022-01-21T18:53:23.457943 | 2018-07-21T20:03:24 | 2018-07-21T20:03:24 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,847 | cpp | #include<bits/stdc++.h>
#include <iomanip>
#include <vector>
#include<cstdio>
#include <cstdlib>
#include <complex>
#include <algorithm>
#include <iostream>
#include <set>
#include <cstring>
using namespace std;
#define ll long long
#define pii pair<long long, long long>
#define endl "\n"
#define EPS 1e-7
#define OO 100000000
#define on(i,n) i=i|(1<<n)
#define off(i,n) i=i& (~(1<<n))
typedef complex<double> point;
#define X real()
#define Y imag()
#define vec(a,b) (b-a)
#define angle(a) (atan2(((a).Y),((a).X)))
#define length(a) (hypot(((a).real()),((a).imag())))
#define normalize(a) ((a)/(length(a)))
#define dotp(a,b) ((conj(a)*(b)).real())
#define crossp(a,b) ((conj(a)*(b)).imag())
#define same(a,b) ((dcmp(((a).X),((b).X))==0 )&& (dcmp(((a).Y),((b).Y))==0))
#define lengthSqr(a) (dp((a),(a)))
#define rotateO(p,ang) ((p)*exp(poll(0,ang)))
#define rotateA(p,ang,about) (rotateO(vec(about,p),ang)+about)
#define reflectO(v,m) (conj((v)/(m))*(m))
#define debugme freopen("out.txt","w",stdout)
#define endp return 0;
#define goleft(L,R) L, (L+R)/2 ,idx*2
#define goright(L,R) (L+R)/2+1, R, idx*2+1
const double PI= acos(-1.0);
long double fixAngle(long double A){return A > 1 ? 1 : (A < -1 ? -1 : A);}
double dcmp( double a,double b){return fabs(a-b)<EPS?0 : a>b? 1:-1; }
int pos[200000+5];
int mark[200000+5];
#define ss second
#define ff first
int main(){
int c;
cin>>c;
while(c--){
int n;
cin>>n;
vector<pair<ll,pii>> data(n);
for(int i=0; i<n; i++){
cin>>data[i].ff;
cin>>data[i].ss.ss;
data[i].ss.ff=i;
}
sort(data.begin(),data.end());
ll t=1;
for(int i=0; i<n; i++){
t=max(t,data[i].ff);
if(data[i].ss.ss<t){
cout<<"0 ";
}else{
cout<<t<<" ";
t++;
}
}
cout<<endl;
}
}
| [
"noreply@github.com"
] | moh-na.noreply@github.com |
82326aa9d3d6a6373bad30b6e67a64f9e45c1eec | 9c5ea7c1df4192291e3bec709d2526dfebdf59ae | /_Includes/precomp.h | 5a4474c712e16092e9c3e2a2d96a0348f29a1cfc | [] | no_license | Walter-Haynes/SMB_Unchained | c402741aa8ecde77d7afc7ec9b75626e0aaa7765 | 3e3f32420d4d7cb25d64d421a843b0d9226a15ba | refs/heads/develop | 2023-01-06T17:28:07.449521 | 2020-11-06T07:36:27 | 2020-11-06T07:36:27 | 308,101,067 | 0 | 0 | null | 2020-11-06T07:20:07 | 2020-10-28T18:04:53 | C | UTF-8 | C++ | false | false | 662 | h | // add your external includes to this file instead of to individual .cpp files
#include <GameSettings.h>
//#define SCRWIDTH Game::SCREEN_HEIGHT_PIXELS;
//#define SCRHEIGHT Game::SCREEN_WIDTH_PIXELS;
constexpr int SCRWIDTH = Game::SCREEN_WIDTH_PIXELS;
constexpr int SCRHEIGHT = Game::SCREEN_HEIGHT_PIXELS;
// #define FULLSCREEN
#define ADVANCEDGL // faster if your system supports it
#include <cinttypes>
#include <cmath>
#include <cstdlib>
#include <cassert>
#include <fstream>
#include <cstdio>
extern "C"
{
#include "glew.h"
}
#include "gl.h"
#include "wglext.h"
#include "SDL.h"
#include "FreeImage.h"
#include "template.h"
#include "surface.h" | [
"walter-haynes@outlook.com"
] | walter-haynes@outlook.com |
79dff7c56116a5ac19f9dbb908a1bbccd5b5cd10 | 3cf2add5c4358157fb31390e3c2fc6ebd8ebb9c8 | /Samples_Cplusplus/sample_traverse_directory.cpp | 45e65c0b7be52ef75b308d13393bb541f4fdc556 | [] | no_license | fengbingchun/Linux_Code_Test | 4b4f4eef5805f47f757a2bfae2d598c4ba9788c4 | 87c1a30e2d9d6a8183c44611663593ef1189eded | refs/heads/master | 2023-08-03T12:41:50.793738 | 2023-07-23T05:20:18 | 2023-07-23T05:20:18 | 55,020,430 | 71 | 52 | null | null | null | null | UTF-8 | C++ | false | false | 3,864 | cpp | #include <dirent.h>
#include <string.h>
#include <iostream>
#include <vector>
#include <string>
namespace {
void Usage(const char* exe)
{
fprintf(stderr, "input params error, run this exe as following command line:\n");
fprintf(stderr, "\t%s arg1 arg2 arg3\n", exe);
fprintf(stderr, "\targ1: specify the directory to traverse\n");
fprintf(stderr, "\targ2: type:\n"
"\t\t0: tarverse all files and all directories in directory;\n"
"\t\t1: only tarverse all files, don't include directories in directory;\n"
"\t\t2: only tarverse all directories, don't include files in directory.\n");
fprintf(stderr, "\targ3: optional, filter, default is *, which is don't filter. \n");
fprintf(stderr, "for example(support relative path), only traverse jpg image:\n");
fprintf(stderr, "\t%s ./images 0 .jpg\n", exe);
fprintf(stderr, "##### test fail #####\n");
}
// 遍历指定文件夹下的所有文件,不包括指定文件夹内的文件夹
std::vector<std::string> GetListFiles(const std::string& path, const std::string& exten = "*")
{
std::vector<std::string> list;
list.clear();
DIR* dp = nullptr;
struct dirent* dirp = nullptr;
if ((dp = opendir(path.c_str())) == nullptr) {
return list;
}
while ((dirp = readdir(dp)) != nullptr) {
if (dirp->d_type == DT_REG) {
if (exten.compare("*") == 0)
list.emplace_back(static_cast<std::string>(dirp->d_name));
else
if (std::string(dirp->d_name).find(exten) != std::string::npos)
list.emplace_back(static_cast<std::string>(dirp->d_name));
}
}
closedir(dp);
return list;
}
// 遍历指定文件夹下的所有文件夹,不包括指定文件夹下的文件
std::vector<std::string> GetListFolders(const std::string& path, const std::string& exten = "*")
{
std::vector<std::string> list;
list.clear();
DIR* dp = nullptr;
struct dirent* dirp = nullptr;
if ((dp = opendir(path.c_str())) == nullptr) {
return list;
}
while ((dirp = readdir(dp)) != nullptr) {
if (dirp->d_type == DT_DIR && strcmp(dirp->d_name, ".") != 0 && strcmp(dirp->d_name, "..") != 0) {
if (exten.compare("*") == 0)
list.emplace_back(static_cast<std::string>(dirp->d_name));
else
if (std::string(dirp->d_name).find(exten) != std::string::npos)
list.emplace_back(static_cast<std::string>(dirp->d_name));
}
}
closedir(dp);
return list;
}
// 遍历指定文件夹下的所有文件,包括指定文件夹内的文件夹
std::vector<std::string> GetListFilesR(const std::string& path, const std::string& exten = "*")
{
std::vector<std::string> list = GetListFiles(path, exten);
std::vector<std::string> dirs = GetListFolders(path, exten);
for (auto it = dirs.cbegin(); it != dirs.cend(); ++it) {
std::vector<std::string> cl = GetListFiles(*it, exten);
for (auto file : cl) {
list.emplace_back(*it + "/" + file);
}
}
return list;
}
} // namespace
int main(int argc, char* argv[])
{
if (argc < 3 || argc > 4) {
Usage(argv[0]);
return -1;
}
int type = atoi(argv[2]);
std::string exten = "*";
if (argc == 4) exten = std::string(argv[3]);
std::vector<std::string> vec;
if (type == 0) vec = GetListFilesR(std::string(argv[1]), exten);
else if (type == 1) vec = GetListFiles(std::string(argv[1]), exten);
else if (type == 2) vec = GetListFolders(std::string(argv[1]), exten);
else { Usage(argv[0]); return -1;}
fprintf(stdout, "traverse result: files count: %d\n", vec.size());
for (auto& file : vec) {
fprintf(stderr, "\t%s\n", file.c_str());
}
fprintf(stdout, "===== test success =====\n");
} | [
"fengbingchun@163.com"
] | fengbingchun@163.com |
9e11e113d06c127b82bbc5ddb26af8f79212740c | 86a9081a05b837ad0f0feaf6e003a1cbb276993f | /cg_exercises-cg_exercise_03/cg_exercise_03/cglib/lib/glm/glm/gtx/matrix_interpolation.hpp | 7cf42e984d08e11b2fb8029a9d060cb608e0203a | [
"MIT",
"LicenseRef-scancode-warranty-disclaimer",
"LicenseRef-scancode-happy-bunny",
"LicenseRef-scancode-unknown-license-reference"
] | permissive | flex3r/cg_exercises | e2defd27427c251d5f0f567a8d192af8d87bca3c | 7c4b699a8211ba66710ac2137f0d460933069331 | refs/heads/master | 2020-12-11T14:06:15.052585 | 2018-02-11T13:58:23 | 2018-02-11T13:58:23 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,899 | hpp | /// @ref gtx_matrix_interpolation
/// @file glm/gtx/matrix_interpolation.hpp
/// @author Ghenadii Ursachi (the.asteroth@gmail.com)
///
/// @see core (dependence)
///
/// @defgroup gtx_matrix_interpolation GLM_GTX_matrix_interpolation
/// @ingroup gtx
///
/// @brief Allows to directly interpolate two exiciting matrices.
///
/// <glm/gtx/matrix_interpolation.hpp> need to be included to use these functionalities.
#pragma once
// Dependency:
#include "../glm.hpp"
#if GLM_MESSAGES == GLM_MESSAGES_ENABLED && !defined(GLM_EXT_INCLUDED)
# pragma message("GLM: GLM_GTX_matrix_interpolation extension included")
#endif
namespace glm
{
/// @addtogroup gtx_matrix_interpolation
/// @{
/// Get the axis and angle of the rotation from a matrix.
/// From GLM_GTX_matrix_interpolation extension.
template <typename T, precision P>
GLM_FUNC_DECL void axisAngle(
tmat4x4<T, P> const & mat,
tvec3<T, P> & axis,
T & angle);
/// Build a matrix from axis and angle.
/// From GLM_GTX_matrix_interpolation extension.
template <typename T, precision P>
GLM_FUNC_DECL tmat4x4<T, P> axisAngleMatrix(
tvec3<T, P> const & axis,
T const angle);
/// Extracts the rotation part of a matrix.
/// From GLM_GTX_matrix_interpolation extension.
template <typename T, precision P>
GLM_FUNC_DECL tmat4x4<T, P> extractMatrixRotation(
tmat4x4<T, P> const & mat);
/// Build a interpolation of 4 * 4 matrixes.
/// From GLM_GTX_matrix_interpolation extension.
/// Warning! works only with rotation and/or translation matrixes, scale will generate unexpected results.
template <typename T, precision P>
GLM_FUNC_DECL tmat4x4<T, P> interpolate(
tmat4x4<T, P> const & m1,
tmat4x4<T, P> const & m2,
T const delta);
/// @}
}//namespace glm
#include "matrix_interpolation.inl"
// CG_REVISION 5076130387d5a9915bfcd693bb4e6b142e11aa30
| [
"n1085633848@outlook.com"
] | n1085633848@outlook.com |
7a4dee754b5bb4610c04e0403511ef622681d754 | be07e3597fef471738fd5204b4690320acc07f74 | /src-generated/wxNode_wxPanel.h | 54964d96ecdb686fc661a7979598f2f34f67c247 | [] | no_license | happyhub/wxNode | 7a88e02187ddcbbe88abf111f638e49f87f7b49a | 4c4846656baaba0c9dea275a119d002e7e0f96de | refs/heads/master | 2020-04-09T00:30:08.392946 | 2012-02-09T05:25:31 | 2012-02-09T05:25:31 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,853 | h |
#ifndef _wxNode_wxPanel_h_
#define _wxNode_wxPanel_h_
#include "wxnode.h"
#include "wxNode_wxEvtHandler.h"
class wxNode_wxEvtHandler;
class wxNode_wxNavigationEnabled;
class wxNode_wxWindow;
class wxNode_wxPoint;
class wxNode_wxSize;
class wxNode_wxPanel : public wxPanel, public wxNodeObject, public NodeExEvtHandlerImpl {
public:
static void Init(v8::Handle<v8::Object> target);
static void AddMethods(v8::Handle<v8::FunctionTemplate> target);
virtual v8::Handle<v8::Object> self() { return m_self; }
static bool AssignableFrom(const v8::Handle<v8::String>& className);
static bool AssignableFrom(const char* className);
static v8::Handle<v8::Value> New(const wxPanel* obj);
static v8::Handle<v8::Value> New(const wxNode_wxPanel* obj);
static v8::Handle<v8::Value> NewCopy(const wxPanel& obj);
wxNode_wxPanel();
wxNode_wxPanel(wxWindow* parent, int winid, wxPoint& pos, wxSize& size, long int style, const wxString& name);
wxNode_wxPanel(wxWindow* parent, int winid, wxPoint& pos, wxSize& size, long int style);
wxNode_wxPanel(wxWindow* parent, int winid, wxPoint& pos, wxSize& size);
wxNode_wxPanel(wxWindow* parent, int winid, wxPoint& pos);
wxNode_wxPanel(wxWindow* parent, int winid);
wxNode_wxPanel(wxWindow* parent);
wxNode_wxPanel(wxWindow* parent, int x, int y, int width, int height, long int style, const wxString& name);
wxNode_wxPanel(wxWindow* parent, int x, int y, int width, int height, long int style);
wxNode_wxPanel(wxWindow* parent, int x, int y, int width, int height);
private:
static v8::Handle<v8::Value> _init(const v8::Arguments& args);
static v8::Handle<v8::Value> _Create(const v8::Arguments& args);
static v8::Handle<v8::Value> _InitDialog(const v8::Arguments& args);
static v8::Persistent<v8::FunctionTemplate> s_ct;
};
#endif
| [
"joe@fernsroth.com"
] | joe@fernsroth.com |
1c922ddafad12901d428b5b4e98122f1033d1441 | bc7c30f48c5322cde4d810ff5fb0912ed49150df | /Assignments/PhysicsAssignment2/PhysicsAssignment2/Vec3.h | 900f950975c093b0d90458a571f7a8ffadcc5850 | [] | no_license | DustinBrown917/GamePhysics1 | ca7c1df9c10dda277266e8af22b2a67c7bab8a2f | 936106db5df38a636c9fa0688554943cbfc6ac45 | refs/heads/master | 2020-04-01T15:07:20.942644 | 2018-11-14T00:04:37 | 2018-11-14T00:04:37 | 153,322,126 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,748 | h |
#include <string> // Just for the ToString() method.
using namespace std;
//Guard statement - Prevents Vec3.h from being compiled more than once.
#ifndef VEC3_H
#define VEC3_H
//Vec3 Class Header
struct Vec3 {
//Member variables
float x, y, z;
//Constructors
//Create a Vec3 with all member properties initialized to 0.
Vec3();
//Create a Vec3 with all member properties initialized to val.
Vec3(float val);
//Create a Vec3 and initialize all member properties explicitly.
Vec3(float x, float y, float z);
//Destruct the Vec3
~Vec3();
//Operator overloads
// I inlined the operator overloads because they would generate more overhead if they were called as normal in the cpp.
// They are short and common enough that inlining the operators generates a justifiable improvement in efficiency.
//TS
//Assignment operator. Return a reference to value at this.
inline Vec3& operator = (const Vec3& vec) {
x = vec.x;
y = vec.y;
z = vec.z;
return *this;
}
//Add two different vectors.
inline const Vec3 operator + (const Vec3& vec) const {
return Vec3(x + vec.x, y + vec.y, z + vec.z);
}
//Subtract two different vectors.
inline const Vec3 operator - (const Vec3& vec) const {
return Vec3(x - vec.x, y - vec.y, z - vec.z);
}
//Multiply vector by scalar
inline const Vec3 operator * (const float f) const {
return Vec3(x * f, y * f, z * f);
}
//Divide vector by scalar
//Beware of dividing by extremely small numbers. Will update to handle such cases as the class develops.
inline const Vec3 operator /(const float f) const {
return Vec3(x / f, y / f, z / f);
}
//Add another vector to this and return a reference to itself.
inline Vec3& operator += (const Vec3& vec) {
x += vec.x;
y += vec.y;
z += vec.z;
return *this;
}
//Subtract another vector from this one and return a reference to itself.
inline Vec3& operator -= (const Vec3& vec) {
x -= vec.x;
y -= vec.y;
z -= vec.z;
return *this;
}
//Multiply this vector by float f and return a reference to itself.
inline Vec3& operator *= (float f) {
x *= f;
y *= f;
z *= f;
return *this;
}
//Divide this vector by float f and return a reference to itself.
inline Vec3& operator /= (float f) {
x /= f;
y /= f;
z /= f;
return *this;
}
//Member methods
//Get the magnitude of this Vec3.
float Mag() const;
//Scale the vector so its magnitude is 1.
void Normalize();
//Return the Dot product of this Vec3 given another.
float Dot(const Vec3& other) const;
//Scale a vector between itself and another Vec3 by factor t.
void Lerp(const Vec3& other, float t);
//Rotate a vector around its z axis.
void RotateZ(float angle);
//Get the Vec3 as a string.
string ToString();
};
#endif //!VEC3_H
| [
"43157195+DustinBrown917@users.noreply.github.com"
] | 43157195+DustinBrown917@users.noreply.github.com |
77b6e8ae718e75d4263c4462601b845aeb521380 | 44a1382fbb4f566a933ff2ad3a864d6f6f4dcaf2 | /Best_Time_to_Buy_and_Sell_Stock_II.cpp | 1f36f5286f669f723a20e0e1d52c488b59a9286d | [] | no_license | yashparmar15/Cpp-Codes | e3f15c5f6bb626d5b8e8115a14a3a825ed138630 | 7016ef17f03f9d493ee7866785f27e73b09779e7 | refs/heads/master | 2023-04-19T02:39:19.138477 | 2021-05-09T18:12:55 | 2021-05-09T18:12:55 | 276,151,617 | 2 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,710 | cpp | // Say you have an array prices for which the ith element is the price of a given stock on day i.
// Design an algorithm to find the maximum profit. You may complete as many transactions as you like (i.e., buy one and sell one share of the stock multiple times).
// Note: You may not engage in multiple transactions at the same time (i.e., you must sell the stock before you buy again).
// Example 1:
// Input: [7,1,5,3,6,4]
// Output: 7
// Explanation: Buy on day 2 (price = 1) and sell on day 3 (price = 5), profit = 5-1 = 4.
// Then buy on day 4 (price = 3) and sell on day 5 (price = 6), profit = 6-3 = 3.
// Example 2:
// Input: [1,2,3,4,5]
// Output: 4
// Explanation: Buy on day 1 (price = 1) and sell on day 5 (price = 5), profit = 5-1 = 4.
// Note that you cannot buy on day 1, buy on day 2 and sell them later, as you are
// engaging multiple transactions at the same time. You must sell before buying again.
// Example 3:
// Input: [7,6,4,3,1]
// Output: 0
// Explanation: In this case, no transaction is done, i.e. max profit = 0.
// Constraints:
// 1 <= prices.length <= 3 * 10 ^ 4
// 0 <= prices[i] <= 10 ^ 4
class Solution {
public:
int maxProfit(vector<int>& prices) {
int Profit = 0;
int i = 0;
int N = prices.size();
while(i < N){
int temp = prices[i];
if(i + 1 < N and prices[i + 1] > prices[i]){
while(i + 1 < N and prices[i + 1] > prices[i]){
i++;
}
Profit = Profit + prices[i] - temp;
}
i++;
}
return Profit;
}
};
| [
"noreply@github.com"
] | yashparmar15.noreply@github.com |
7b48930687cccc3afc730d43865eee5b4805aa6b | 7af9c24bb6cea6e77c74990fbdf061bd03c0e779 | /src/acpp/Stack_set.h | cb4f7f914d24c53bd09d498f77d2217fdddb32fa | [] | no_license | dtbinh/sedgewick_cpp | abfca17d774f03cfde912fe5404770fad68a8628 | b488e5df2ad9c855aaaed66397c457dba55a4463 | refs/heads/master | 2023-03-16T09:11:31.240153 | 2017-08-23T23:39:20 | 2017-08-23T23:39:20 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,005 | h | // Program 4.16 - Stack with index items and no duplicates
#ifndef STACK_SET_H
#define STACK_SET_H
#include <cstddef>
#include <vector>
#include <deque>
template<typename Item_t> // Item_t must be an integer type
class Stack_set {
public:
Stack_set(std::size_t size)
: _stack(size),
_size{0},
_on_stack(size, false) {}
inline bool empty() const noexcept { return _size == 0; }
void push(Item_t& item)
{
if (_on_stack[item]) { return; }
_stack[_size++] = item;
_on_stack[item] = true;
}
void push(Item_t&& item)
{
if (_on_stack[item]) { return; }
_stack[_size++] = item;
_on_stack[item] = true;
}
Item_t pop()
{
_on_stack[_stack[--_size]] = false;
return _stack[_size];
}
private:
std::vector<Item_t> _stack;
std::deque<bool> _on_stack; // used to test whether the item is already on the stack
std::size_t _size;
};
#endif // STACK_SET_H
| [
"timothyshull@gmail.com"
] | timothyshull@gmail.com |
078899c9184b7b6016e2bdb8d7a8bc176df51be2 | f5f451c3e1c420789107addacb0da3107685bc4f | /TCMPhysicEngine/stdafx.cpp | ead1df20d5a5f9d319ed91cd4c255d21718e4c34 | [] | no_license | cl4nk/TayCaMead-Engine | 4db6089fd7d952f1aecee82378db0c3bad407c99 | 4e6a9281fbaf9b7708db95a95078e97b5aeb2772 | refs/heads/master | 2021-01-01T19:21:17.655499 | 2019-06-11T09:11:39 | 2019-06-11T09:11:39 | 98,566,424 | 0 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 294 | cpp | // stdafx.cpp : source file that includes just the standard includes
// TCMPhysicEngine.pch will be the pre-compiled header
// stdafx.obj will contain the pre-compiled type information
#include "stdafx.h"
// TODO: reference any additional headers you need in STDAFX.H
// and not in this file
| [
"n.fontes@student.isartdigital.com"
] | n.fontes@student.isartdigital.com |
19ba21ea42085a4c0cd5df1c04eef3928f90725f | de80b91a12b10bd962b59a89b2badbb83a0193da | /ClientProject/Mof/MofLibrary/Include/Graphics/PMD/ConvertPMD.h | 221e955307109d5791c1d5fc9cfca436fc5ca3b0 | [
"MIT"
] | permissive | OIC-Shinchaemin/RatchetNclank-PrivateCopy | 8845eea799b3346646c8c93435c0149e842dede8 | e2e646e89ef3c29d474a503f5ca80405c4c676c9 | refs/heads/main | 2023-08-15T06:36:05.244293 | 2021-10-08T00:34:48 | 2021-10-08T00:34:48 | 350,923,064 | 0 | 0 | MIT | 2021-10-06T11:05:03 | 2021-03-24T02:35:36 | C++ | SHIFT_JIS | C++ | false | false | 17,532 | h | /*****************************************************************************
[ファイル名] ConvertPMD.h
[処理概要] PMDメッシュ変換クラス
Author 濱田 享
Since 2009.04.01
*****************************************************************************/
//ONCE
#ifndef __CONVERTPMDMESH__H__
#define __CONVERTPMDMESH__H__
//INCLUDE
#include "ConvertVMD.h"
namespace Mof {
//TYPEDEF STRUCT
/*******************************//*!
@brief PMDファイルヘッダー構造体
PMDファイルヘッダー構造体。
@author CDW
*//********************************/
typedef struct tag_PMDHEADER {
char Magic[3]; //!<pmd
MofFloat Version; //!<バージョン
char Name[21]; //!<名前
char Comment[257]; //!<コメント
char EName[21]; //!<名前(英語)
char EComment[257]; //!<コメント(コメント)
MofU32 ExpressionCount; //!<表情数
MofU32 BoneFrameCount; //!<ボーン枠数
}PMDHEADER,*LPPMDHEADER;
/*******************************//*!
@brief PMDファイル頂点構造体
PMDファイル頂点構造体。
@author CDW
*//********************************/
typedef MOF_ALIGNED16_STRUCT tag_PMDVERTEX {
Vector3 Pos; //!<座標
Vector3 Normal; //!<法線
Vector2 UV; //!<UV
Vector4 Color[4]; //!<色
MofU8 BlendIndicesCount; //!<ブレンドボーン数
MofU8 BlendIndices[2]; //!<ブレンドインデックス
MofFloat BlendWait[2]; //!<ブレンドウェイト
MofU32 Index; //!<元番号
MOF_ALIGNED_NEW_OPERATOR(tag_PMDVERTEX);
}PMDVERTEX, *LPPMDVERTEX;
//リスト置き換え
typedef CDynamicArray< PMDVERTEX > PMDVERTEXLIST, *LPPMDVERTEXLIST;
/*******************************//*!
@brief PMDファイル頂点リスト構造体
PMDファイル頂点リスト構造体。
@author CDW
*//********************************/
typedef struct tag_PMDMESHVERTEX {
PMDVERTEXLIST VertexList; //!<頂点リスト
MofU32 Flag; //!<頂点フラグ
/*************************************************************************//*!
@brief コンストラクタ
@param None
@return None
*//**************************************************************************/
tag_PMDMESHVERTEX() :
VertexList(),
Flag(0) {
}
tag_PMDMESHVERTEX(const tag_PMDMESHVERTEX& Obj) :
VertexList(Obj.VertexList),
Flag(Obj.Flag) {
}
/*************************************************************************//*!
@brief デストラクタ
@param None
@return None
*//**************************************************************************/
virtual ~tag_PMDMESHVERTEX(){
VertexList.Release();
}
}PMDMESHVERTEX, *LPPMDMESHVERTEX;
/*******************************//*!
@brief Xファイルのマテリアルレンダリングオフセット情報構造体
Xファイルマテリアルレンダリングオフセット情報を読み込むための構造体。
@author CDW
*//********************************/
typedef struct tag_PMDMATERIALOFFSET {
char Name[256]; //!<名前
MofU32 Offset; //!<オフセット
MofU32 RenderFace; //!<描画フェイス
LPPMDVERTEX pRenderVertex; //!<描画頂点
MofU32 RenderVertexCount; //!<描画頂点数
LPMofU32 pRenderIndex; //!<描画インデックス
MofU32 RenderIndexCount; //!<描画インデックス数
/*************************************************************************//*!
@brief コンストラクタ
@param None
@return None
*//**************************************************************************/
tag_PMDMATERIALOFFSET() :
Offset(0) ,
RenderFace(0) ,
pRenderVertex(NULL) ,
RenderVertexCount(0) ,
pRenderIndex(NULL) ,
RenderIndexCount(0) {
memset(Name, 0, sizeof(Name));
}
/*************************************************************************//*!
@brief デストラクタ
@param None
@return None
*//**************************************************************************/
~tag_PMDMATERIALOFFSET(){
MOF_SAFE_FREE(pRenderVertex, "pRenderVertex");
MOF_SAFE_FREE(pRenderIndex, "pRenderIndex");
}
}PMDMATERIALOFFSET,*LPPMDMATERIALOFFSET;
typedef CDynamicArray< LPPMDMATERIALOFFSET > PMDMATERIALOFFSETLIST, *LPPMDMATERIALOFFSETLIST;
/*******************************//*!
@brief PMDファイルボーン構造体
PMDファイルボーン構造体。
@author CDW
*//********************************/
typedef struct tag_PMDBONE {
char Name[24];
Matrix44 GrobalTransform;
Matrix44 LocalTransform;
Matrix44 Offset;
MofS32 BNo;
MofS32 PNo;
MofU16 TNo;
MofU8 Type;
MofU16 IKNo;
}PMDBONE, *LPPMDBONE;
//リスト置き換え
typedef CDynamicArray< PMDBONE > PMDBONELIST, *LPPMDBONELIST;
/*******************************//*!
@brief PMDファイル剛体構造体
PMDファイル剛体構造体。
@author CDW
*//********************************/
typedef MOF_ALIGNED16_STRUCT tag_PMDRIGID {
char Name[24];
Vector3 Size;
Vector3 Pos;
Vector3 Angle;
MofU32 BNo;
MofU32 GNo;
MofU32 GTNo;
MofU32 Type;
MofU32 PType;
MofFloat Mass;
MofFloat LinearDamping;
MofFloat AngularDamping;
MofFloat Restitution;
MofFloat Friction;
MOF_ALIGNED_NEW_OPERATOR(tag_PMDRIGID);
}PMDRIGID, *LPPMDRIGID;
//リスト置き換え
typedef CDynamicArray< PMDRIGID > PMDRIGIDLIST, *LPPMDRIGIDLIST;
/*******************************//*!
@brief PMDファイルモーフィング構造体
PMDファイルモーフィング構造体。
@author CDW
*//********************************/
typedef struct tag_PMDMORPHING {
char Name[24];
MofU32 Count;
MofU32 Type;
CU32Array Index;
CDynamicArray< Vector3 > Vertex;
}PMDMORPHING, *LPPMDMORPHING;
//リスト置き換え
typedef CDynamicArray< LPPMDMORPHING > PMDMORPHINGLIST, *LPPMDMORPHINGLIST;
/*******************************//*!
@brief PMDファイル剛体形状
PMDファイル剛体形状。
@author CDW
*//********************************/
enum tag_PMDRIGIDBODYSHAPE {
PMDRIGIDBODYSHAPE_SPHERE, //!<球
PMDRIGIDBODYSHAPE_BOX, //!<箱
PMDRIGIDBODYSHAPE_CAPSULE, //!<カプセル
};
/*******************************//*!
@brief PMDファイル剛体形状
PMDファイル剛体形状。
@author CDW
*//********************************/
enum tag_PMDRIGIDBODYRELATION {
PMDRIGIDBODYRELATIONTYPE_RELATION, //!<参照優先
PMDRIGIDBODYRELATIONTYPE_RIGID, //!<物理演算
PMDRIGIDBODYRELATIONTYPE_RELATIONPOSITION, //!<参照優先(座標のみ)
};
//CLASS
/*******************************//*!
@brief PMDファイル変換
PMDファイル変換。
@author CDW
*//********************************/
class MOFLIBRARY_API CConvertPMD : public CWriteChunkFile {
private:
/*******************//*!
ファイルヘッダー
*//********************/
LPPMDHEADER m_pHeader;
/*******************//*!
読み込みファイル
*//********************/
LPReadBinaryFile m_pFile;
/*******************//*!
読み込みファイル
*//********************/
LPReadTextFile m_pMaterialFile;
/*******************//*!
モーフィング
*//********************/
PMDMORPHINGLIST m_Morphing;
/*************************************************************************//*!
@brief メッシュファイルを変換する
@param None
@return TRUE 成功<br>
それ以外 失敗、エラーコードが戻り値となる
*//**************************************************************************/
MofBool Convert(void);
/*************************************************************************//*!
@brief メッシュファイルを変換する
@param[in] pVertex 頂点
@return TRUE 成功<br>
それ以外 失敗、エラーコードが戻り値となる
*//**************************************************************************/
MofBool ConvertVertex(LPPMDMESHVERTEX pVertex);
/*************************************************************************//*!
@brief メッシュファイルを変換する
@param[in] pIndex インデックス
@return TRUE 成功<br>
それ以外 失敗、エラーコードが戻り値となる
*//**************************************************************************/
MofBool ConvertFace(LPU32Array pIndex);
/*************************************************************************//*!
@brief メッシュファイルを変換する
@param[in] pVertex 頂点
@param[in] pIndex インデックス
@param[in] pMO マテリアルオフセット
@return TRUE 成功<br>
それ以外 失敗、エラーコードが戻り値となる
*//**************************************************************************/
MofBool ConvertMaterial(LPPMDMESHVERTEX pVertex, LPU32Array pIndex, LPPMDMATERIALOFFSETLIST pMO);
/*************************************************************************//*!
@brief メッシュファイルを変換する
@param[in] pVertex 頂点
@param[in] Flag フラグ
@return TRUE 成功<br>
それ以外 失敗、エラーコードが戻り値となる
*//**************************************************************************/
MofBool ConvertGeometryVertex(LPPMDVERTEX pVertex, MofU32 Flag);
/*************************************************************************//*!
@brief メッシュファイルを変換する
@param[in] pMorphing モーフィング
@param[in] pVertex 頂点
@param[in] pIndex インデックス
@param[in] pMO マテリアルオフセット
@return TRUE 成功<br>
それ以外 失敗、エラーコードが戻り値となる
*//**************************************************************************/
MofBool ConvertMorphing(LPPMDMORPHING pMorphing, LPPMDMESHVERTEX pVertex, LPU32Array pIndex, LPPMDMATERIALOFFSET pMO);
/*************************************************************************//*!
@brief メッシュファイルを変換する
@param[in] pBone ボーン
@param[in] pMO マテリアルオフセット
@return TRUE 成功<br>
それ以外 失敗、エラーコードが戻り値となる
*//**************************************************************************/
MofBool ConvertBone(LPPMDBONELIST pBone, LPPMDMATERIALOFFSETLIST pMO);
/*************************************************************************//*!
@brief メッシュファイルを変換する
@param[in] pBone ボーン
@param[in] pMO マテリアルオフセット
@return TRUE 成功<br>
それ以外 失敗、エラーコードが戻り値となる
*//**************************************************************************/
MofBool ConvertWeight(LPPMDBONE pBone, LPPMDMATERIALOFFSETLIST pMO);
/*************************************************************************//*!
@brief メッシュファイルを変換する
@param[in] pBone ボーン
@return TRUE 成功<br>
それ以外 失敗、エラーコードが戻り値となる
*//**************************************************************************/
MofBool ConvertIK(LPPMDBONELIST pBone);
/*************************************************************************//*!
@brief メッシュファイルを変換する
@param None
@return TRUE 成功<br>
それ以外 失敗、エラーコードが戻り値となる
*//**************************************************************************/
MofBool ConvertExpression(void);
/*************************************************************************//*!
@brief メッシュファイルを変換する
@param None
@return TRUE 成功<br>
それ以外 失敗、エラーコードが戻り値となる
*//**************************************************************************/
MofBool ConvertExpressionViewList(void);
/*************************************************************************//*!
@brief メッシュファイルを変換する
@param None
@return TRUE 成功<br>
それ以外 失敗、エラーコードが戻り値となる
*//**************************************************************************/
MofBool ConvertBoneFrameList(void);
/*************************************************************************//*!
@brief メッシュファイルを変換する
@param None
@return TRUE 成功<br>
それ以外 失敗、エラーコードが戻り値となる
*//**************************************************************************/
MofBool ConvertBoneViewList(void);
/*************************************************************************//*!
@brief メッシュファイルを変換する
@param[in] pBone ボーン
@return TRUE 成功<br>
それ以外 失敗、エラーコードが戻り値となる
*//**************************************************************************/
MofBool ConvertEnglishName(LPPMDBONELIST pBone);
/*************************************************************************//*!
@brief メッシュファイルを変換する
@param None
@return TRUE 成功<br>
それ以外 失敗、エラーコードが戻り値となる
*//**************************************************************************/
MofBool ConvertToonTexture(void);
/*************************************************************************//*!
@brief メッシュファイルを変換する
@param[in] pBone ボーン
@param[in] pRigid 剛体
@return TRUE 成功<br>
それ以外 失敗、エラーコードが戻り値となる
*//**************************************************************************/
MofBool ConvertRigidBody(LPPMDBONELIST pBone, LPPMDRIGIDLIST pRigid);
/*************************************************************************//*!
@brief メッシュファイルを変換する
@param[in] pRigid 剛体
@return TRUE 成功<br>
それ以外 失敗、エラーコードが戻り値となる
*//**************************************************************************/
MofBool ConvertJoint(LPPMDRIGIDLIST pRigid);
/*************************************************************************//*!
@brief ヘッダー読み込み
@param[in] pData 読み込みヘッダ−
@return TRUE 正常終了<br>
それ以外 解放エラー、エラーコードを返す。
*//**************************************************************************/
MofBool ReadHeader(LPPMDHEADER pData);
/*************************************************************************//*!
@brief モーフィング読み込み
@param None
@return TRUE 正常終了<br>
それ以外 解放エラー、エラーコードを返す。
*//**************************************************************************/
MofBool ReadMorphing(void);
public:
/*************************************************************************//*!
@brief コンストラクタ
@param None
@return None
*//**************************************************************************/
CConvertPMD();
/*************************************************************************//*!
@brief デストラクタ
@param None
@return None
*//**************************************************************************/
virtual ~CConvertPMD();
/*************************************************************************//*!
@brief ファイルを開いて解析を行い、独自形式で出力を行う
@param[in] pInName 入力ファイル名
@param[in] pOutName 出力ファイル名
@return TRUE 成功<br>
それ以外 失敗、エラーコードが戻り値となる
*//**************************************************************************/
MofBool Convert(LPCMofChar pInName,LPCMofChar pOutName);
/*************************************************************************//*!
@brief 解放
@param[in] pData 解放追加データ
@return TRUE 正常終了<br>
それ以外 解放エラー、エラーコードを返す。
*//**************************************************************************/
virtual MofBool Release(LPMofVoid pData = NULL);
//クラス基本定義
MOF_LIBRARYCLASS_NOTCOPY(CConvertPMD, MOF_CONVERTPMDCLASS_ID);
};
//INLINE INCLUDE
#include "ConvertPMD.inl"
}
#endif //__CONVERTPMDMESH__H__
//[EOF] | [
"shin@oic.jp"
] | shin@oic.jp |
41e7838aed24679ed4016b9f41791e515a2a5fc1 | f9c465192c40433fc67057471e9173dae3d4a8ca | /05_03/sortarray012.cpp | 5850094b6961106b48b5191e4f8373312121accb | [] | no_license | mlkorra/Prep | f77ebd4867008aaa457a7819e89ea1a2bfc95152 | fe2c4542c864bffae111923101048fb77b962bc9 | refs/heads/master | 2021-03-24T11:57:49.152570 | 2018-07-30T08:58:31 | 2018-07-30T08:58:31 | 107,019,861 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 413 | cpp | #include <bits/stdc++.h>
using namespace std;
void swap(int *a,int *b){
int temp;
temp = *a;
*a = *b;
*b = temp;
}
int main()
{
int t;cin>>t;
while(t--){
int i,j,n;cin>>n;
int v[n];
for(i=0;i<n;i++){
cin>>v[i];
}
for(i=0;i<n;i++){
for(j=0;j<n;j++){
if(v[i]<=v[j]){
swap(&v[i],&v[j]);
}
}
}
for(i=0;i<n;i++){
printf("%d ",v[i]);
}
cout << "\n";
}
return 0;
} | [
"korrarahuldev@gmail.com"
] | korrarahuldev@gmail.com |
4f1613f0ccddd76fd46d2393322883c77637be6f | 18da60961156696d4dfa7368cab91a6ed20cc223 | /Source/RRM/LinkAdaptation/LinkAdaptation.h | d0b88addc9af0e97f2c44894df785729b372dc33 | [] | no_license | Snorlaxgithub/4g-lte | d377dfb59657152f595a36589bea1c5490950ed2 | 55d15c04bccb847622da5c25e65669f1ee7f00d9 | refs/heads/master | 2020-03-27T10:02:09.798542 | 2013-11-20T19:11:55 | 2013-11-20T19:11:55 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,350 | h | /**
* @file LinkAdaptation.h
* Name: 3G LTE System Simulator
* @author Guilherme Silveira Rabelo
* Date: 03/12/2008
*
* This file is part of the undergraduate final project, under the supervision
* of Robson Domingos and Paulo Portela.
*
* @author_2 Luiz Gustavo da Silva Carvalho
* @author_3 Marcos Samuel Santos Ouriques
* Date: 09/01/2012 (Month/Day/Year)
*
* This file is also a part of the undergraduate final project, under the supervision
* of Andre Noll Barreto.
*/
#ifndef _LinkAdaptation_h_
#define _LinkAdaptation_h_
#include <itpp/itbase.h>
#include "User.h"
#include "PhysicalResourceBlock.h"
using namespace itpp;
using namespace std;
/**
* LinkAdaptation Namespace.
* Detailed Description.
*/
namespace LinkAdaptation
{
enum MCS_e
{
MCS1,
MCS2,
MCS3,
MCS4,
MCS5,
MCS6,
MCS7,
MCS8,
MCS9
};
/**
* LinkAdaptation Class.
* Detailed Description.
*/
class LinkAdaptation
{
public:
/**
* Destructor.
* Left empty.
*/
~LinkAdaptation();
/**
* Interface.
* Sinlgetown instance of the class.
*/
static LinkAdaptation* getInstance();
/**
* Interface.
* Initializes numberMCSs_, BERt_, codingRate_, betas_ and MCSThresholds_.
*/
void setParameters();
/**
* Interface.
* Left empty.
*/
void initialize();
/**
* Interface.
* Detailed description.
*/
void clear();
/**
* Interface.
* Detailed description.
*/
double mapSINRs( const vec& sinrs,
const int MCS );
/**
* Interface.
* Detailed description.
*/
void chooseMCS( vec sinrs,
double& sinr,
int& MCS,
int& rawBits,
double& effectiveBits );
/**
* Interface.
* Detailed description.
*/
double getBER( const double sinr,
const int MCS );
/**
* Interface.
* Detailed description.
*/
bool isBERvalid( const double BER );
/**
* Interface.
* Where effectively happens the transmission, according to MCS.
*/
void setBits( const int MCS,
int& rawBits,
double& effectiveBits );
/**
* Interface.
* Detailed description.
*/
bool checkMCS( vec sinrs,
int MCS );
private:
/**
* Constructor.
* Left empty.
*/
LinkAdaptation();
/**
* Member.
* Left empty.
*/
static LinkAdaptation* instance_;
/**
* Member.
* Left empty.
*/
vec betas_;
/**
* Member.
* Left empty.
*/
vec MCSThresholds_;
/**
* Member.
* Equals to 3.
*/
int numberMCSs_;
/**
* Member.
* Equals to 1e-6.
*/
double BERt_;
/**
* Member.
* Left empty.
*/
double codingRate_;
};
};
#endif
| [
"marcos.samuel@gmail.com"
] | marcos.samuel@gmail.com |
4564d52d10c333a63137b207b1109fc6efe2f17e | e92afca02bd03aa5d8d92147fa854c51d0bd4705 | /src/node_main.cc | 5091594db413034b177c0b657731d921b2690c98 | [
"ICU",
"LicenseRef-scancode-unicode",
"NAIST-2003",
"MIT",
"ISC",
"LicenseRef-scancode-public-domain",
"NTP",
"Artistic-2.0",
"BSD-3-Clause",
"BSD-2-Clause",
"Zlib",
"LicenseRef-scancode-unknown-license-reference",
"LicenseRef-scancode-openssl"
] | permissive | ajamshed/node.js | 18725a630c82b5188ec43929be6330c17ef8e496 | 9faeacbd97a09024ee984a0140f7dac2af74bc20 | refs/heads/master | 2021-08-28T17:18:28.712229 | 2017-12-12T22:31:47 | 2017-12-12T22:31:47 | 113,892,329 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,129 | cc | #include "node.h"
#ifdef _WIN32
#include <VersionHelpers.h>
#include <WinError.h>
int wmain(int argc, wchar_t *wargv[]) {
if (!IsWindows7OrGreater()) {
fprintf(stderr, "This application is only supported on Windows 7, "
"Windows Server 2008 R2, or higher.");
exit(ERROR_EXE_MACHINE_TYPE_MISMATCH);
}
// Convert argv to to UTF8
char** argv = new char*[argc + 1];
for (int i = 0; i < argc; i++) {
// Compute the size of the required buffer
DWORD size = WideCharToMultiByte(CP_UTF8,
0,
wargv[i],
-1,
nullptr,
0,
nullptr,
nullptr);
if (size == 0) {
// This should never happen.
fprintf(stderr, "Could not convert arguments to utf8.");
exit(1);
}
// Do the actual conversion
argv[i] = new char[size];
DWORD result = WideCharToMultiByte(CP_UTF8,
0,
wargv[i],
-1,
argv[i],
size,
nullptr,
nullptr);
if (result == 0) {
// This should never happen.
fprintf(stderr, "Could not convert arguments to utf8.");
exit(1);
}
}
argv[argc] = nullptr;
// Now that conversion is done, we can finally start.
return node::Start(argc, argv);
}
#else
// UNIX
extern "C" {
int node_mtcp_init_wrapper();
}
int main(int argc, char *argv[]) {
// Disable stdio buffering, it interacts poorly with printf()
// calls elsewhere in the program (e.g., any logging from V8.)
setvbuf(stdout, nullptr, _IONBF, 0);
setvbuf(stderr, nullptr, _IONBF, 0);
if (node_mtcp_init_wrapper() < 0) {
printf("Failed to initialized mtcp_wrapper\n");
exit(1);
}
return node::Start(argc, argv);
}
#endif
| [
"ajamshed@ndsl.kaist.edu"
] | ajamshed@ndsl.kaist.edu |
b15688c875a4660140c9e800aa40da02977c6729 | 10c0a8cb0899692014417ef60093ace05e5e1763 | /include/RMsg_Ping.i | 8b329294c78ba907e31b08b3c847d7014d85819e | [
"BSD-3-Clause"
] | permissive | openunderlight/ULServer | 56cb96360c57598be6f72f2a20c41f69b41b56bd | 42e12e245506e6a76c3905d64378eff79c908fc5 | refs/heads/dev | 2023-03-10T22:50:51.591229 | 2023-01-31T20:27:44 | 2023-01-31T20:27:44 | 145,008,033 | 7 | 5 | NOASSERTION | 2019-12-24T19:08:59 | 2018-08-16T15:40:15 | TSQL | UTF-8 | C++ | false | false | 427 | i | // RMsg_Ping.i -*- C++ -*-
// $Id: RMsg_Ping.i,v 1.3 1997-07-18 17:26:00-07 jason Exp $
// Copyright 1996-1997 Lyra LLC, All rights reserved.
//
// conditionally inline methods/functions
#ifndef USE_DEBUG
INLINE void RMsg_Ping::Dump(FILE*, int) const
{
// empty
}
#endif /* !USE_DEBUG */
INLINE int RMsg_Ping::Nonce() const
{
return data_.nonce;
}
INLINE void RMsg_Ping::SetNonce(int nonce)
{
data_.nonce = nonce;
}
| [
"root@underlightlyra.(none)"
] | root@underlightlyra.(none) |
594fe263bec14a62807954ceed574c68b196184f | 6e6d008c24d8540e28a3dd6b51a7387d7c700921 | /Vision week 3&4/Vision_timer/BinaryYellow.cpp | 4b7a36b1bd517cc9cef247404d613cd74e723890 | [] | no_license | bryanbaan/Themaopdracht-07---Lokalisatie-2 | a8a9c4779e4f3054ce98b6c5835c7ada64a4b711 | e3490029d6b67f97ba96b0c5bcb2226bd44b0e2c | refs/heads/master | 2021-01-22T17:58:45.149697 | 2014-04-14T12:31:49 | 2014-04-14T12:31:49 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,099 | cpp | #include "BinaryYellow.h"
//AUTHOR Lars Veenendaal
BinaryYellow::BinaryYellow() {
bt = new BaseTimer();
}
BinaryYellow::~BinaryYellow() {
delete bt;
}
void BinaryYellow::CreateBinaryImage(Image &sourceImage, Image &destinationImage) {
bt->reset();
bt->start();
if (sourceImage.GetWidth() != destinationImage.GetWidth() && sourceImage.GetHeight() != destinationImage.GetHeight()) {
std::cout << "Error images are not the same size" << std::endl;
return;
}
for (int y = sourceImage.GetHeight() - 1; y >= 0; y--) {
for (int x = sourceImage.GetWidth() - 1; x >= 0; x--) {
// red = 130 -255
// Green = 80 -255
// Blue = 0 -85
if (((int)sourceImage.GetPixelRed(x, y) >= 130) && ((int)sourceImage.GetPixelGreen(x, y) >= 80) && ((int)sourceImage.GetPixelBlue(x, y) <= 85)){
destinationImage.SetPixel(x, y, 0xFFFFFFFF);
}
else{
destinationImage.SetPixel(x, y, 0x000000FF);
}
}
}
bt->stop();
std::cout << "Time for the binary yellow function: " << bt->elapsedMicroSeconds() << " Microseconds (" << bt->elapsedMilliSeconds() << "ms)" << std::endl;
}
| [
"chanan_van_ooijen13_7@hotmail.com"
] | chanan_van_ooijen13_7@hotmail.com |
7e007c9098cb1459535979fd19534ec51af5fe84 | 80a4bea7acdfb6ce22f2d1b0b0603c418dd85fc9 | /OpenGL/src/GLObject/VertexBufferLayout/VertexBufferLayout.cpp | 99b73f477f33814e19ff3bd9a00d568b56225b4d | [
"MIT"
] | permissive | dusko2/OpenGL | 859dd5a191cc5230a85c2f66407f89afc0919c68 | 3610f83698a0ddc54760afef1e90822adf8d16db | refs/heads/master | 2023-03-19T22:16:17.536614 | 2021-02-26T19:01:17 | 2021-02-26T19:01:17 | 340,934,579 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 919 | cpp | #include <glad/glad.h>
#include "VertexBufferLayout.h"
VertexBufferLayout::VertexBufferLayout() : stride(0) {}
template<>
void VertexBufferLayout::Add<float>(uint32 count, bool normalized) {
elements.push_back({ GL_FLOAT, count, normalized });
stride += count * sizeof(float);
}
template<>
void VertexBufferLayout::Add<uint32>(uint32 count, bool normalized) {
elements.push_back({ GL_UNSIGNED_INT, count, normalized });
stride += count * sizeof(uint32);
}
template <>
void VertexBufferLayout::Add<uint8>(uint32 count, bool normalized) {
elements.push_back({ GL_UNSIGNED_BYTE, count, normalized });
stride += count * sizeof(uint8);
}
template void VertexBufferLayout::Add<float>(uint32 count, bool normalized = false);
template void VertexBufferLayout::Add<uint32>(uint32 count, bool normalized = false);
template void VertexBufferLayout::Add<uint8>(uint32 count, bool normalized = false);
| [
"mirkovic.dusko.16@sinergija.com"
] | mirkovic.dusko.16@sinergija.com |
d1da66b2796bd59ad37d39324a7c68d2e9e82ab7 | ec4711e5444c280fc4fcd6505d5c0acca0627d55 | /hermit/scrollcom.h | 085aebe0a1a52ffb76185604950006e39f399533 | [
"LicenseRef-scancode-warranty-disclaimer",
"LicenseRef-scancode-unknown-license-reference",
"MIT"
] | permissive | ancientlore/hermit | 18f605d1cc8f145c6d936268c9139c92f6182590 | 0b6b5b3e364fe9a7080517a7f3ddb8cdb03f5b14 | refs/heads/master | 2020-05-16T21:02:57.517459 | 2012-01-26T00:17:12 | 2012-01-26T00:17:12 | 3,269,934 | 2 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,782 | h | // Scrollable COM Custom Viewer class
// Copyright (C) 1997 Michael D. Lore All Rights Reserved
#ifndef SCROLLCOM_H
#define SCROLLCOM_H
#include "console/scrollable.h"
#include "console/screen.h"
#include "hmtobjs.h"
class ScrollCOM : public Scrollable {
const CLSID& mClass;
IHermitScrollable *mpInterface;
const char *mpCompName;
public:
// All of these can throw exceptions from the component's failure.
// The COMScroller class catches these.
ScrollCOM (const CLSID& classid, const char *compName = "<unknown>");
virtual ~ScrollCOM ();
virtual int isAtHome () const; // returns whether cursor is at beginning
virtual int isAtEnd () const; // returns whether cursor is at end
virtual int moveCursor (int count); // returns amount it actually moved; negative to go up
virtual int home (); // returns how much the cursor moved to get there
virtual int end (); // returns how much the cursor moved to get there
// The convention with these is to return "empty" values when the position is bogus
// The lines do NOT need to be padded on the right, but the attributes must fill the whole thing
virtual int getText (int pos, char *line, int width) const; // pos relative to cursor
virtual void getAttributes (int pos, WORD *attrs, int width) const; // pos relative to cursor
// Extra methods specific to ScrollCOM
void showFile (const char *filename); // should be called after construction
int processEvent (int key, DWORD data, int& redraw); // returns 1 if the key was handled
int getStatusText (char *line, int width) const; // returns 1 if status to be drawn
void positionCursor (int absolutePos); // should redraw
};
#endif
| [
"michael.lore@gmail.com"
] | michael.lore@gmail.com |
aa5d2677f30a0759a5839a283a7b403b2f8eed40 | a92b18defb50c5d1118a11bc364f17b148312028 | /src/prod/src/Hosting2/NonActivatedApplicationHost.h | b9345e32c4cb4358dd68cc3e6a89a7c675619eb5 | [
"MIT"
] | permissive | KDSBest/service-fabric | 34694e150fde662286e25f048fb763c97606382e | fe61c45b15a30fb089ad891c68c893b3a976e404 | refs/heads/master | 2023-01-28T23:19:25.040275 | 2020-11-30T11:11:58 | 2020-11-30T11:11:58 | 301,365,601 | 1 | 0 | MIT | 2020-11-30T11:11:59 | 2020-10-05T10:05:53 | null | UTF-8 | C++ | false | false | 1,719 | h | // ------------------------------------------------------------
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License (MIT). See License.txt in the repo root for license information.
// ------------------------------------------------------------
#pragma once
namespace Hosting2
{
class NonActivatedApplicationHost :
public ApplicationHost
{
public:
NonActivatedApplicationHost(
std::wstring const & hostId,
KtlSystem *,
std::wstring const & runtimeServiceAddress);
virtual ~NonActivatedApplicationHost();
static Common::ErrorCode NonActivatedApplicationHost::Create(
KtlSystem *,
std::wstring const & runtimeServiceAddress,
__out ApplicationHostSPtr & applicationHost);
static Common::ErrorCode NonActivatedApplicationHost::Create2(
KtlSystem *,
std::wstring const & runtimeServiceAddress,
std::wstring const & hostId,
__out ApplicationHostSPtr & applicationHost);
protected:
virtual Common::ErrorCode OnCreateAndAddFabricRuntime(
FabricRuntimeContextUPtr const & fabricRuntimeContextUPtr,
Common::ComPointer<IFabricProcessExitHandler> const & fabricExitHandler,
__out FabricRuntimeImplSPtr & fabricRuntime);
virtual Common::ErrorCode OnGetCodePackageActivationContext(
CodePackageContext const & codeContext,
__out CodePackageActivationContextSPtr & codePackageActivationContext);
virtual Common::ErrorCode OnUpdateCodePackageContext(
CodePackageContext const & codeContext);
};
}
| [
"noreply-sfteam@microsoft.com"
] | noreply-sfteam@microsoft.com |
5c78d634cb27994fcb03a2dbb68c17d4e52dee90 | d85fa954775b1bf2ecca0d3291cbe3df408ed1ce | /homework_lection_6/alloc.cpp | f83f3f762c4679c7930c875198a401b4a5f06601 | [] | no_license | cojuer/advanced_cpp_2018 | 546a73f6e18aa57bb997543cd9448a1425ccfcca | 4655b5ad39506af2d3e34b4c063cd3347c8e967c | refs/heads/master | 2020-03-29T07:31:37.994210 | 2018-12-24T08:20:02 | 2018-12-24T08:20:02 | 149,668,502 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,253 | cpp | #include <iostream>
#include <vector>
#define STACK_SIZE 40
template <class T>
struct TestAllocator {
public:
using value_type = T;
T* allocate (size_t n)
{
if (n == 0) return nullptr;
if (!m_is_buf_used && n * sizeof(T) < STACK_SIZE) {
std::cout << "alloc " << n * sizeof(T) << " static memory at " << (void*)m_buf << std::endl;
m_is_buf_used = true;
return (T*)(m_buf);
}
void* mem = operator new(n * sizeof(T));
std::cout << "alloc " << n * sizeof(T) << " dynamic memory at " << mem << std::endl;
return (T*)mem;
}
void deallocate (void* p, size_t)
{
if (p == m_buf) {
std::cout << "dealloc static memory at " << p << std::endl;
m_is_buf_used = false;
}
else if (p) {
operator delete(p);
std::cout << "dealloc dynamic memory at " << p << std::endl;
}
}
private:
char m_buf[STACK_SIZE];
bool m_is_buf_used = false;
};
int main(void)
{
std::vector<int, TestAllocator<int>> vec;
vec.push_back(1);
vec.push_back(2);
vec.push_back(3);
vec.push_back(4);
return 0;
}
| [
"akovalev@arccn.ru"
] | akovalev@arccn.ru |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.